DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
ver0.5.0-dev
Bingxi Zhao16bc0f46560a
diff --git a/.env.example b/.env.exampleindex ea835b1c4..aeec7bfad 100644--- a/.env.example+++ b/.env.example@@ -1,210 +1,115 @@-# ============================================================================-# Deep-Tutor Environment Configuration-# ============================================================================-# Copy this file to .env and fill in your API keys and settings.-# All API keys should be kept confidential and never committed to version control.-# You can adjust the max_token parameters in DeepTutor/config/agents.yaml.-# ============================================================================--# ============================================================================-# Server Configuration-# ============================================================================-# Configure the server ports and API URL for remote access.--# Backend API port (default: 8001)-# BACKEND_PORT=8001--# Frontend web port (default: 3782)-# FRONTEND_PORT=3782--# Frontend API Base URL (for remote/LAN access)-# Set this when accessing DeepTutor from another device on your network.-# Example: If your server IP is 192.168.1.100, set:-# NEXT_PUBLIC_API_BASE=http://192.168.1.100:8001-# If not set, defaults to http://localhost:8001 (only works on the local machine)--# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001 (optional)--# ============================================================================-# LLM Deployment Mode Configuration-# ============================================================================-# Control how DeepTutor selects LLM providers.-#-# Options:-# - hybrid (default): Use both API and Local providers. Active provider takes priority.-# - api: Only use cloud API providers (OpenAI, Anthropic, DeepSeek, etc.)-# - local: Only use local/self-hosted providers (Ollama, LM Studio, vLLM, etc.)-#-# In hybrid mode, you can add both API and local providers via the Settings UI,-# and switch between them by setting one as "active".--LLM_MODE=hybrid--# ============================================================================-# LLM (Large Language Model) Configuration-# ============================================================================-# Configure the main AI model used for reasoning, generation, and conversation.-# Supports OpenAI-compatible APIs (OpenAI, Azure OpenAI, DeepSeek, Qwen, etc.)-# and local servers (Ollama, LM Studio, vLLM, llama.cpp).-#-# Note: These environment variables serve as the default/fallback configuration.-# You can also add providers via the Settings UI, which takes priority when active.--# LLM service provider type-# Options: openai, azure_openai, ollama, anthropic+# ==============================================================================+# DeepTutor Environment Configuration+# ==============================================================================+# Copy this file to `.env` and fill in the values.+# Required fields are marked with [Required], optional fields with [Optional].++# ==============================================================================+# Server Ports+# ==============================================================================++# [Optional] Backend API server port+BACKEND_PORT=8001++# [Optional] Frontend server port+FRONTEND_PORT=3782++# ==============================================================================+# LLM Configuration (Large Language Model)+# ==============================================================================+# Primary LLM for all AI operations (chat, research, solve, etc.)++# [Required] Provider binding: openai, azure_openai, anthropicLLM_BINDING=openai-# Model name for the LLM-# Cloud examples: gpt-4o, gpt-4o-mini, deepseek-chat, claude-3-5-sonnet-20241022-# Local examples: llama3.2, qwen2.5, mistral-nemo, deepseek-r1-LLM_MODEL=--# LLM API endpoint URL-# Cloud examples:-# - 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-# - vLLM: http://localhost:8000/v1-# - llama.cpp: http://localhost:8080/v1-LLM_HOST=--# LLM API authentication key-# Required for cloud APIs, optional for local deployment-# For Ollama, you can use any string (e.g., "ollama")-LLM_API_KEY=--# API version for Azure OpenAI (e.g., 2024-02-15-preview)-# Required only when LLM_BINDING=azure_openai-LLM_API_VERSION=+# [Required] Model name (e.g., gpt-4o, deepseek-chat, claude-3-5-sonnet)+LLM_MODEL=gpt-4o-# Disable SSL certificate verification (set 'true' for self-signed certificates)-DISABLE_SSL_VERIFY=false+# [Required] API key for the LLM provider+LLM_API_KEY=sk-xxx++# [Required] API endpoint URL+LLM_HOST=https://api.openai.com/v1-# ============================================================================-# Embedding Model Configuration-# ============================================================================-# Configure the text embedding model used for semantic search and RAG.-# Required for knowledge base functionality.+# [Optional] API version (required for Azure OpenAI)+LLM_API_VERSION=-# Embedding service provider type-# Options: openai, azure_openai, ollama, lollms+# ==============================================================================+# Embedding Configuration+# ==============================================================================+# Embedding model for RAG (Retrieval-Augmented Generation)++# [Optional] Provider: openai, azure_openai, jina, cohere, ollamaEMBEDDING_BINDING=openai-# Embedding model name-# Cloud examples: text-embedding-3-large, text-embedding-3-small, text-embedding-ada-002-# Local examples (Ollama): nomic-embed-text, mxbai-embed-large-EMBEDDING_MODEL=text-embedding-3-large+# [Required] Model name+EMBEDDING_MODEL=text-embedding-3-small-# Embedding vector dimension-# text-embedding-3-large: 3072-# text-embedding-3-small: 1536-# nomic-embed-text: 768-# mxbai-embed-large: 1024-EMBEDDING_DIMENSION=3072+# [Required] API key+EMBEDDING_API_KEY=sk-xxx-# Embedding API endpoint URL-# Cloud examples:-# - 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)-# Local (Ollama): http://localhost:11434-EMBEDDING_HOST=+# [Required] API endpoint URL+EMBEDDING_HOST=https://api.openai.com/v1-# Embedding API authentication key-# Required for cloud providers, not needed for Ollama-EMBEDDING_API_KEY=+# [Required] Vector dimensions (must match model output)+EMBEDDING_DIMENSION=3072-# API version for Azure OpenAI (e.g., 2024-02-15-preview)-# Required only when EMBEDDING_BINDING=azure_openai+# [Optional] API version (for Azure OpenAI)EMBEDDING_API_VERSION=-# ============================================================================-# TTS (Text-to-Speech) Configuration (Optional)-# ============================================================================-# Configure voice synthesis for the Co-Writer (Interactive IdeaGen) narration feature.-# Also remember to choose a voice in DeepTutor/config/main.yaml.+# ==============================================================================+# TTS Configuration (Text-to-Speech)+# ==============================================================================+# Optional: Enable audio narration features-# TTS model name (e.g., tts-1, tts-1-hd)-TTS_MODEL=+# [Optional] Provider: openai, azure_openai+TTS_BINDING=openai-# TTS API endpoint URL-# - OpenAI: https://api.openai.com/v1-# - Azure OpenAI: https://{your-resource}.openai.azure.com/-# (Note: For TTS on Azure, use the base resource URL)-TTS_URL=+# [Optional] TTS model name+TTS_MODEL=tts-1-# TTS API authentication key-TTS_API_KEY=+# [Optional] API key (can be same as LLM_API_KEY for OpenAI)+TTS_API_KEY=sk-xxx-# TTS service provider type (openai, azure_openai)-TTS_BINDING=openai+# [Optional] API endpoint URL+TTS_URL=https://api.openai.com/v1-# API version for Azure OpenAI TTS (e.g., 2024-02-15-preview)-# Required only when TTS_BINDING=azure_openai+# [Optional] Voice: alloy, echo, fable, onyx, nova, shimmer+TTS_VOICE=alloy++# [Optional] API version (for Azure OpenAI)TTS_BINDING_API_VERSION=-# ============================================================================-# Web Search Configuration-# ============================================================================-# Configure external search APIs for research features.+# ==============================================================================+# Search Configuration (Web Search)+# ==============================================================================+# Optional: Enable web search capabilities-# Search provider to use for web search-# Options: perplexity, baidu, tavily, exa, serper, jina-# Default: perplexity+# [Optional] Provider: perplexity, tavily, serper, jina, exaSEARCH_PROVIDER=perplexity-# -----------------------------------------------------------------------------# Perplexity AI Search Configuration-# -----------------------------------------------------------------------------# Perplexity API key for web search functionality-# Get your API key at: https://www.perplexity.ai/settings/api-PERPLEXITY_API_KEY=--# -----------------------------------------------------------------------------# Baidu AI Search Configuration (百度AI搜索)-# -----------------------------------------------------------------------------# Baidu API Key for intelligent search and generation-# Get your API key at: https://console.bce.baidu.com/ai_apaas/resource-# Format: bce-v3/ALTAK-xxx/xxx or the full API key-BAIDU_API_KEY=--# -----------------------------------------------------------------------------# Tavily Research Search Configuration-# -----------------------------------------------------------------------------# Tavily API key for research-focused search-# Get your API key at: https://tavily.com-TAVILY_API_KEY=--# -----------------------------------------------------------------------------# Exa Neural Search Configuration-# -----------------------------------------------------------------------------# Exa API key for embeddings-based neural search-# Get your API key at: https://dashboard.exa.ai-EXA_API_KEY=--# -----------------------------------------------------------------------------# Serper Google SERP Configuration-# -----------------------------------------------------------------------------# Serper API key for Google search results-# Get your API key at: https://serper.dev-SERPER_API_KEY=--# -----------------------------------------------------------------------------# Jina Reader Search Configuration-# -----------------------------------------------------------------------------# Jina API key for SERP with full content extraction-# Get your API key at: https://jina.ai/reader (optional, has free tier)-JINA_API_KEY=--# ============================================================================-# Logging Configuration-# ============================================================================--# Log level for RAG tool module-# Options: DEBUG, INFO, WARNING, ERROR+# [Optional] API key for your chosen search provider+SEARCH_API_KEY=pplx-xxx++# ==============================================================================+# Cloud Deployment Configuration+# ==============================================================================+# Required when deploying to cloud/remote servers++# [Optional] External API base URL for cloud deployment+# Set this to your server's public URL when deploying remotely+# Example: https://your-server.com:8001 or https://api.yourdomain.com+NEXT_PUBLIC_API_BASE_EXTERNAL=++# [Optional] Direct API base URL (alternative to above)+NEXT_PUBLIC_API_BASE=++# ==============================================================================+# Debug & Development+# ==============================================================================++# [Optional] Disable SSL verification (not recommended for production)+DISABLE_SSL_VERIFY=false++# [Optional] RAG tool module log level: DEBUG, INFO, WARNING, ERRORRAG_TOOL_MODULE_LOG_LEVEL=INFOdiff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 13d6bcc27..230dc0ff6 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -58,7 +58,7 @@ body:id: configusedattributes:label: Configuration Used- description: The AI-Tutor configuration used (if applicable).+ description: The DeepTutor configuration used (if applicable).placeholder: |# Paste your config here or describe the settings- type: textarea@@ -72,7 +72,7 @@ body:attributes:label: Additional Informationdescription: |- - AI-Tutor Version: e.g., v0.1.0+ - DeepTutor Version: e.g., v0.5.0- Operating System: e.g., macOS 14.0, Windows 11, Ubuntu 22.04- Python Version: e.g., 3.10.0- Node.js Version: e.g., 18.17.0@@ -80,7 +80,7 @@ body:- Related Issues: e.g., #1- Any other relevant information.value: |- - AI-Tutor Version:+ - DeepTutor Version:- Operating System:- Python Version:- Node.js Version:diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdindex fedb71c7a..04decd779 100644--- a/.github/pull_request_template.md+++ b/.github/pull_request_template.md@@ -14,13 +14,17 @@ For more details, see our [CONTRIBUTING.md](https://github.com/HKUDS/DeepTutor/b### Module(s) Affected- [ ] `agents`- [ ] `api`-- [ ] `cli`- [ ] `config`- [ ] `core`- [ ] `knowledge`+- [ ] `logging`- [ ] `services`+- [ ] `tools`+- [ ] `utils`- [ ] `web` (Frontend)- [ ] `docs` (Documentation)+- [ ] `scripts`+- [ ] `tests`- [ ] Other: `...`### Checklist@@ -32,4 +36,4 @@ For more details, see our [CONTRIBUTING.md](https://github.com/HKUDS/DeepTutor/b- [ ] My changes do not introduce any new security vulnerabilities.### Additional Notes-*Add any other context or screenshots about the pull request here.*\ No newline at end of file+*Add any other context or screenshots about the pull request here.*diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.ymlindex d13938998..2d2cde558 100644--- a/.github/workflows/docker-publish.yml+++ b/.github/workflows/docker-publish.yml@@ -77,7 +77,7 @@ jobs:type=ref,event=tag- name: Build and push AMD64 image- uses: docker/build-push-action@v5+ uses: docker/build-push-action@v6with:context: .file: ./Dockerfile@@ -148,7 +148,7 @@ jobs:type=raw,value=${{ github.ref_name }}-arm64,enable=${{ startsWith(github.ref, 'refs/tags/') }}- name: Build and push ARM64 image- uses: docker/build-push-action@v5+ uses: docker/build-push-action@v6with:context: .file: ./Dockerfilediff --git a/.github/workflows/linting.yaml b/.github/workflows/linting.yamlindex f249a15c0..4922aa180 100644--- a/.github/workflows/linting.yaml+++ b/.github/workflows/linting.yaml@@ -27,7 +27,7 @@ jobs:- name: Set up Node.jsuses: actions/setup-node@v4with:- node-version: '18'+ node-version: '20'cache: 'npm'cache-dependency-path: web/package-lock.jsondiff --git a/.github/workflows/sync-branch.yml b/.github/workflows/sync-branch.ymlindex 43e8a0dab..c6dcbc891 100644--- a/.github/workflows/sync-branch.yml+++ b/.github/workflows/sync-branch.yml@@ -15,7 +15,7 @@ jobs:runs-on: ubuntu-lateststeps:- name: Checkout repository- uses: actions/checkout@v4+ uses: actions/checkout@v6with:fetch-depth: 0ref: maindiff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 973902182..d37c471e4 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -28,7 +28,7 @@ jobs:strategy:matrix:- python-version: ["3.10", "3.11"]+ python-version: ["3.10", "3.11", "3.12"]fail-fast: falsesteps:@@ -55,7 +55,7 @@ jobs:- name: Upload coverage to Codecovif: matrix.python-version == '3.10'- uses: codecov/codecov-action@v4+ uses: codecov/codecov-action@v5with:files: ./coverage.xmlfail_ci_if_error: false@@ -87,7 +87,9 @@ jobs:python -c "from src.services.llm import complete, stream, fetch_models, sanitize_url; print('✅ LLM service imports OK')"python -c "from src.services.llm.config import get_llm_config; print('✅ LLM config imports OK')"python -c "from src.services.config.loader import load_config_with_main; print('✅ Config loader imports OK')"+ python -c "from src.services.config.unified_config import UnifiedConfigManager; print('✅ Unified config imports OK')"python -c "from src.knowledge.kb import KnowledgeBase; print('✅ Knowledge imports OK')"python -c "from src.tools.rag_tool import rag_search; print('✅ Tools imports OK')"+ python -c "from src.logging import get_logger; print('✅ Logging imports OK')"env:PYTHONPATH: ${{ github.workspace }}diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 7027963b9..ec179fc43 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -25,7 +25,7 @@ repos:- id: check-yamlargs: [--unsafe]-+- id: check-jsonexclude: ^(.*\.lock|.*\.log)@@ -56,7 +56,7 @@ repos:rev: v4.0.0-alpha.8hooks:- id: prettier- args: [--loglevel, warn]+ args: [--log-level, warn]files: ^web/.*\.(css|scss|json|jsonc|yaml|yml|md|graphql|html|ts|tsx|js|jsx)$exclude: ^web/(node_modules|\.next|out|dist|build)/@@ -98,9 +98,14 @@ repos:# ============================================# Type checking# ============================================+ # Type checking - currently relaxed due to gradual type adoption+ # TODO: Gradually enable stricter checks as types are added- repo: https://github.com/pre-commit/mirrors-mypyrev: v1.13.0hooks:- id: mypy- args: [--max-errors, "10"]- exclude: ^(tests/|scripts/)\ No newline at end of file+ args: [--ignore-missing-imports, --no-error-summary, --no-strict-optional]+ exclude: ^(tests/|scripts/|src/agents/|src/services/rag/|src/api/routers/)+ additional_dependencies:+ - types-PyYAML+ - types-requestsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c0f8c5e47..535e8d831 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -144,4 +144,4 @@ We follow a structured commit format to maintain a clean history:3. Follow the process above and submit your PR!Questions? Reach out on Discord.-Let's build the future of AI tutoring together! 🚀\ No newline at end of file+Let's build the future of AI tutoring together! 🚀diff --git a/README.md b/README.mdindex 94f4ef1d3..47f62b1d1 100644--- a/README.md+++ b/README.md@@ -1,6 +1,45 @@+<div align="center">++<img src="assets/logo-ver2.png" alt="DeepTutor Logo" width="150" style="border-radius: 15px;">++# DeepTutor: AI-Powered Personalized Learning Assistant++[](https://www.python.org/downloads/)+[](https://fastapi.tiangolo.com/)+[](https://react.dev/)+[](https://nextjs.org/)+[](https://tailwindcss.com/)+[](LICENSE)++<p align="center">+ <a href="https://discord.gg/zpP9cssj"><img src="https://img.shields.io/badge/Discord-Join_Community-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Discord"></a>+ + <a href="./Communication.md"><img src="https://img.shields.io/badge/Feishu-Join_Group-00D4AA?style=for-the-badge&logo=feishu&logoColor=white" alt="Feishu"></a>+ + <a href="https://github.com/HKUDS/DeepTutor/issues/78"><img src="https://img.shields.io/badge/WeChat-Join_Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" alt="WeChat"></a>+</p>++++[**Quick Start**](#quick-start) · [**Core Modules**](#core-modules) · [**FAQ**](#faq)++[🇨🇳 中文](assets/README/README_CN.md) · [🇯🇵 日本語](assets/README/README_JA.md) · [🇪🇸 Español](assets/README/README_ES.md) · [🇫🇷 Français](assets/README/README_FR.md) · [🇸🇦 العربية](assets/README/README_AR.md) · [🇷🇺 Русский](assets/README/README_RU.md) · [🇮🇳 हिन्दी](assets/README/README_HI.md) · [🇵🇹 Português](assets/README/README_PT.md)++</div>++<div align="center">++📚 **Massive Document Knowledge Q&A** • 🎨 **Interactive Learning Visualization**<br>+🎯 **Knowledge Reinforcement** • 🔍 **Deep Research & Idea Generation**++</div>++---### 📰 News-> **[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! 💬+> **[2026.1.15]** DeepTutor [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) is out! Fixed multiple environment configuration and stability issues. We recommend everyone to pull the latest version! 🎉++> **[2026.1.1]** Happy New Year! Join our [Discord Community](https://discord.gg/zpP9cssj), [Wechat Community](https://github.com/HKUDS/DeepTutor/issues/78), or [Discussions](https://github.com/HKUDS/DeepTutor/discussions) - shape the future of DeepTutor! 💬> **[2025.12.30]** Visit our [Official Website](https://hkuds.github.io/DeepTutor/) for more details!@@ -8,10 +47,12 @@### 📦 Releases-> **[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!+> **[2026.1.15]** Release [v0.5.0](https://github.com/HKUDS/DeepTutor/releases/tag/v0.5.0) - Unified LLM & Embedding services, RAG pipeline selection, and major enhancements to Home, History, QuestionGen & Settings modules -- Thanks to all the contributors!<details><summary>History releases</summary>+> **[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!+> **[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!> **[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@@ -202,9 +243,13 @@## 📋 Todo> 🌟 Star to follow our future updates!-- [ x ] Support More RAG Pipelines-- [ x ] DataBase Robostness and Visualization-- [ ] Personalized Interaction with Notebook+- [ x ] Multi-linguistic support+- [ x ] DeepTutor Community+- [ x ] Incremental Knowledge-base Edit+- [ x ] Personalized Workspace+- [ - ] DataBase Visualization+- [ - ] Atomic RAG pipeline customize+- [ - ] Online Demo## 🚀 Getting Started@@ -241,9 +286,8 @@ cp .env.example .env| `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 |+| `SEARCH_PROVIDER` | No | Search provider (options: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, default: `perplexity`) |+| `SEARCH_API_KEY` | No | Unified API key for all search providers |> 💡 **Remote Access**: If accessing from another device (e.g., `192.168.31.66:3782`), add to `.env`:> ```bashdiff --git a/assets/README/README_AR.md b/assets/README/README_AR.mdindex 45268fb57..2a57f5695 100644--- a/assets/README/README_AR.md+++ b/assets/README/README_AR.md@@ -237,7 +237,8 @@ cp .env.example .env| `BACKEND_PORT` | لا | منفذ الخلفية (افتراضي: `8001`) || `FRONTEND_PORT` | لا | منفذ الواجهة الأمامية (افتراضي: `3782`) || `TTS_*` | لا | إعدادات تحويل النص إلى كلام |-| `PERPLEXITY_API_KEY` | لا | للبحث على الويب |+| `SEARCH_PROVIDER` | لا | مزود البحث (الخيارات: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`، الافتراضي: `perplexity`) |+| `SEARCH_API_KEY` | لا | مفتاح API موحد للبحث |</details>diff --git a/assets/README/README_CN.md b/assets/README/README_CN.mdindex 15815853e..ddacbb012 100644--- a/assets/README/README_CN.md+++ b/assets/README/README_CN.md@@ -255,7 +255,8 @@ cp .env.example .env| `BACKEND_PORT` | 否 | 后端端口(默认:`8001`) || `FRONTEND_PORT` | 否 | 前端端口(默认:`3782`) || `TTS_*` | 否 | 文本转语音设置 |-| `PERPLEXITY_API_KEY` | 否 | 用于网络搜索 |+| `SEARCH_PROVIDER` | 否 | 搜索提供商(可选:`perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`,默认:`perplexity`)|+| `SEARCH_API_KEY` | 否 | 统一的搜索 API 密钥 |</details>diff --git a/assets/README/README_ES.md b/assets/README/README_ES.mdindex 0fcde9003..a9019a362 100644--- a/assets/README/README_ES.md+++ b/assets/README/README_ES.md@@ -237,7 +237,8 @@ cp .env.example .env| `BACKEND_PORT` | No | Puerto del backend (predeterminado: `8001`) || `FRONTEND_PORT` | No | Puerto del frontend (predeterminado: `3782`) || `TTS_*` | No | Configuración de texto a voz |-| `PERPLEXITY_API_KEY` | No | Para búsqueda web |+| `SEARCH_PROVIDER` | No | Proveedor de búsqueda (opciones: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, predeterminado: `perplexity`) |+| `SEARCH_API_KEY` | No | Clave API unificada para búsqueda |</details>diff --git a/assets/README/README_FR.md b/assets/README/README_FR.mdindex 9c558c247..c2dd58b43 100644--- a/assets/README/README_FR.md+++ b/assets/README/README_FR.md@@ -237,7 +237,8 @@ cp .env.example .env| `BACKEND_PORT` | Non | Port backend (par défaut: `8001`) || `FRONTEND_PORT` | Non | Port frontend (par défaut: `3782`) || `TTS_*` | Non | Paramètres de synthèse vocale |-| `PERPLEXITY_API_KEY` | Non | Pour la recherche web |+| `SEARCH_PROVIDER` | Non | Fournisseur de recherche (options: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, défaut: `perplexity`) |+| `SEARCH_API_KEY` | Non | Clé API unifiée pour la recherche |</details>diff --git a/assets/README/README_HI.md b/assets/README/README_HI.mdindex 7fbdcdf5f..6f9a482ea 100644--- a/assets/README/README_HI.md+++ b/assets/README/README_HI.md@@ -237,7 +237,8 @@ cp .env.example .env| `BACKEND_PORT` | नहीं | बैकएंड पोर्ट (डिफ़ॉल्ट: `8001`) || `FRONTEND_PORT` | नहीं | फ्रंटएंड पोर्ट (डिफ़ॉल्ट: `3782`) || `TTS_*` | नहीं | टेक्स्ट-टू-स्पीच सेटिंग्स |-| `PERPLEXITY_API_KEY` | नहीं | वेब खोज के लिए |+| `SEARCH_PROVIDER` | नहीं | खोज प्रदाता (विकल्प: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, डिफ़ॉल्ट: `perplexity`) |+| `SEARCH_API_KEY` | नहीं | खोज के लिए एकीकृत API कुंजी |</details>diff --git a/assets/README/README_JA.md b/assets/README/README_JA.mdindex cc88b7378..466a103f8 100644--- a/assets/README/README_JA.md+++ b/assets/README/README_JA.md@@ -255,7 +255,8 @@ cp .env.example .env| `BACKEND_PORT` | いいえ | バックエンドポート(デフォルト:`8001`) || `FRONTEND_PORT` | いいえ | フロントエンドポート(デフォルト:`3782`) || `TTS_*` | いいえ | テキスト読み上げ設定 |-| `PERPLEXITY_API_KEY` | いいえ | ウェブ検索用 |+| `SEARCH_PROVIDER` | いいえ | 検索プロバイダー(オプション:`perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`、デフォルト:`perplexity`)|+| `SEARCH_API_KEY` | いいえ | 統一検索APIキー |</details>diff --git a/assets/README/README_PT.md b/assets/README/README_PT.mdindex 0f6430d63..e4095d4d6 100644--- a/assets/README/README_PT.md+++ b/assets/README/README_PT.md@@ -237,7 +237,8 @@ cp .env.example .env| `BACKEND_PORT` | Não | Porta do backend (padrão: `8001`) || `FRONTEND_PORT` | Não | Porta do frontend (padrão: `3782`) || `TTS_*` | Não | Configurações de texto para voz |-| `PERPLEXITY_API_KEY` | Não | Para busca na web |+| `SEARCH_PROVIDER` | Não | Provedor de busca (opções: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, padrão: `perplexity`) |+| `SEARCH_API_KEY` | Não | Chave API unificada para busca |</details>diff --git a/assets/README/README_RU.md b/assets/README/README_RU.mdindex f10ce806a..6d6b3c5e2 100644--- a/assets/README/README_RU.md+++ b/assets/README/README_RU.md@@ -255,7 +255,8 @@ cp .env.example .env| `BACKEND_PORT` | Нет | Порт backend (по умолчанию: `8001`) || `FRONTEND_PORT` | Нет | Порт frontend (по умолчанию: `3782`) || `TTS_*` | Нет | Настройки синтеза речи |-| `PERPLEXITY_API_KEY` | Нет | Для веб-поиска |+| `SEARCH_PROVIDER` | Нет | Провайдер поиска (варианты: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, по умолчанию: `perplexity`) |+| `SEARCH_API_KEY` | Нет | Единый API-ключ для поиска |</details>diff --git a/assets/releases/ver0-5-0.md b/assets/releases/ver0-5-0.mdnew file mode 100644index 000000000..2e1257347--- /dev/null+++ b/assets/releases/ver0-5-0.md@@ -0,0 +1,141 @@+# DeepTutor v0.5.0 Release Notes++**Release Date:** 2026.01.15++We're thrilled to announce DeepTutor v0.5.0! This release delivers **unified service configuration**, **flexible RAG pipeline selection**, and **major UI/UX improvements** across multiple modules.++> **Stability Update:** This release fixes multiple environment configuration and stability issues. We recommend all users to pull the latest version! Remember to update your .env file!++> [!TIP]+> **Call for Issues:** We welcome your feedback! If you encounter any bugs or have feature requests, please [open an issue](https://github.com/HKUDS/DeepTutor/issues)! If you would like to submit a PR, please check out our [Contributing Guide](https://github.com/HKUDS/DeepTutor/blob/main/CONTRIBUTING.md).++---++## Quick Summary++- **Configuration** — Refactored config logic for smoother LLM/Embedding setup. Backend secrets stay hidden from frontend. Added more search providers.+- **RAG Pipelines** — Select different pipelines per KB: LlamaIndex (direct), LightRAG (graph), RAG-Anything (multimodal graph).+- **Question Gen** — Unified BaseAgent architecture with more intuitive UI.+- **Home** — Save chat history to notebooks.+- **Sidebar** — Drag-and-drop reordering + customizable top-left label.+- **Misc** — Various bug fixes and stability improvements.++---++## ✨ Highlights++### Unified Configuration System++Completely redesigned configuration management for LLM, Embedding, TTS, and Search services:++**Key Features:**+- **Environment-based secrets**: Store sensitive API keys in `.env` while managing configurations in the UI+- **`{"use_env": "VAR_NAME"}` syntax**: Reference environment variables without exposing them in the frontend+- **Per-service active config**: Each service (LLM, Embedding, TTS, Search) maintains its own active configuration+- **Seamless provider switching**: Add new providers in the frontend without touching backend secrets+++**New Search Providers:**+| Provider | Description |+|:---|:---|+| Tavily | AI-native search API |+| Exa | Neural search engine |+| Jina | Reader-based web search |+| Serper | Google SERP API |++### RAG Pipeline Selection++Choose the optimal RAG pipeline for each knowledge base based on your speed/quality requirements:++| Pipeline | Index Type | Best For | Speed |+|:---|:---|:---|:---|+| **LlamaIndex** | Vector (Direct) | Quick setup, simple documents | Fastest |+| **LightRAG** | Knowledge Graph | General documents, text-heavy | Fast |+| **RAG-Anything** | Multimodal Graph | Academic papers, textbooks with figures/equations | Thorough |++### Question Generation Overhaul++Refactored the Question Generation module with unified agent architecture:++**Backend Changes:**+- Migrated to `BaseAgent` pattern consistent with other modules+- New specialized agents: `RetrieveAgent`, `GenerateAgent`, `RelevanceAnalyzer`+- Single-pass generation with relevance classification (no iterative validation loops)+- Improved JSON parsing with markdown code block extraction++**Frontend Improvements:**+- Real-time progress dashboard with stage indicators+- Log drawer for debugging generation process+- Cleaner question card layout with answer submission+- "Add to Notebook" integration++### Home Page Enhancements++**Save Chat to Notebook:**+- New "Save to Notebook" button in chat interface+- Automatically formats conversation as markdown+- Preserves user queries and assistant responses with role labels++### Sidebar Customization++**Drag-and-Drop Navigation:**+- Reorder sidebar items within groups by dragging+- Visual feedback during drag operations+- Persistent order saved to user settings++**Customizable Description:**+- Click to edit the sidebar description label+- Personalize your workspace identity++---++## 📦 What's Changed++### Core Infrastructure++- Added `src/services/config/unified_config.py` — Centralized configuration manager+- Added `src/api/routers/config.py` — Unified REST API for all service configs+- Refactored web search to support multiple providers (`src/services/search/`)+- Enhanced error handling with LLM error framework++### RAG System++- Implemented `LlamaIndexPipeline` with custom embedding adapter+- Implemented pure `LightRAGPipeline` with complete initialization+- Added pipeline selection during KB create/upload (PR #129)+- Factory pattern in `src/services/rag/factory.py` for pipeline management++### Question Generation++- Refactored `AgentCoordinator` with specialized agents+- New `RetrieveAgent`, `GenerateAgent`, `RelevanceAnalyzer` in `src/agents/question/agents/`+- Removed iterative validation loops for faster generation+- Added `useQuestionReducer` hook for frontend state management++### Frontend Updates++- `web/app/settings/page.tsx` — Complete rebuild with unified config UI+- `web/app/question/page.tsx` — New dashboard with progress tracking+- `web/app/page.tsx` — Added "Save to Notebook" functionality+- `web/components/Sidebar.tsx` — Drag-and-drop + editable description+- `web/components/AddToNotebookModal.tsx` — Reusable notebook integration++---++## What's Changed++* feat(kb): allow selecting RAG provider during KB create/upload by @tusharkhatriofficial in https://github.com/HKUDS/DeepTutor/pull/129+* fix(docker): make Dockerfile portable by @scrrlt in https://github.com/HKUDS/DeepTutor/pull/128+* feat: pre-commit CI integration by @scrrlt in https://github.com/HKUDS/DeepTutor/pull/126+* feat: LlamaIndex pipeline implementation by @tusharkhatriofficial in https://github.com/HKUDS/DeepTutor/pull/98+* feat: web search providers (Tavily, Exa, Jina, Serper) by @Andres77872 in https://github.com/HKUDS/DeepTutor/pull/95+* feat: Azure OpenAI support enhancement by @scrrlt in https://github.com/HKUDS/DeepTutor/pull/87+* fix: modal vertical centering by @OlalalalaO in https://github.com/HKUDS/DeepTutor/pull/117+* work: LLM error framework by @scrrlt in https://github.com/HKUDS/DeepTutor/pull/118++## New Contributors++* @Andres77872 made their first contribution in https://github.com/HKUDS/DeepTutor/pull/95+* @OlalalalaO made their first contribution in https://github.com/HKUDS/DeepTutor/pull/117++**Full Changelog**: https://github.com/HKUDS/DeepTutor/compare/v0.4.1...v0.5.0diff --git a/config/main.yaml b/config/main.yamlindex f95d83389..619523a19 100644--- a/config/main.yaml+++ b/config/main.yaml@@ -38,19 +38,18 @@ logging:logger_names:knowledge_init: LightRAG-Initrag_tool: LightRAG-tts:- default_voice: alloyquestion:- max_rounds: 10+ # Refactored: no iteration loops (max_rounds removed)rag_query_count: 3max_parallel_questions: 1rag_mode: naiveagents:- question_generation:- max_iterations: 5- retrieve_top_k: 30- question_validation:- strict_mode: true+ retrieve:+ top_k: 30+ generate:+ max_retries: 2+ relevance_analyzer:+ enabled: truesolve:max_solve_correction_iterations: 3enable_citations: truediff --git a/docker-compose.yml b/docker-compose.ymlindex fbe9a848c..f05c788cc 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -47,7 +47,7 @@ services:- EMBEDDING_MODEL=${EMBEDDING_MODEL:-text-embedding-3-large}- EMBEDDING_API_KEY=${EMBEDDING_API_KEY}- EMBEDDING_HOST=${EMBEDDING_HOST}- - EMBEDDING_DIM=${EMBEDDING_DIM:-3072}+ - EMBEDDING_DIMENSION=${EMBEDDING_DIMENSION:-3072}- EMBEDDING_MAX_TOKENS=${EMBEDDING_MAX_TOKENS:-8192}# TTS Configuration (Optional)- TTS_MODEL=${TTS_MODEL:-}@@ -56,12 +56,7 @@ services:- TTS_VOICE=${TTS_VOICE:-alloy}# Web Search Configuration (Optional)- SEARCH_PROVIDER=${SEARCH_PROVIDER:-perplexity}- - PERPLEXITY_API_KEY=${PERPLEXITY_API_KEY:-}- - BAIDU_API_KEY=${BAIDU_API_KEY:-}- - TAVILY_API_KEY=${TAVILY_API_KEY:-}- - EXA_API_KEY=${EXA_API_KEY:-}- - SERPER_API_KEY=${SERPER_API_KEY:-}- - JINA_API_KEY=${JINA_API_KEY:-}+ - SEARCH_API_KEY=${SEARCH_API_KEY:-}# Logging Configuration- RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-INFO}# ============================================diff --git a/docs/guide/configuration.md b/docs/guide/configuration.mdindex 3d2c16703..1cb773b4f 100644--- a/docs/guide/configuration.md+++ b/docs/guide/configuration.md@@ -29,9 +29,9 @@ FRONTEND_PORT=3782# Remote accessNEXT_PUBLIC_API_BASE=http://your-server-ip:8001-# Web search-SEARCH_PROVIDER=perplexity # or: baidu-PERPLEXITY_API_KEY=your_key+# Web search (unified API key)+SEARCH_PROVIDER=perplexity # Options: perplexity, tavily, serper, jina, exa, baidu+SEARCH_API_KEY=your_search_api_key# TTSTTS_MODEL=@@ -133,9 +133,8 @@ 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搜索)+SEARCH_PROVIDER=perplexity # Options: perplexity, tavily, serper, jina, exa, baidu+SEARCH_API_KEY=your_search_api_key # Unified API key for all search providers# ============================================================================# TTS (Text-to-Speech) Configuration - Optionaldiff --git a/docs/zh/guide/configuration.md b/docs/zh/guide/configuration.mdindex be7e74b4b..1db52ef0c 100644--- a/docs/zh/guide/configuration.md+++ b/docs/zh/guide/configuration.md@@ -35,9 +35,9 @@ FRONTEND_PORT=3782# 远程访问NEXT_PUBLIC_API_BASE=http://your-server-ip:8001-# 网络搜索-SEARCH_PROVIDER=perplexity # 或:baidu-PERPLEXITY_API_KEY=your_key+# 网络搜索(统一 API Key)+SEARCH_PROVIDER=perplexity # 可选:perplexity, tavily, serper, jina, exa, baidu+SEARCH_API_KEY=your_search_api_key# TTS 语音合成TTS_MODEL=diff --git a/pyproject.toml b/pyproject.tomlindex ffd37012d..ffb36c415 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"[project]name = "ai-tutor"-version = "0.4.1"+version = "0.5.0"description = "An intelligent learning companion with multi-agent collaboration and RAG"requires-python = ">=3.10"readme = "README.md"@@ -186,16 +186,19 @@ addopts = [# ============================================[tool.mypy]python_version = "3.10"-# Only show the summary line if there are errors+# Relaxed type checking for gradual adoptionpretty = falseshow_error_context = false-# Limit the number of errors shown-max_errors = 10-warn_return_any = true-warn_no_return = true+warn_return_any = false+warn_no_return = falseshow_error_codes = trueignore_missing_imports = truefollow_imports = "silent"+# Disable strict checks that generate too many errors+check_untyped_defs = false+disallow_untyped_defs = false+disallow_incomplete_defs = false+no_implicit_optional = false# Module-specific overrides[[tool.mypy.overrides]]@@ -211,4 +214,13 @@ ignore_errors = true # Some tools may have dynamic imports# ============================================[tool.bandit]exclude_dirs = ["tests", "scripts"]-skips = ["B101", "B311", "B403", "B404"] # B101=assert, B311=random, B403/B404=pickle/subprocess imports+# B101=assert, B311=random, B403/B404=pickle/subprocess imports+# B110=try_except_pass (intentional for non-critical error handling)+# B104=hardcoded_bind_all_interfaces (required for server binding)+# B112=try_except_continue (intentional for iteration)+# B105=hardcoded_password_string (false positive on empty string initialization)+# B301=pickle (used for internal embedding cache, not untrusted data)+# B501=request_with_no_cert_validation (opt-in via env var for dev/testing)+# B603=subprocess_without_shell_equals_true (controlled execution)+# B202=tarfile_unsafe_members (already using safe_members filter)+skips = ["B101", "B311", "B403", "B404", "B110", "B104", "B112", "B105", "B301", "B501", "B603", "B202"]diff --git a/src/agents/base_agent.py b/src/agents/base_agent.pyindex 2332be34d..e91f9a53b 100644--- a/src/agents/base_agent.py+++ b/src/agents/base_agent.py@@ -8,9 +8,7 @@ This is the single source of truth for agent base functionality across:- guide module- ideagen module- co_writer module--Note: The question module uses a separate ReAct architecture and is intentionally-not unified with this base class.+- question module (unified in Jan 2026 refactor)"""from abc import ABC, abstractmethoddiff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.pyindex ed7bb6a4c..5ecb8fd59 100644--- a/src/agents/co_writer/narrator_agent.py+++ b/src/agents/co_writer/narrator_agent.py@@ -17,7 +17,6 @@ import uuidfrom openai import AsyncAzureOpenAI, AsyncOpenAIfrom src.agents.base_agent import BaseAgent-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@@ -56,24 +55,18 @@ class NarratorAgent(BaseAgent):self._load_tts_config()def _load_tts_config(self):- """Load TTS-specific configuration."""- # Load main config file to get TTS default settings- try:- config = load_config_with_main("solve_config.yaml")- self.tts_settings = config.get("tts", {})- self.default_voice = self.tts_settings.get("default_voice", "alloy")- self.logger.info(f"TTS settings loaded from config: voice={self.default_voice}")- except Exception as e:- self.logger.warning(f"Failed to load TTS settings from config, using defaults: {e}")- self.default_voice = "alloy"-+ """Load TTS-specific configuration from unified config service."""try:self.tts_config = get_tts_config()+ # Get voice from unified config (defaults to "alloy")+ self.default_voice = self.tts_config.get("voice", "alloy")+ self.logger.info(f"TTS settings loaded: voice={self.default_voice}")# Validate TTS configurationself._validate_tts_config()except Exception as e:self.logger.error(f"Failed to load TTS config: {e}", exc_info=True)self.tts_config = None+ self.default_voice = "alloy"def _validate_tts_config(self):"""Validate TTS configuration completeness and format"""diff --git a/src/agents/question/README.md b/src/agents/question/README.mdindex f2248ed2d..02ab2c623 100644--- a/src/agents/question/README.md+++ b/src/agents/question/README.md@@ -1,176 +1,196 @@# Question Generation System-Intelligent question generation system with **dual-mode architecture** supporting both knowledge base-driven custom generation and reference exam paper mimicking.+Intelligent question generation system with **modular agent architecture** supporting both knowledge base-driven custom generation and reference exam paper mimicking.## 📁 Directory Structure```question/├── __init__.py # Module exports-├── agents/ # Agent classes+├── agents/ # Specialized agents│ ├── __init__.py-│ ├── base_agent.py # Base agent class (ReAct paradigm)-│ ├── generation_agent.py # Question generation agent-│ └── validation_agent.py # Question validation agent (deprecated)-├── tools/ # Tools and utilities-│ ├── __init__.py-│ ├── pdf_parser.py # PDF parsing with MinerU-│ ├── question_extractor.py # Extract questions from exams-│ └── exam_mimic.py # Reference-based question generation+│ ├── retrieve_agent.py # Knowledge retrieval from KB+│ ├── generate_agent.py # Question generation+│ └── relevance_analyzer.py # Question-KB relevance analysis├── prompts/ # Bilingual prompts (YAML)-│ ├── zh/ # Chinese prompts-│ │ ├── generation_agent.yaml-│ │ ├── validation_workflow.yaml+│ ├── zh/ # Chinese prompts+│ │ ├── retrieve_agent.yaml+│ │ ├── generate_agent.yaml+│ │ ├── relevance_analyzer.yaml│ │ └── coordinator.yaml-│ └── en/ # English prompts+│ └── en/ # English prompts│ └── (same structure)-├── coordinator.py # Agent coordinator-├── validation_workflow.py # Validation workflow-├── example.py # Usage examples+├── coordinator.py # Workflow orchestration+├── example.py # Usage examples└── README.md++# Tools moved to src/tools/question/+src/tools/question/+├── __init__.py+├── pdf_parser.py # PDF parsing with MinerU+├── question_extractor.py # Extract questions from exams+└── exam_mimic.py # Reference-based question generation```## 🚀 Core Features### Custom Mode (Knowledge Base-Driven)-- ✅ **Intelligent Search Query Generation** - Generates configurable number of RAG queries (from `config/main.yaml`)-- ✅ **Background Knowledge Acquisition** - Retrieves relevant knowledge using naive mode RAG-- ✅ **Question Planning** - Creates comprehensive plan with question IDs, focuses, and types-- ✅ **Single-Pass Validation** - Analyzes question relevance without iterative refinement-- ✅ **Complete File Persistence** - Saves background knowledge, plan, and individual results+- ✅ **Intelligent Search Query Generation** - Generates configurable number of RAG queries+- ✅ **Background Knowledge Acquisition** - Retrieves relevant knowledge using RAG+- ✅ **Question Planning** - Creates comprehensive plan with question IDs and focuses+- ✅ **Single-Pass Relevance Analysis** - Analyzes question relevance (no iteration/rejection)+- ✅ **Complete File Persistence** - Saves knowledge, plan, and individual results### Mimic Mode (Reference Exam-Based)- ✅ **PDF Parsing** - Automatic PDF extraction using MinerU- ✅ **Question Extraction** - Identifies and extracts reference questions from exams- ✅ **Style Mimicking** - Generates similar questions based on reference structure- ✅ **Batch Organization** - All outputs saved to timestamped folders-- ✅ **Progress Tracking** - Real-time updates for parsing, extracting, and generating stages### Common Features-- ✅ **Multimodal Content Support** - Correctly parses text, equations, images, and tables-- ✅ **Batch Question Generation** - Handles multiple questions in parallel-- ✅ **Bilingual Prompts** - Supports both Chinese and English prompts via YAML configuration+- ✅ **Unified BaseAgent** - All agents inherit from `src/agents/base_agent.py`+- ✅ **No Iteration Loops** - Single-pass generation + analysis+- ✅ **Bilingual Prompts** - Supports both Chinese and English via YAML- ✅ **Real-time WebSocket Streaming** - Live progress updates to frontend## System Architecture-### Custom Mode Architecture+### Modular Agent Architecture+```User Requirement↓-Generate RAG Queries (configurable count)- ↓-Retrieve Background Knowledge (naive mode)- ↓-Create Question Plan (IDs, focuses, types)+┌─────────────────────────────────────────────────┐+│ AgentCoordinator │+│ │+│ 1. RetrieveAgent │+│ ├── Generate RAG queries (LLM) │+│ └── Execute RAG searches (parallel) │+│ │+│ 2. Plan Generation (in coordinator) │+│ └── Create focuses for each question │+│ │+│ 3. GenerateAgent (per question) │+│ └── Generate question from knowledge+focus │+│ │+│ 4. RelevanceAnalyzer (per question) │+│ └── Analyze KB relevance (high/partial) │+│ │+└─────────────────────────────────────────────────┘↓-For each question:- GenerationAgent → ValidationWorkflow- ↓ ↓- [retrieve] [analyze_relevance]- [generate] (single-pass, no rejection)- ↓-Save: background_knowledge.json- question_plan.json- question_X_result.json+Save Results:+ - knowledge.json (queries + retrievals)+ - plan.json (focuses)+ - q_1/result.json, q_1/question.md+ - q_2/result.json, q_2/question.md+ - summary.json```### Mimic Mode Architecture+```PDF Upload / Parsed Directory↓-Parse PDF with MinerU+Parse PDF with MinerU (tools/pdf_parser.py)↓-Extract Reference Questions+Extract Reference Questions (tools/question_extractor.py)↓For each reference question (parallel):- GenerationAgent → ValidationWorkflow+ AgentCoordinator.generate_question(with_reference=True)+ ├── RetrieveAgent+ ├── GenerateAgent (with reference)+ └── RelevanceAnalyzer↓-Save to: mimic_YYYYMMDD_HHMMSS_{pdf_name}/- ├── {pdf_name}.pdf- ├── auto/{pdf_name}.md- ├── {pdf_name}_questions.json- └── {pdf_name}_generated_questions.json+Save to timestamped folder```## Core Components-### 1. BaseAgent (Base Agent Class)+### 1. RetrieveAgent-Located in `agents/base_agent.py`. Implements ReAct loop: **Think → Act → Observe**+Located in `agents/retrieve_agent.py`. Inherits from `src/agents/base_agent.py`.-### 2. QuestionGenerationAgent+**Responsibilities:**+- Generate semantic search queries from requirements+- Execute RAG searches in parallel+- Merge and summarize retrieval results-Located in `agents/generation_agent.py`. Generates questions based on knowledge base content or reference questions.+```python+retrieve_agent = RetrieveAgent(kb_name="math2211", language="en")+result = await retrieve_agent.process(requirement, num_queries=3)+# Returns: {"queries": [...], "retrievals": [...], "summary": "...", "has_content": True}+```-**Available Actions** (Custom Mode):-- `retrieve`: Retrieve relevant knowledge from knowledge base-- `generate_question`: Generate questions based on retrieved knowledge-- `refine_question`: Modify questions based on validation feedback-- `submit_question`: Submit question to validation workflow+### 2. GenerateAgent-**Key Changes**:-- ❌ Removed `reject_task` action - no longer rejects tasks-- ✅ Focuses on generation and refinement only+Located in `agents/generate_agent.py`. Generates questions based on knowledge context.-### 3. QuestionValidationWorkflow+**Responsibilities:**+- Generate custom questions from requirements + knowledge+- Generate mimic questions from reference + knowledge+- Output structured question JSON-Located in `validation_workflow.py`. Validates question quality using single-pass analysis.+```python+generate_agent = GenerateAgent(language="en")+result = await generate_agent.process(+ requirement={"knowledge_point": "...", "difficulty": "medium"},+ knowledge_context="...",+ focus={"focus": "...", "type": "written"},+ reference_question=None # or "reference text" for mimic mode+)+# Returns: {"success": True, "question": {...}}+```-**Custom Mode Workflow**:-- `retrieve` → `validate` → `analyze_relevance` → `return`+### 3. RelevanceAnalyzer-**Validation Output**:-- `decision`: "approve" (always, no rejection)-- `relevance`: "highly_relevant" | "partially_relevant"-- `kb_coverage`: Detailed analysis of knowledge base content tested-- `extension_points`: Explanation of extensions beyond KB (if applicable)-- `issues`: List of quality issues (if any)-- `suggestions`: Improvement suggestions (for refinement)+Located in `agents/relevance_analyzer.py`. Replaces old validation workflow.-**Mimic Mode Workflow**:-- Similar structure, but validates against reference question style and knowledge base sufficiency+**Key difference from old ValidationWorkflow:**+- **NO rejection**: all questions are accepted+- **NO iteration**: single-pass analysis+- Output: relevance level (high/partial) with explanations-### 4. AgentCoordinator+```python+analyzer = RelevanceAnalyzer(language="en")+result = await analyzer.process(question={"question": "..."}, knowledge_context="...")+# Returns: {"relevance": "high", "kb_coverage": "...", "extension_points": ""}+```-Located in `coordinator.py`. Manages question generation workflows for both custom and mimic modes.+### 4. AgentCoordinator-**Custom Mode Methods**:-- `generate_questions_custom()`: Full pipeline from requirement text to final questions-- `_generate_search_queries_from_text()`: Creates RAG queries (count from config)-- `_create_question_plan()`: Generates question plan based on requirements-- `generate_question()`: Single question generation with validation+Located in `coordinator.py`. Orchestrates the workflow using specialized agents.-**Mimic Mode**:-- Handled by `tools/exam_mimic.py` with coordinator for individual question generation+**Methods:**+- `generate_question()`: Single question generation (used by Mimic mode)+- `generate_questions_custom()`: Batch generation from requirement## Usage-### Custom Mode - Full Pipeline+### Custom Mode - Batch Generation```pythonimport asynciofrom src.agents.question import AgentCoordinatorasync def main():- # Create coordinatorcoordinator = AgentCoordinator(- max_rounds=10,kb_name="math2211",- output_dir="data/user/question"+ output_dir="data/user/question",+ language="en")- # Full pipeline from text requirementresult = await coordinator.generate_questions_custom(- requirement_text="Generate 3 medium-difficulty questions about multivariable limits",- difficulty="medium",- question_type="choice",- count=3+ requirement={+ "knowledge_point": "Multivariable limits",+ "difficulty": "medium",+ "question_type": "choice"+ },+ num_questions=3)print(f"✅ Generated {result['completed']}/{result['requested']} questions")- for q in result['results']:- print(f"- {q['question']['question'][:50]}...")+ for r in result['results']:+ print(f"- [{r['analysis']['relevance']}] {r['question']['question'][:50]}...")asyncio.run(main())```@@ -178,29 +198,24 @@ asyncio.run(main())### Custom Mode - Single Question```python-# Define question requirementrequirement = {- "knowledge_point": "Limits and continuity of multivariable functions",+ "knowledge_point": "Limits and continuity","difficulty": "medium",- "question_type": "choice",- "focus": "Test path-dependent limits at (0,0)"+ "question_type": "choice"}-# Generate single questionresult = await coordinator.generate_question(requirement)if result["success"]:- print(f"✅ Generated in {result['rounds']} rounds")print(f"Question: {result['question']['question']}")print(f"Relevance: {result['validation']['relevance']}")-else:- print(f"❌ Failed: {result['error']}")+ print(f"KB Coverage: {result['validation']['kb_coverage']}")```### Mimic Mode - PDF Upload```python-from src.agents.question.tools.exam_mimic import mimic_exam_questions+from src.tools.question import mimic_exam_questionsresult = await mimic_exam_questions(pdf_path="exams/midterm.pdf",@@ -210,121 +225,47 @@ result = await mimic_exam_questions()print(f"✅ Generated {result['successful_generations']} questions")-print(f"Output: {result['output_file']}")```### Mimic Mode - Parsed Directory```python-# If you already have MinerU parsed resultsresult = await mimic_exam_questions(paper_dir="data/parsed_exams/exam_20240101",- kb_name="math2211",- max_questions=None # Generate for all reference questions+ kb_name="math2211")```-## Prompts Configuration--Prompts are stored in YAML files under `prompts/` directory with bilingual support:--- `prompts/en/` - English prompts-- `prompts/zh/` - Chinese prompts--Each agent loads prompts based on the `language` parameter (default: "en").--### YAML Format Example--```yaml-system: |- You are a professional Question Generation Agent...--generate: |- Generate a question based on the following information:- Requirements: {requirements}- Retrieved knowledge: {knowledge}- ...--refine: |- Please modify the question based on validation feedback:- ...-```-## Configuration-### Environment Variables--```bash-# LLM API Configuration-LLM_API_KEY=your_api_key_here-LLM_HOST=https://api.openai.com/v1-LLM_MODEL=gpt-4o-```+### `config/main.yaml`-### Configuration Files--**`config/main.yaml`** - RAG query count:```yamlquestion:- rag_query_count: 3 # Number of RAG queries for background knowledge+ # Refactored: no iteration loops (max_rounds removed)+ rag_query_count: 3+ max_parallel_questions: 1+ rag_mode: naive+ agents:+ retrieve:+ top_k: 30+ generate:+ max_retries: 2+ relevance_analyzer:+ enabled: true```-**`config/agents.yaml`** - Agent parameters:+### `config/agents.yaml`+```yamlquestion:temperature: 0.7max_tokens: 4000```-## Tools--### PDF Parsing (`tools/pdf_parser.py`)--Uses MinerU for high-quality PDF extraction with formula and table support.--```python-from src.agents.question.tools import parse_pdf_with_mineru--# Parse PDF to markdown-success = await parse_pdf_with_mineru(- pdf_path="/path/to/exam.pdf",- output_base_dir="data/user/question/mimic_papers"-)-```--### Question Extraction (`tools/question_extractor.py`)--Extracts structured questions from parsed exam papers.--```python-from src.agents.question.tools import extract_questions_from_paper--questions = await extract_questions_from_paper(- paper_dir="data/mimic_papers/exam_20241211",- output_dir="data/mimic_papers"-)-# Returns: [{"question_number": "1", "question_text": "...", "images": []}, ...]-```--### Exam Mimicking (`tools/exam_mimic.py`)--Complete pipeline for reference-based question generation.--```python-from src.agents.question.tools import mimic_exam_questions--result = await mimic_exam_questions(- pdf_path="exams/midterm.pdf", # Or use paper_dir for parsed- kb_name="math2211",- output_dir="data/user/question/mimic_papers",- max_questions=5,- ws_callback=None # Optional: async callback for progress updates-)-```-## Return Format-### Custom Mode - Single Question+### Single Question Result```python{@@ -338,56 +279,35 @@ result = await mimic_exam_questions("knowledge_point": "Topic name"},"validation": {- "decision": "approve", # Always approve, no rejection- "relevance": "highly_relevant", # or "partially_relevant"- "kb_coverage": "This question tests...", # For highly relevant- "extension_points": "This question extends...", # For partially relevant- "issues": [], # Quality issues if any- "suggestions": [] # Improvement suggestions+ "decision": "approve", # Always approve+ "relevance": "high", # or "partial"+ "kb_coverage": "This question tests...",+ "extension_points": "" # Only if relevance is "partial"},- "rounds": 1 # Number of generation rounds (typically 1-2)+ "rounds": 1 # Always 1 (no iteration)}```-### Custom Mode - Batch Generation+### Batch Generation Result```python{- "completed": 3,+ "success": True,"requested": 3,+ "completed": 3,"failed": 0,+ "search_queries": ["query1", "query2", "query3"],+ "plan": {"focuses": [...]},"results": [{+ "question_id": "q_1",+ "focus": {"focus": "...", "type": "written"},"question": {...},- "validation": {...},- "rounds": 1- },- ...- ]-}-```--### Mimic Mode - Output--```python-{- "reference_paper": "exam_name",- "kb_name": "math2211",- "total_reference_questions": 5,- "successful_generations": 5,- "failed_generations": 0,- "generated_questions": [- {- "success": True,- "reference_question_number": "1",- "reference_question_text": "Original question...",- "generated_question": {...},- "validation": {...},- "rounds": 2+ "analysis": {"relevance": "high", "kb_coverage": "..."}},...],- "output_file": "data/user/question/mimic_papers/mimic_20241211_120000_exam/..."+ "failures": []}```@@ -396,131 +316,83 @@ result = await mimic_exam_questions(### Custom Mode Directory Structure```-data/user/question/custom_YYYYMMDD_HHMMSS/-├── background_knowledge.json # RAG retrieval results-│ {-│ "queries": ["query1", "query2", "query3"],-│ "knowledge": {-│ "query1": {"chunks": [...], "entities": [...], "relations": [...]},-│ ...-│ }-│ }-│-├── question_plan.json # Question planning-│ {-│ "focuses": [-│ {"id": "q_1", "focus": "...", "type": "choice"},-│ {"id": "q_2", "focus": "...", "type": "written"},-│ ...-│ ]-│ }-│-├── question_1_result.json # Individual question + validation-├── question_2_result.json-└── ...+data/user/question/batch_YYYYMMDD_HHMMSS/+├── knowledge.json # RAG queries and retrievals+├── plan.json # Question focuses+├── q_1/+│ ├── result.json # Question + analysis+│ └── question.md # Human-readable format+├── q_2/+│ ├── result.json+│ └── question.md+└── summary.json # Overall summary```### Mimic Mode Directory Structure```-data/user/question/mimic_papers/-└── mimic_YYYYMMDD_HHMMSS_{pdf_name}/- ├── {pdf_name}.pdf # Original PDF- ├── auto/{pdf_name}.md # MinerU parsed markdown- ├── {pdf_name}_YYYYMMDD_HHMMSS_questions.json # Extracted reference questions- │ {- │ "total_questions": 4,- │ "questions": [- │ {"question_number": "1", "question_text": "...", "images": []},- │ ...- │ ]- │ }- │- └── {pdf_name}_YYYYMMDD_HHMMSS_generated_questions.json # Generated questions- {- "reference_paper": "...",- "kb_name": "...",- "total_reference_questions": 4,- "successful_generations": 4,- "generated_questions": [- {- "reference_question_text": "...",- "generated_question": {...},- "validation": {...}- },- ...- ]- }+data/user/question/mimic_papers/{paper_name}/+├── auto/{paper_name}.md # MinerU parsed markdown+├── {paper_name}_YYYYMMDD_HHMMSS_questions.json # Extracted reference questions+└── {paper_name}_YYYYMMDD_HHMMSS_generated.json # Generated questions```## Key Changes from Previous Version-### ✅ What's New--1. **Dual-Mode Architecture**- - Custom mode: Knowledge base-driven generation- - Mimic mode: Reference exam paper mimicking+### ✅ Architecture Changes-2. **Simplified Validation**- - Single-pass validation (no iterative refinement)- - Always approves questions (no rejection)- - Analyzes relevance: `highly_relevant` vs `partially_relevant`+1. **Unified BaseAgent**+ - All agents now inherit from `src/agents/base_agent.py`+ - Automatic LLM config, prompt loading, token tracking+ - No more separate ReAct base class-3. **Enhanced File Persistence**- - All intermediate files saved (background knowledge, plan)- - Mimic mode: Timestamped batch folders- - Complete traceability for debugging+2. **Specialized Agents**+ - `RetrieveAgent`: Knowledge retrieval only+ - `GenerateAgent`: Question generation only+ - `RelevanceAnalyzer`: Relevance analysis only (replaces ValidationWorkflow)-4. **Configurable RAG Queries**- - `rag_query_count` in `config/main.yaml`- - Previously hardcoded to 3+3. **No Iteration/Rejection**+ - Removed `max_rounds` from config+ - Single-pass generation + analysis+ - All questions accepted with relevance classification-5. **Real-time Progress Tracking**- - WebSocket streaming for live updates- - Mimic mode stages: uploading → parsing → extracting → generating+4. **Tools Moved**+ - `src/agents/question/tools/` → `src/tools/question/`+ - Import via `from src.tools.question import ...`-### ❌ What's Removed+### ❌ Removed-1. **Task Rejection Logic**- - Removed `reject_task` action from generation agent- - Questions always proceed to validation- - Validation analyzes relevance instead of rejecting+1. **Old ReAct Architecture**+ - `agents/base_agent.py` (ReAct paradigm)+ - `agents/generation_agent.py` (ReAct-based)+ - `agents/validation_agent.py` (deprecated)+ - `validation_workflow.py` (replaced by RelevanceAnalyzer)-2. **Iterative Refinement**- - No multi-round validation loop- - Single-pass generation + validation- - Reduces LLM calls and cost+2. **Iteration Logic**+ - No more validation loops+ - No more task rejection+ - No more request_modification/request_regeneration-3. **Standalone Validation Agent**- - Merged into `ValidationWorkflow`- - Simplified architecture+3. **Message Queue**+ - Agent communication simplified+ - Direct method calls instead of message passing## Migration Notes-If upgrading from the old structure:--**File Structure Changes:**-- `base_agent.py` → `agents/base_agent.py`-- `question_generation_agent.py` → `agents/generation_agent.py`-- `question_validation_agent.py` → `agents/validation_agent.py` (deprecated)-- `question_tools/retrieve.py` → Removed (use RAG tool directly)-- `parse_pdf_with_mineru.py` → `tools/pdf_parser.py`-- `extract_questions_from_paper.py` → `tools/question_extractor.py`-- `mimic_exam_paper.py` → `tools/exam_mimic.py`-- `question_validation_workflow.py` → `validation_workflow.py`-**Import Path Updates:**+```python# Old-from .base_agent import BaseAgent-from .question_tools import retrieve+from src.agents.question import BaseAgent, QuestionGenerationAgent+from src.tools.question import mimic_exam_questions# New-from .agents import BaseAgent-from src.tools import rag_search # Use RAG tool directly+from src.agents.question import RetrieveAgent, GenerateAgent, RelevanceAnalyzer+from src.tools.question import mimic_exam_questions```**API Changes:**+```python# Old - with rejection handlingresult = await coordinator.generate_question(requirement)@@ -530,9 +402,8 @@ if result.get("error") == "task_rejected":# New - always generates, check relevanceresult = await coordinator.generate_question(requirement)if result["success"]:- relevance = result["validation"]["relevance"]- if relevance == "highly_relevant":- print(result["validation"]["kb_coverage"])+ if result["validation"]["relevance"] == "high":+ print("Fully covered by KB:", result["validation"]["kb_coverage"])else:- print(result["validation"]["extension_points"])+ print("Extension question:", result["validation"]["extension_points"])```diff --git a/src/agents/question/__init__.py b/src/agents/question/__init__.pyindex 7bc729959..3dc8e3680 100644--- a/src/agents/question/__init__.py+++ b/src/agents/question/__init__.py@@ -1,28 +1,24 @@"""-Agent-based Question Generation System+Question Generation System-This is an autonomous question generation system based on the ReAct (Reasoning + Acting) paradigm.-Two independent agents collaborate to complete question generation and validation.+Modular question generation using specialized agents:+- RetrieveAgent: Knowledge base retrieval+- GenerateAgent: Question generation+- RelevanceAnalyzer: Question-KB relevance analysis+- AgentCoordinator: Workflow orchestration++Tools (moved to src/tools/question):+- parse_pdf_with_mineru+- extract_questions_from_paper+- mimic_exam_questions"""-from .agents import (- Action,- BaseAgent,- Message,- Observation,- QuestionGenerationAgent,- QuestionValidationAgent,-)+from .agents import GenerateAgent, RelevanceAnalyzer, RetrieveAgentfrom .coordinator import AgentCoordinator-from .validation_workflow import QuestionValidationWorkflow__all__ = [- "BaseAgent",- "Action",- "Observation",- "Message",- "QuestionGenerationAgent",- "QuestionValidationAgent",- "QuestionValidationWorkflow",+ "RetrieveAgent",+ "GenerateAgent",+ "RelevanceAnalyzer","AgentCoordinator",]diff --git a/src/agents/question/agents/__init__.py b/src/agents/question/agents/__init__.pyindex cbe1c9469..e70106fa2 100644--- a/src/agents/question/agents/__init__.py+++ b/src/agents/question/agents/__init__.py@@ -1,17 +1,18 @@"""Question Generation Agents-Agent modules for question generation and validation++Specialized agents for question generation workflow:+- RetrieveAgent: Knowledge retrieval from KB+- GenerateAgent: Question generation+- RelevanceAnalyzer: Question-KB relevance analysis"""-from .base_agent import Action, BaseAgent, Message, Observation-from .generation_agent import QuestionGenerationAgent-from .validation_agent import QuestionValidationAgent+from .generate_agent import GenerateAgent+from .relevance_analyzer import RelevanceAnalyzer+from .retrieve_agent import RetrieveAgent__all__ = [- "BaseAgent",- "Action",- "Observation",- "Message",- "QuestionGenerationAgent",- "QuestionValidationAgent",+ "RetrieveAgent",+ "GenerateAgent",+ "RelevanceAnalyzer",]diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.pydeleted file mode 100644index a8535d016..000000000--- a/src/agents/question/agents/base_agent.py+++ /dev/null@@ -1,561 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Base Agent class - Implements the ReAct (Reasoning + Acting) paradigm.--Uses the unified LLM Factory for all LLM calls, supporting:-- Cloud providers (OpenAI, Anthropic, DeepSeek, etc.)-- Local providers (Ollama, LM Studio, vLLM, etc.)-- Automatic retry with exponential backoff-"""--from abc import ABC, abstractmethod-from collections.abc import Callable-import json-import os-from pathlib import Path-import sys-from typing import Any--from dotenv import load_dotenv-from openai import AsyncAzureOpenAI, AsyncOpenAI--# Load environment variables-load_dotenv(override=False)--# Add project root for imports-project_root = Path(__file__).parent.parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.logging import get_logger-from src.services.config import get_agent_params-from src.services.llm import complete as llm_complete-from src.services.llm.capabilities import supports_response_format-from src.services.llm.config import get_llm_config--# Module logger-_logger = get_logger("QuestionAgent")---class Action:- """Represents an Agent action"""-- def __init__(self, name: str, **params):- self.name = name- self.params = params-- def __repr__(self):- params_str = ", ".join([f"{k}={v}" for k, v in self.params.items()])- return f"Action({self.name}, {params_str})"---class Observation:- """Represents the observation result of an action"""-- def __init__(self, success: bool, result: Any, message: str = ""):- self.success = success- self.result = result- self.message = message-- def __repr__(self):- return f"Observation(success={self.success}, message={self.message})"---class Message:- """Message passed between agents"""-- def __init__(self, from_agent: str, to_agent: str, message_type: str, content: dict[str, Any]):- self.from_agent = from_agent- self.to_agent = to_agent- self.message_type = message_type- self.content = content-- def __repr__(self):- return f"Message({self.from_agent} -> {self.to_agent}: {self.message_type})"---class BaseAgent(ABC):- """- Base Agent class implementing ReAct paradigm-- Subclasses need to implement:- - get_available_actions(): Return available action list- - execute_action(): Execute specific action- - get_system_prompt(): Return system prompt- """-- def __init__(- self,- agent_name: str,- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- model: str | None = None,- max_iterations: int = 10,- kb_name: str | None = None,- token_stats_callback: Callable | None = None,- language: str = "en",- ):- self.agent_name = agent_name- self.max_iterations = max_iterations- self.kb_name = kb_name- self.token_stats_callback = token_stats_callback- self.language = language-- # Load agent parameters from unified config (agents.yaml)- self._agent_params = get_agent_params("question")-- # Load LLM configuration via unified config system- try:- llm_config = get_llm_config()- self.api_key = api_key or llm_config.api_key- self.base_url = base_url or llm_config.base_url- self.api_version = api_version or llm_config.api_version- self.binding = llm_config.binding or "openai"- self.model = model or llm_config.model- except Exception:- # Fallback to environment variables- self.api_key = api_key or os.getenv("LLM_API_KEY")- self.base_url = base_url or os.getenv("LLM_HOST")- self.api_version = api_version or os.getenv("LLM_API_VERSION")- self.binding = os.getenv("LLM_BINDING", "openai")- self.model = model or os.getenv("LLM_MODEL")-- 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."- )-- # Initialize OpenAI client for direct API calls- if self.binding == "azure":- self.client = AsyncAzureOpenAI(- api_key=self.api_key,- azure_endpoint=self.base_url,- api_version=self.api_version or "2024-02-15-preview",- )- else:- self.client = AsyncOpenAI(- api_key=self.api_key,- base_url=self.base_url,- )-- self.thought_history: list[str] = []- self.action_history: list[Action] = []- self.observation_history: list[Observation] = []- self.retrieved_knowledge: list[dict[str, Any]] = []-- self.inbox: list[Message] = []-- @abstractmethod- def get_available_actions(self) -> list[dict[str, str]]:- """- Return available action list-- Returns:- List[Dict]: [{"name": "action_name", "description": "action_desc", "parameters": "param_desc"}, ...]- """-- @abstractmethod- async def execute_action(self, action: Action) -> Observation:- """- Execute specific action-- Args:- action: Action to execute-- Returns:- Observation: Observation result of the action- """-- @abstractmethod- def get_system_prompt(self) -> str:- """- Return system prompt-- Returns:- str: System prompt- """-- def receive_message(self, message: Message):- """Receive message from other Agent."""- self.inbox.append(message)- _logger.debug(f"[{self.agent_name}] Received message: {message}")-- def format_history(self) -> str:- """Format history"""- if not self.thought_history:- return "(No history)"-- history_parts = []-- recent_count = min(3, len(self.action_history))- if recent_count > 0:- history_parts.append("🔥 **Recent Actions** (Must read! Avoid repeating actions)")- history_parts.append("=" * 60)- for i in range(len(self.action_history) - recent_count, len(self.action_history)):- action = self.action_history[i]- obs = self.observation_history[i] if i < len(self.observation_history) else None- status = "✓ Success" if (obs and obs.success) else "✗ Failed"-- history_parts.append(f" [{i + 1}] Action: {action.name} → {status}")- if action.params:- history_parts.append(- f" Params: {json.dumps(action.params, ensure_ascii=False)}"- )- if obs and obs.message:- history_parts.append(f" Result: {obs.message}")- history_parts.append(- "⚠️ Please decide next step based on recent actions, avoid repeating the same actions!"- )- history_parts.append("=" * 60 + "\n")-- if self.retrieved_knowledge:- history_parts.append("📚 **Retrieved Knowledge Summary** (No need to retrieve again)")- history_parts.append("=" * 60)- for i, k in enumerate(self.retrieved_knowledge, 1):- query = k.get("query", "N/A")- num_entities = len(k.get("entities", []))- num_relations = len(k.get("relations", []))- num_text = len(k.get("text_chunks", []))- num_multimodal = len(k.get("multimodal_chunks", []))- history_parts.append(- f' {i}. Query: "{query}" → '- f"{num_entities} entities, {num_relations} relations, "- f"{num_text} text chunks, {num_multimodal} multimodal content"- )- history_parts.append("=" * 60 + "\n")-- if len(self.thought_history) > 0:- history_parts.append("📜 **Complete History**")- history_parts.append("-" * 60)- for i in range(len(self.thought_history)):- history_parts.append(f"\nRound {i + 1}:")- history_parts.append(f"Thought: {self.thought_history[i]}")-- if i < len(self.action_history):- action = self.action_history[i]- history_parts.append(f"Action: {action.name}")- if action.params:- history_parts.append(- f" Params: {json.dumps(action.params, ensure_ascii=False)}"- )-- if i < len(self.observation_history):- obs = self.observation_history[i]- status = "✓ Success" if obs.success else "✗ Failed"- history_parts.append(f"Observation: {status}")- if obs.message:- history_parts.append(f" Message: {obs.message}")- history_parts.append("-" * 60)-- return "\n".join(history_parts)-- def format_inbox(self) -> str:- """Format inbox"""- if not self.inbox:- return "(Inbox is empty)"-- inbox_parts = []- for msg in self.inbox:- inbox_parts.append(f"- From {msg.from_agent}: {msg.message_type}")- inbox_parts.append(- f" Content: {json.dumps(msg.content, ensure_ascii=False, indent=2)}"- )-- return "\n".join(inbox_parts)-- async def think(self, task: str, context: dict[str, Any] = None) -> dict[str, Any]:- """- Think about next action-- Args:- task: Current task description- context: Additional context information-- Returns:- Dict: {"thought": str, "action": str, "parameters": Dict}- """- system_prompt = self.get_system_prompt()-- actions_desc = "\n".join(- [- f"- **{a['name']}**: {a['description']}\n Parameters: {a['parameters']}"- for a in self.get_available_actions()- ]- )-- # Build context description- context_info = ""- if context:- # Check if it's a new round iteration- round_num = context.get("round_num")- is_new_round = context.get("is_new_round", False)-- if round_num and round_num > 1:- context_info = (- f"\n{'=' * 60}\n⚠️ Important note: This is round {round_num} iteration\n"- )- if is_new_round:- context_info += "- Work in history was for previous version of question/task\n"- context_info += (- "- Now received new content, need to re-execute complete workflow\n"- )- context_info += "- Can reference retrieved knowledge from history, but don't skip necessary steps\n"- context_info += "- Special note: Even if validated/generated before, need to re-process now\n"- context_info += f"{'=' * 60}\n"-- context_info += (- f"\nCurrent context:\n{json.dumps(context, ensure_ascii=False, indent=2)}\n"- )-- user_prompt = f"""Current task: {task}-{context_info}-Inbox:-{self.format_inbox()}--History:-{self.format_history()}--Available actions:-{actions_desc}--Please think and decide the next action.--Output JSON format:-{{- "thought": "your thinking process",- "action": "action name",- "parameters": {{"parameter_name": "parameter_value"}}-}}--⚠️ **Important notes**:-1. **Must read history**: Check "Recent actions" section to understand what you just did-2. **Avoid duplicate actions**: If you just successfully executed an action, don't execute the same action again!-3. **Logical flow**: Based on recent action results, choose reasonable next action- - Example: retrieve → generate → submit, not generate → generate-4. If inbox has messages, process messages first-5. History can be referenced, but if it's a new round, must re-execute key steps-"""-- # Build kwargs for LLM Factory- llm_kwargs = {- "temperature": self._agent_params["temperature"],- "max_tokens": self._agent_params["max_tokens"],- }-- # Only add response_format if the provider supports it- if supports_response_format(self.binding, self.model):- llm_kwargs["response_format"] = {"type": "json_object"}-- # Call LLM via unified Factory (supports all providers with retry)- response_content = await llm_complete(- prompt=user_prompt,- system_prompt=system_prompt,- model=self.model,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- binding=self.binding,- **llm_kwargs,- )-- # Update token statistics if callback is available- # Note: Factory doesn't return token counts, estimate based on response- if self.token_stats_callback:- # Rough estimation: ~4 chars per token- input_tokens = (len(system_prompt) + len(user_prompt)) // 4- output_tokens = len(response_content) // 4- self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model- )-- # Log LLM call with detailed information- _logger.log_llm_call(- model=self.model,- stage="think",- system_prompt=system_prompt,- user_prompt=user_prompt,- response=response_content,- agent_name=self.agent_name,- input_tokens=0, # Not available from factory- output_tokens=0,- cost=0.0,- level="DEBUG",- )-- result = json.loads(response_content)-- # Record thought- thought = result.get("thought", "")- self.thought_history.append(thought)-- _logger.debug(f"[{self.agent_name}] Thinking: {thought[:100]}...")-- return result-- async def act(self, action_name: str, parameters: dict[str, Any]) -> Observation:- """- Execute an action-- Args:- action_name: Action name- parameters: Action parameters-- Returns:- Observation: Observation result- """- action = Action(action_name, **parameters)- self.action_history.append(action)-- _logger.info(f"[{self.agent_name}] Action: {action_name}")- if parameters:- _logger.debug(f" Parameters: {json.dumps(parameters, ensure_ascii=False)[:100]}")-- observation = await self.execute_action(action)- self.observation_history.append(observation)-- if observation.success:- _logger.debug(f"[{self.agent_name}] Observation: Success")- else:- _logger.warning(f"[{self.agent_name}] Observation: Failed")- if observation.message:- _logger.debug(f" Message: {observation.message[:100]}")-- # Print detailed information about action results- if observation.success and observation.result:- self._print_result(action_name, observation.result)-- return observation-- def _print_result(self, action_name: str, result: Any):- """Log action result details."""- try:- if action_name == "retrieve":- # Retrieval action result- if isinstance(result, dict):- entities = result.get("entities", [])- relations = result.get("relations", [])- text_chunks = result.get("text_chunks", [])- multimodal_chunks = result.get("multimodal_chunks", [])-- _logger.debug(- f" Result: {len(entities)} entities, {len(relations)} relations, {len(text_chunks)} text chunks, {len(multimodal_chunks)} multimodal items"- )-- elif action_name == "generate_question":- # Generate question result- if isinstance(result, dict):- q_type = result.get("question_type", "N/A")- _logger.debug(f" Result: Generated {q_type} type question")-- elif action_name == "refine_question":- # Refine question result- if isinstance(result, dict):- q_type = result.get("question_type", "N/A")- _logger.debug(f" Result: Refined {q_type} type question")-- elif action_name == "validate":- # Validation result- if isinstance(result, dict):- decision = result.get("decision", "N/A")- issues = result.get("issues", [])- _logger.debug(- f" Result: Validation decision = {decision}, {len(issues)} issues"- )-- elif action_name == "reject_task":- # Task rejection result- if isinstance(result, dict):- reason = result.get("reason", "N/A")- _logger.info(f" Result: Task rejected - {reason[:100]}")-- elif action_name in [- "submit_question",- "request_modification",- "request_regeneration",- "approve_question",- ]:- # Message sending actions- _logger.debug(" Result: Message sent")-- # Other actions- elif isinstance(result, dict):- _logger.debug(f" Result: {json.dumps(result, ensure_ascii=False)[:80]}...")- elif isinstance(result, str):- _logger.debug(f" Result: {result[:80]}...")-- except Exception:- # Log failure should not affect main flow- pass-- async def run(- self,- task: str,- context: dict[str, Any] = None,- send_message_callback: Callable | None = None,- ) -> dict[str, Any]:- """- Run the main loop of the Agent (think-act-observe)-- Args:- task: Task description- context: Initial context- send_message_callback: Callback function for sending messages-- Returns:- Dict: Execution result- """- _logger.info(f"[{self.agent_name}] Starting task execution")- _logger.debug(f" Task: {task[:80]}...")-- self.send_message = send_message_callback-- for iteration in range(self.max_iterations):- _logger.info(- f"[{self.agent_name}] ReAct iteration {iteration + 1}/{self.max_iterations}"- )-- # Think- decision = await self.think(task, context)-- # Act- action_name = decision.get("action")- parameters = decision.get("parameters", {})-- observation = await self.act(action_name, parameters)-- # Check if submitted (for QuestionGenerationAgent)- if hasattr(self, "submitted") and self.submitted:- _logger.success(f"[{self.agent_name}] Question submitted, task completed")- return {"success": True, "result": observation.result, "iterations": iteration + 1}-- # Check if completed- # These actions indicate the Agent has completed the current stage- terminal_actions = [- "submit_question", # Generation agent submits question- "approve_question", # Validation agent approves question- "request_modification", # Validation agent requests modification- "request_regeneration", # Validation agent requests regeneration- "reject_task", # Generation agent rejects task- "finish", # Generic completion flag- ]-- if action_name in terminal_actions:- _logger.success(f"[{self.agent_name}] Task completed")- return {"success": True, "result": observation.result, "iterations": iteration + 1}-- _logger.warning(f"[{self.agent_name}] Max iterations reached")- return {- "success": False,- "error": "Max iterations reached",- "iterations": self.max_iterations,- }-- def reset(self):- """Reset Agent state"""- self.thought_history.clear()- self.action_history.clear()- self.observation_history.clear()- self.inbox.clear()diff --git a/src/agents/question/agents/generate_agent.py b/src/agents/question/agents/generate_agent.pynew file mode 100644index 000000000..341112e6f--- /dev/null+++ b/src/agents/question/agents/generate_agent.py@@ -0,0 +1,378 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+GenerateAgent - Responsible for generating questions based on knowledge context.++Uses unified BaseAgent for LLM calls and configuration management.+"""++import json+import re+from typing import Any++from src.agents.base_agent import BaseAgent+++class GenerateAgent(BaseAgent):+ """+ Agent responsible for generating questions from knowledge context.++ Responsibilities:+ - Generate questions based on requirements and knowledge+ - Support both custom mode (from scratch) and mimic mode (from reference)+ - Output structured question JSON+ """++ def __init__(+ self,+ language: str = "en",+ **kwargs,+ ):+ """+ Initialize GenerateAgent.++ Args:+ language: Language for prompts ("en" or "zh")+ **kwargs: Additional arguments passed to BaseAgent+ """+ super().__init__(+ module_name="question",+ agent_name="generate_agent",+ language=language,+ **kwargs,+ )++ async def process(+ self,+ requirement: dict[str, Any],+ knowledge_context: str,+ focus: dict[str, Any] | None = None,+ reference_question: str | None = None,+ ) -> dict[str, Any]:+ """+ Main processing: generate a question.++ Args:+ requirement: Question requirement dict (knowledge_point, difficulty, question_type, etc.)+ knowledge_context: Retrieved knowledge summary+ focus: Optional focus/angle for the question+ reference_question: Optional reference question for mimic mode++ Returns:+ Dict with:+ - success: Whether generation succeeded+ - question: Generated question dict (if success)+ - error: Error message (if failed)+ """+ self.logger.info("Starting question generation")++ # Build requirements string+ requirements_str = json.dumps(requirement, ensure_ascii=False, indent=2)++ # Build focus string+ if focus:+ focus_str = f"Focus: {focus.get('focus', '')}\nType: {focus.get('type', requirement.get('question_type', 'written'))}"+ else:+ focus_str = f"Type: {requirement.get('question_type', 'written')}"++ # Choose prompt based on mode+ if reference_question:+ # Mimic mode+ return await self._generate_with_reference(+ requirements_str=requirements_str,+ knowledge_context=knowledge_context,+ reference_question=reference_question,+ )+ else:+ # Custom mode+ return await self._generate_custom(+ requirements_str=requirements_str,+ knowledge_context=knowledge_context,+ focus_str=focus_str,+ knowledge_point=requirement.get("knowledge_point", ""),+ )++ async def _generate_custom(+ self,+ requirements_str: str,+ knowledge_context: str,+ focus_str: str,+ knowledge_point: str,+ ) -> dict[str, Any]:+ """+ Generate a custom question (not based on reference).++ Args:+ requirements_str: JSON string of requirements+ knowledge_context: Retrieved knowledge summary+ focus_str: Focus/angle description+ knowledge_point: Main knowledge point++ Returns:+ Dict with success status and question/error+ """+ system_prompt = self.get_prompt("system", "")+ user_prompt_template = self.get_prompt("generate", "")++ if not user_prompt_template:+ # Fallback prompt+ user_prompt_template = (+ "Generate a question based on:\n"+ "Requirements: {requirements}\n"+ "Focus: {focus}\n"+ "Knowledge: {knowledge}\n\n"+ "Return JSON with question_type, question, correct_answer, explanation."+ )++ user_prompt = user_prompt_template.format(+ requirements=requirements_str,+ focus=focus_str,+ knowledge=knowledge_context[:4000] if len(knowledge_context) > 4000 else knowledge_context,+ )++ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="generate_question",+ )++ question = self._parse_question_response(response)+ question["knowledge_point"] = knowledge_point++ self.logger.info(f"Generated {question.get('question_type', 'unknown')} question")++ return {+ "success": True,+ "question": question,+ }++ except Exception as e:+ self.logger.error(f"Question generation failed: {e}")+ return {+ "success": False,+ "error": str(e),+ }++ async def _generate_with_reference(+ self,+ requirements_str: str,+ knowledge_context: str,+ reference_question: str,+ ) -> dict[str, Any]:+ """+ Generate a question based on a reference (mimic mode).++ Args:+ requirements_str: JSON string of requirements+ knowledge_context: Retrieved knowledge summary+ reference_question: Reference question text++ Returns:+ Dict with success status and question/error+ """+ system_prompt = self.get_prompt("system", "")+ user_prompt_template = self.get_prompt("generate_with_reference", "")++ if not user_prompt_template:+ # Fallback prompt+ user_prompt_template = (+ "Generate a new question inspired by the reference but distinct:\n"+ "Reference: {reference_question}\n"+ "Requirements: {requirements}\n"+ "Knowledge: {knowledge}\n\n"+ "Return JSON with question_type, question, correct_answer, explanation."+ )++ user_prompt = user_prompt_template.format(+ reference_question=reference_question,+ requirements=requirements_str,+ knowledge=knowledge_context[:4000] if len(knowledge_context) > 4000 else knowledge_context,+ )++ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="generate_with_reference",+ )++ question = self._parse_question_response(response)++ self.logger.info(f"Generated mimic {question.get('question_type', 'unknown')} question")++ return {+ "success": True,+ "question": question,+ }++ except Exception as e:+ self.logger.error(f"Reference-based generation failed: {e}")+ return {+ "success": False,+ "error": str(e),+ }++ def _parse_question_response(self, response: str) -> dict[str, Any]:+ """+ Parse LLM response into question dict.++ Uses robust JSON extraction that handles:+ - Markdown code blocks+ - Control characters in LaTeX formulas+ - Python triple-quoted strings+ - Partial JSON extraction++ Args:+ response: LLM response string++ Returns:+ Parsed question dict++ Raises:+ ValueError: If parsing fails+ """+ if not response or not response.strip():+ raise ValueError("LLM returned empty response")++ # Try to extract JSON from markdown code blocks if present+ json_content = self._extract_json_from_markdown(response)++ # Clean control characters that may break JSON parsing+ json_content = self._clean_json_string(json_content)++ # Try multiple parsing strategies+ question = None+ parse_error = None++ # Strategy 1: Direct parse+ try:+ question = json.loads(json_content)+ except json.JSONDecodeError as e:+ parse_error = e++ # Strategy 2: Try extracting JSON object pattern+ if question is None:+ json_obj_pattern = re.compile(r"\{[\s\S]*\}")+ match = json_obj_pattern.search(json_content)+ if match:+ try:+ question = json.loads(match.group(0))+ except json.JSONDecodeError:+ pass++ # Strategy 3: Try fixing common LLM JSON issues+ if question is None:+ try:+ fixed_content = self._fix_common_json_issues(json_content)+ question = json.loads(fixed_content)+ except json.JSONDecodeError:+ pass++ if question is None:+ raise ValueError(f"Failed to parse question JSON: {parse_error}") from parse_error++ # Validate required fields+ if "question" not in question:+ raise ValueError("Question response missing 'question' field")++ # Ensure question_type exists+ if "question_type" not in question:+ question["question_type"] = "written"++ # Validate options for choice questions+ if question.get("question_type") == "choice":+ options = question.get("options")+ if not options:+ # Create default options if missing+ self.logger.warning("Choice question missing options, adding placeholder")+ question["options"] = {+ "A": "Option A (placeholder)",+ "B": "Option B (placeholder)",+ "C": "Option C (placeholder)",+ "D": "Option D (placeholder)",+ }+ elif not isinstance(options, dict):+ # Convert to dict if it's a list or other format+ self.logger.warning(f"Options is not a dict: {type(options)}, converting")+ if isinstance(options, list):+ question["options"] = {+ chr(65 + i): str(opt) for i, opt in enumerate(options[:4])+ }+ else:+ question["options"] = {"A": str(options)}+ elif len(options) < 2:+ self.logger.warning(f"Choice question has only {len(options)} options")++ return question++ def _clean_json_string(self, json_str: str) -> str:+ """+ Clean JSON string by removing/escaping problematic characters.++ Handles:+ - Control characters (0x00-0x1f except tab, newline, carriage return)+ - Unescaped newlines inside string values+ """+ if not json_str:+ return json_str++ # Remove most control characters but keep \t, \n, \r+ # These can appear in LLM output and break JSON parsing+ cleaned = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", json_str)++ return cleaned++ def _fix_common_json_issues(self, content: str) -> str:+ """+ Attempt to fix common JSON issues from LLM output.++ Fixes:+ - Python triple-quoted strings converted to JSON strings+ - Trailing commas before closing braces/brackets+ """+ if not content:+ return content++ # Fix Python triple-quoted strings (LLMs sometimes generate these)+ def replace_triple_quotes(match: re.Match) -> str:+ inner = match.group(1)+ # Use json.dumps to properly escape the content+ return json.dumps(inner)++ content = re.sub(r'"""([\s\S]*?)"""', replace_triple_quotes, content)++ # Remove trailing commas before } or ]+ content = re.sub(r",\s*([}\]])", r"\1", content)++ return content++ def _extract_json_from_markdown(self, content: str) -> str:+ """+ Extract JSON from markdown code blocks.++ LLMs often wrap JSON in ```json ... ``` blocks. This method strips+ the markdown formatting and any surrounding text.++ Args:+ content: Raw LLM response++ Returns:+ Extracted JSON string+ """+ if not content:+ return content++ # Try to find JSON code block+ json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"+ matches = re.findall(json_block_pattern, content, re.DOTALL)++ if matches:+ # Return the content inside the first code block+ return matches[0].strip()++ # If no code blocks found, return as-is (might already be valid JSON)+ return content.strip()+diff --git a/src/agents/question/agents/generation_agent.py b/src/agents/question/agents/generation_agent.pydeleted file mode 100644index 674cc5434..000000000--- a/src/agents/question/agents/generation_agent.py+++ /dev/null@@ -1,408 +0,0 @@-#!/usr/bin/env python-"""-Question Generation Agent - responsible for creating and refining questions.-Uses unified PromptManager for prompt loading.-"""--import json-from pathlib import Path-import sys-from typing import Any--# Add project root to sys.path-project_root = Path(__file__).parent.parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.logging import get_logger-from src.services.config import load_config_with_main-from src.services.prompt import get_prompt_manager-from src.tools.rag_tool import rag_search--from .base_agent import Action, BaseAgent, Message, Observation--# Module logger-_logger = get_logger("QuestionGenerationAgent")---class QuestionGenerationAgent(BaseAgent):- """Question generation agent"""-- def __init__(self, language: str = "en", **kwargs):- super().__init__(agent_name="QuestionGenerationAgent", language=language, **kwargs)-- # Load prompts using unified PromptManager- self._prompts = get_prompt_manager().load_prompts(- module_name="question",- agent_name="generation_agent",- language=language,- )-- # Load config for RAG settings- self._config = load_config_with_main("question_config.yaml", project_root)-- # State- self.current_requirement = None- self.current_question = None- self.retrieved_knowledge = [] # Retrieved knowledge- self.submitted = False # Whether a question has been submitted-- def reset(self):- """Reset agent state, including custom fields."""- super().reset()- self.current_requirement = None- self.current_question = None- self.retrieved_knowledge = []- self.submitted = False-- def get_system_prompt(self) -> str:- return self._prompts.get("system", "")-- def get_available_actions(self) -> list[dict[str, str]]:- """Return available actions for the agent."""- return [- {- "name": "retrieve",- "description": "Retrieve relevant knowledge from the knowledge base",- "parameters": "query (str): search query",- },- {- "name": "generate_question",- "description": "Generate a new question based on retrieved knowledge",- "parameters": "none",- },- {- "name": "refine_question",- "description": "Refine the question according to validation feedback",- "parameters": "none",- },- {- "name": "submit_question",- "description": "Submit the current question to the Validation Agent",- "parameters": "none",- },- ]-- async def execute_action(self, action: Action) -> Observation:- """Execute concrete actions."""- try:- if action.name == "retrieve":- return await self._action_retrieve(action.params)-- if action.name == "generate_question":- return await self._action_generate_question()-- if action.name == "refine_question":- return await self._action_refine_question()-- if action.name == "submit_question":- return await self._action_submit_question()-- return Observation(success=False, result=None, message=f"Unknown action: {action.name}")-- except Exception as e:- return Observation(- success=False, result=None, message=f"Action execution failed: {e!s}"- )-- async def _action_retrieve(self, params: dict[str, Any]) -> Observation:- """Retrieve knowledge from the KB."""- query = params.get("query", "")-- if not query:- return Observation(success=False, result=None, message="Search query cannot be empty")-- # Get RAG mode from config- question_cfg = self._config.get("question", {})- rag_mode = question_cfg.get("rag_mode", "hybrid")-- # Use unified RAG tool- result = await rag_search(- query=query,- kb_name=self.kb_name,- mode=rag_mode,- only_need_context=True,- )-- answer = result.get("answer", "")-- # Save retrieved knowledge- self.retrieved_knowledge.append(- {- "query": query,- "answer": answer,- }- )-- # Summarize result- answer_len = len(answer) if answer else 0- summary = f"Retrieved context with {answer_len} characters for query: {query[:50]}..."-- return Observation(success=True, result={"answer": answer}, message=summary)-- async def _action_generate_question(self) -> Observation:- """Generate a question."""- if not self.retrieved_knowledge:- return Observation(- success=False, result=None, message="Run retrieve before generating a question"- )-- # Format retrieved knowledge- knowledge_parts = []- for k in self.retrieved_knowledge:- knowledge_parts.append(f"=== Query: {k['query']} ===")- answer = k.get("answer", "")- if answer:- # Truncate very long contexts- if len(answer) > 3000:- answer = answer[:3000] + "...[truncated]"- knowledge_parts.append(answer)- knowledge_parts.append("")-- knowledge_str = "\n".join(knowledge_parts)-- # Check whether a reference question exists- reference_question = self.current_requirement.get("reference_question")-- # Call LLM to generate the question- if reference_question:- # Use reference-aware prompt- prompt_template = self._prompts.get("generate_with_reference", "")- prompt = prompt_template.format(- reference_question=reference_question,- requirements=json.dumps(self.current_requirement, ensure_ascii=False, indent=2),- knowledge=knowledge_str,- )- else:- # Use standard prompt- prompt_template = self._prompts.get("generate", "")- prompt = prompt_template.format(- requirements=json.dumps(self.current_requirement, ensure_ascii=False, indent=2),- knowledge=knowledge_str,- )-- response = await self.client.chat.completions.create(- model=self.model,- messages=[- {"role": "system", "content": "You are a professional question designer"},- {"role": "user", "content": prompt},- ],- temperature=self._agent_params["temperature"],- max_tokens=self._agent_params["max_tokens"],- response_format={"type": "json_object"},- )-- # Extract response content- response_content = response.choices[0].message.content-- # Update token statistics if callback is available- input_tokens = 0- output_tokens = 0- cost = 0.0- if hasattr(response, "usage") and response.usage:- input_tokens = response.usage.prompt_tokens- output_tokens = response.usage.completion_tokens- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006- if self.token_stats_callback:- self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model- )-- # Log LLM call with detailed information- _logger.log_llm_call(- model=self.model,- stage="generate_question",- system_prompt="You are a professional question designer",- user_prompt=prompt,- response=response_content,- agent_name="QuestionGenerationAgent",- input_tokens=input_tokens,- output_tokens=output_tokens,- cost=cost,- level="DEBUG",- )-- # Parse JSON with error handling- try:- question = json.loads(response_content)- self.current_question = question- except json.JSONDecodeError as e:- error_msg = (- f"[generate_question] Failed to parse JSON response: {e}\n"- f"Response content: {response_content[:500]}..."- )- _logger.error(error_msg)- return Observation(- success=False, result=None, message=f"Failed to parse question JSON: {e}"- )-- # Automatically submit after generation- submit_result = await self._action_submit_question()- self.submitted = True # Mark as submitted-- # Return the submission result to stop the loop- return submit_result-- async def _action_refine_question(self) -> Observation:- """Refine the question."""- if not self.current_question:- return Observation(- success=False, result=None, message="No question available for refinement"- )-- # Get feedback from inbox- feedback_msg = None- for msg in self.inbox:- if msg.message_type in ["request_modification", "request_regeneration"]:- feedback_msg = msg- break-- if not feedback_msg:- return Observation(success=False, result=None, message="No validation feedback found")-- # Format retrieved knowledge- knowledge_parts = []- for k in self.retrieved_knowledge:- knowledge_parts.append(f"=== Query: {k['query']} ===")- answer = k.get("answer", "")- if answer:- # Truncate very long contexts- if len(answer) > 3000:- answer = answer[:3000] + "...[truncated]"- knowledge_parts.append(answer)- knowledge_parts.append("")- knowledge_str = "\n".join(knowledge_parts)-- # Call LLM to refine the question- prompt_template = self._prompts.get("refine", "")- prompt = prompt_template.format(- original_question=json.dumps(self.current_question, ensure_ascii=False, indent=2),- feedback=json.dumps(feedback_msg.content, ensure_ascii=False, indent=2),- knowledge=knowledge_str,- )-- # Log request details- _logger.debug(- f"[refine_question] Calling LLM: model={self.model}, "- f"prompt_len={len(prompt)}, temperature={self._agent_params['temperature']}"- )-- try:- response = await self.client.chat.completions.create(- model=self.model,- messages=[- {"role": "system", "content": "You are a professional question designer"},- {"role": "user", "content": prompt},- ],- temperature=self._agent_params["temperature"],- max_tokens=self._agent_params["max_tokens"],- response_format={"type": "json_object"},- timeout=180.0, # Add timeout- )- except Exception as e:- error_msg = f"[refine_question] LLM API call failed: {type(e).__name__}: {e}"- _logger.error(error_msg)- return Observation(- success=False, result=None, message=f"Failed to refine question: {e}"- )-- # Validate response structure- if not response or not response.choices:- error_msg = "[refine_question] LLM returned empty response or no choices"- _logger.error(error_msg)- return Observation(success=False, result=None, message="LLM returned empty response")-- # Extract response content with validation- response_content = response.choices[0].message.content-- # Validate content is not None or empty- if response_content is None:- error_msg = f"[refine_question] LLM returned None content. Response: {response}"- _logger.error(error_msg)- return Observation(success=False, result=None, message="LLM returned None content")-- if not response_content.strip():- error_msg = f"[refine_question] LLM returned empty string. Response: {response}"- _logger.error(error_msg)- return Observation(success=False, result=None, message="LLM returned empty string")-- # Log successful response- _logger.debug(- f"[refine_question] LLM response received: "- f"length={len(response_content)}, preview={response_content[:200]}..."- )-- # Update token statistics if callback is available- input_tokens = 0- output_tokens = 0- cost = 0.0- if hasattr(response, "usage") and response.usage:- input_tokens = response.usage.prompt_tokens- output_tokens = response.usage.completion_tokens- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006- if self.token_stats_callback:- self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model- )-- # Log LLM call with detailed information- _logger.log_llm_call(- model=self.model,- stage="refine_question",- system_prompt="You are a professional question designer",- user_prompt=prompt,- response=response_content,- agent_name="QuestionGenerationAgent",- input_tokens=input_tokens,- output_tokens=output_tokens,- cost=cost,- level="DEBUG",- )-- # Parse JSON with error handling- try:- question = json.loads(response_content)- self.current_question = question- except json.JSONDecodeError as e:- error_msg = (- f"[refine_question] Failed to parse JSON response: {e}\n"- f"Response content: {response_content[:500]}..."- )- _logger.error(error_msg)- return Observation(- success=False, result=None, message=f"Failed to parse question JSON: {e}"- )-- # Remove the processed feedback message- self.inbox.remove(feedback_msg)-- # Automatically submit after refinement- submit_result = await self._action_submit_question()- self.submitted = True # Mark as submitted-- # Return submission result to stop the loop- return submit_result-- async def _action_submit_question(self) -> Observation:- """Submit the current question to validation."""- if not self.current_question:- return Observation(success=False, result=None, message="There is no question to submit")-- # Send validation request- if hasattr(self, "send_message") and self.send_message:- message = Message(- from_agent=self.agent_name,- to_agent="QuestionValidationAgent",- message_type="validate_request",- content={"question": self.current_question},- )- await self.send_message(message)-- return Observation(- success=True,- result=self.current_question,- message="Question submitted to Validation Agent",- )-- def set_requirement(self, requirement: dict[str, Any]):- """Set the current generation requirement"""- self.current_requirement = requirementdiff --git a/src/agents/question/agents/relevance_analyzer.py b/src/agents/question/agents/relevance_analyzer.pynew file mode 100644index 000000000..00c65fb60--- /dev/null+++ b/src/agents/question/agents/relevance_analyzer.py@@ -0,0 +1,206 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+RelevanceAnalyzer - Analyzes the relevance between questions and knowledge base.++Replaces the old validation workflow with a single-pass relevance analysis.+No iterative validation or rejection - all questions are accepted and analyzed.+"""++import json+import re+from typing import Any++from src.agents.base_agent import BaseAgent+++class RelevanceAnalyzer(BaseAgent):+ """+ Agent responsible for analyzing question-knowledge relevance.++ Key difference from old ValidationWorkflow:+ - NO rejection: all questions are accepted+ - NO iteration: single-pass analysis+ - Output: relevance level (high/partial) with explanations++ Responsibilities:+ - Analyze how well a question aligns with knowledge base content+ - Identify what KB concepts the question tests+ - Identify any extensions beyond the KB (for "partial" relevance)+ """++ def __init__(+ self,+ language: str = "en",+ **kwargs,+ ):+ """+ Initialize RelevanceAnalyzer.++ Args:+ language: Language for prompts ("en" or "zh")+ **kwargs: Additional arguments passed to BaseAgent+ """+ super().__init__(+ module_name="question",+ agent_name="relevance_analyzer",+ language=language,+ **kwargs,+ )++ async def process(+ self,+ question: dict[str, Any],+ knowledge_context: str,+ ) -> dict[str, Any]:+ """+ Main processing: analyze relevance between question and knowledge.++ Args:+ question: Generated question dict+ knowledge_context: Retrieved knowledge summary++ Returns:+ Dict with:+ - relevance: "high" or "partial"+ - kb_coverage: Description of KB content tested+ - extension_points: Description of extensions (only if partial)+ """+ self.logger.info("Starting relevance analysis")++ # Format question for analysis+ question_str = json.dumps(question, ensure_ascii=False, indent=2)++ # Truncate context if too long+ if len(knowledge_context) > 4000:+ knowledge_context = knowledge_context[:4000] + "...[truncated]"++ # Get prompts+ system_prompt = self.get_prompt("system", "")+ user_prompt_template = self.get_prompt("analyze_relevance", "")++ if not user_prompt_template:+ # Fallback prompt+ user_prompt_template = (+ "Analyze the relevance between this question and knowledge base:\n\n"+ "Question:\n{question}\n\n"+ "Knowledge Base:\n{knowledge}\n\n"+ "Return JSON with: relevance (high/partial), kb_coverage, extension_points"+ )++ user_prompt = user_prompt_template.format(+ question=question_str,+ knowledge=knowledge_context,+ )++ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ temperature=0.3, # Lower temperature for more consistent analysis+ stage="analyze_relevance",+ )++ result = self._parse_analysis_response(response)++ self.logger.info(f"Relevance analysis completed: {result['relevance']}")++ return result++ except Exception as e:+ self.logger.warning(f"Relevance analysis failed: {e}")+ # Return default "partial" on failure+ return {+ "relevance": "partial",+ "kb_coverage": "Unable to analyze knowledge base coverage",+ "extension_points": f"Analysis could not be completed: {e}",+ }++ def _parse_analysis_response(self, response: str) -> dict[str, Any]:+ """+ Parse LLM response into analysis result.++ Uses robust JSON extraction that handles control characters+ and common LLM output issues.++ Args:+ response: LLM response string++ Returns:+ Parsed analysis dict with normalized relevance value+ """+ if not response or not response.strip():+ raise ValueError("LLM returned empty response")++ # Try to extract JSON from markdown code blocks if present+ json_content = self._extract_json_from_markdown(response)++ # Clean control characters+ json_content = self._clean_json_string(json_content)++ # Try multiple parsing strategies+ result = None+ parse_error = None++ # Strategy 1: Direct parse+ try:+ result = json.loads(json_content)+ except json.JSONDecodeError as e:+ parse_error = e++ # Strategy 2: Extract JSON object pattern+ if result is None:+ json_obj_pattern = re.compile(r"\{[\s\S]*\}")+ match = json_obj_pattern.search(json_content)+ if match:+ try:+ result = json.loads(match.group(0))+ except json.JSONDecodeError:+ pass++ if result is None:+ raise ValueError(f"Failed to parse analysis JSON: {parse_error}") from parse_error++ # Normalize relevance value+ relevance = result.get("relevance", "partial")+ if relevance not in ["high", "partial"]:+ relevance = "partial"++ return {+ "relevance": relevance,+ "kb_coverage": result.get("kb_coverage", ""),+ "extension_points": result.get("extension_points", "") if relevance == "partial" else "",+ }++ def _clean_json_string(self, json_str: str) -> str:+ """+ Clean JSON string by removing problematic control characters.+ """+ if not json_str:+ return json_str+ # Remove control characters except tab, newline, carriage return+ return re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", json_str)++ def _extract_json_from_markdown(self, content: str) -> str:+ """+ Extract JSON from markdown code blocks.++ Args:+ content: Raw LLM response++ Returns:+ Extracted JSON string+ """+ if not content:+ return content++ # Try to find JSON code block+ json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"+ matches = re.findall(json_block_pattern, content, re.DOTALL)++ if matches:+ return matches[0].strip()++ return content.strip()+diff --git a/src/agents/question/agents/retrieve_agent.py b/src/agents/question/agents/retrieve_agent.pynew file mode 100644index 000000000..ee1f50191--- /dev/null+++ b/src/agents/question/agents/retrieve_agent.py@@ -0,0 +1,240 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""+RetrieveAgent - Responsible for generating RAG queries and retrieving knowledge.++Uses unified BaseAgent for LLM calls and configuration management.+"""++import asyncio+import json+from typing import Any++from src.agents.base_agent import BaseAgent+from src.tools.rag_tool import rag_search+++class RetrieveAgent(BaseAgent):+ """+ Agent responsible for knowledge retrieval from the knowledge base.++ Responsibilities:+ - Generate semantic search queries from requirements+ - Execute RAG searches in parallel+ - Merge and summarize retrieval results+ """++ def __init__(+ self,+ kb_name: str | None = None,+ rag_mode: str = "naive",+ language: str = "en",+ **kwargs,+ ):+ """+ Initialize RetrieveAgent.++ Args:+ kb_name: Knowledge base name to search+ rag_mode: RAG search mode ("naive" or "hybrid")+ language: Language for prompts ("en" or "zh")+ **kwargs: Additional arguments passed to BaseAgent+ """+ super().__init__(+ module_name="question",+ agent_name="retrieve_agent",+ language=language,+ **kwargs,+ )+ self.kb_name = kb_name+ self.rag_mode = rag_mode++ async def process(+ self,+ requirement: dict[str, Any] | str,+ num_queries: int = 3,+ ) -> dict[str, Any]:+ """+ Main processing: generate queries and retrieve knowledge.++ Args:+ requirement: Question requirement (dict or string)+ num_queries: Number of RAG queries to generate++ Returns:+ Dict with:+ - queries: List of generated queries+ - retrievals: List of retrieval results+ - summary: Merged knowledge summary+ """+ self.logger.info("Starting knowledge retrieval")++ # Convert requirement to text+ if isinstance(requirement, dict):+ requirement_text = json.dumps(requirement, ensure_ascii=False, indent=2)+ else:+ requirement_text = str(requirement)++ # Step 1: Generate search queries+ queries = await self._generate_queries(requirement_text, num_queries)+ self.logger.info(f"Generated {len(queries)} search queries")++ # Step 2: Execute RAG searches in parallel+ retrievals = await self._execute_searches(queries)+ self.logger.info(f"Retrieved {len(retrievals)} results")++ # Step 3: Summarize results+ summary = self._summarize_retrievals(retrievals)++ return {+ "queries": queries,+ "retrievals": retrievals,+ "summary": summary,+ "has_content": any(r.get("answer", "").strip() for r in retrievals),+ }++ async def _generate_queries(+ self,+ requirement_text: str,+ num_queries: int,+ ) -> list[str]:+ """+ Use LLM to generate semantic search queries from requirement text.++ Args:+ requirement_text: Natural language requirement+ num_queries: Number of queries to generate++ Returns:+ List of query strings+ """+ system_prompt = self.get_prompt("system", "")+ user_prompt_template = self.get_prompt("generate_queries", "")++ if not user_prompt_template:+ # Fallback prompt+ user_prompt_template = (+ f"Extract {num_queries} knowledge point names from this requirement for retrieval:\n"+ "{requirement_text}\n\n"+ "Return JSON: {{\"queries\": [\"point1\", \"point2\", ...]}}"+ )++ user_prompt = user_prompt_template.format(+ requirement_text=requirement_text,+ num_queries=num_queries,+ )++ try:+ response = await self.call_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="generate_queries",+ )++ data = json.loads(response)+ queries_raw = data.get("queries", [])++ # Ensure queries is a list+ if not isinstance(queries_raw, list):+ if isinstance(queries_raw, dict):+ queries_raw = list(queries_raw.values())+ elif isinstance(queries_raw, str):+ queries_raw = [queries_raw]+ else:+ queries_raw = []++ queries = [q.strip() for q in queries_raw if q and q.strip()]++ except Exception as e:+ self.logger.warning(f"Failed to generate queries: {e}")+ queries = []++ # Fallback: use requirement text as query+ if not queries:+ queries = [requirement_text[:100]]++ return queries[:num_queries]++ async def _single_rag_search(self, query: str) -> dict[str, Any]:+ """+ Execute a single RAG search.++ Args:+ query: Search query++ Returns:+ Dict with query and answer+ """+ try:+ result = await rag_search(+ query=query,+ kb_name=self.kb_name,+ mode=self.rag_mode,+ only_need_context=True,+ )+ return {+ "query": query,+ "answer": result.get("answer", ""),+ "mode": result.get("mode", self.rag_mode),+ }+ except Exception as e:+ self.logger.warning(f"RAG search failed for '{query}': {e}")+ return {+ "query": query,+ "answer": "",+ "error": str(e),+ }++ async def _execute_searches(self, queries: list[str]) -> list[dict[str, Any]]:+ """+ Execute RAG searches in parallel.++ Args:+ queries: List of search queries++ Returns:+ List of retrieval results+ """+ self.logger.debug(f"Executing {len(queries)} RAG searches in parallel")++ tasks = [self._single_rag_search(query) for query in queries]+ results = await asyncio.gather(*tasks, return_exceptions=True)++ retrievals = []+ for i, result in enumerate(results):+ if isinstance(result, Exception):+ self.logger.warning(f"Search failed for query '{queries[i]}': {result}")+ continue+ if result.get("answer"):+ retrievals.append(result)+ self.logger.debug(f" → Query: {queries[i][:50]}... (retrieved)")++ return retrievals++ def _summarize_retrievals(self, retrievals: list[dict[str, Any]]) -> str:+ """+ Merge retrieval results into a summary string.++ Args:+ retrievals: List of retrieval results++ Returns:+ Merged summary string+ """+ if not retrievals:+ return "No retrieval context available."++ lines = []+ for item in retrievals:+ lines.append(f"=== Query: {item['query']} ===")+ answer = item.get("answer", "")+ if answer:+ # Truncate very long answers+ if len(answer) > 2000:+ answer = answer[:2000] + "...[truncated]"+ lines.append(answer)+ lines.append("")++ return "\n".join(lines)+diff --git a/src/agents/question/agents/validation_agent.py b/src/agents/question/agents/validation_agent.pydeleted file mode 100644index 840433ff1..000000000--- a/src/agents/question/agents/validation_agent.py+++ /dev/null@@ -1,306 +0,0 @@-#!/usr/bin/env python-"""-Validation Agent - Responsible for validating question rigor and correctness.-Uses unified PromptManager for prompt loading.-"""--import json-from pathlib import Path-import sys-from typing import Any--project_root = Path(__file__).parent.parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.logging import get_logger-from src.services.config import load_config_with_main-from src.services.prompt import get_prompt_manager-from src.tools.rag_tool import rag_search--from .base_agent import Action, BaseAgent, Message, Observation--# Module logger-_logger = get_logger("QuestionValidationAgent")---class QuestionValidationAgent(BaseAgent):- """Validation Agent"""-- def __init__(self, language: str = "en", **kwargs):- super().__init__(agent_name="QuestionValidationAgent", language=language, **kwargs)-- # Load prompts using unified PromptManager- self._prompts = get_prompt_manager().load_prompts(- module_name="question",- agent_name="validation_agent",- language=language,- )-- # Load config for RAG settings- self._config = load_config_with_main("question_config.yaml", project_root)-- self.current_question = None- self.validation_result = None-- def get_system_prompt(self) -> str:- return self._prompts.get("system", "")-- def get_available_actions(self) -> list[dict[str, str]]:- return [- {- "name": "retrieve",- "description": "Retrieve knowledge from knowledge base for validation",- "parameters": "query (str): Retrieval query",- },- {- "name": "validate",- "description": "Validate question rigor and correctness",- "parameters": "None",- },- {- "name": "request_modification",- "description": "Request question generation agent to modify question",- "parameters": "None",- },- {- "name": "request_regeneration",- "description": "Request question generation agent to regenerate question",- "parameters": "None",- },- {- "name": "approve_question",- "description": "Validation passed, output final question",- "parameters": "None",- },- ]-- async def execute_action(self, action: Action) -> Observation:- """Execute specific action"""- try:- if action.name == "retrieve":- return await self._action_retrieve(action.params)-- if action.name == "validate":- return await self._action_validate()-- if action.name == "request_modification":- return await self._action_request_modification()-- if action.name == "request_regeneration":- return await self._action_request_regeneration()-- if action.name == "approve_question":- return await self._action_approve_question()-- return Observation(success=False, result=None, message=f"Unknown action: {action.name}")-- except Exception as e:- return Observation(- success=False, result=None, message=f"Action execution failed: {e!s}"- )-- async def _action_retrieve(self, params: dict[str, Any]) -> Observation:- """Retrieve validation knowledge"""- query = params.get("query", "")-- if not query:- return Observation(- success=False, result=None, message="Retrieval query cannot be empty"- )-- # Get RAG mode from config- question_cfg = self._config.get("question", {})- rag_mode = question_cfg.get("rag_mode", "hybrid")-- result = await rag_search(- query=query,- kb_name=self.kb_name,- mode=rag_mode,- only_need_context=True,- )-- answer = result.get("answer", "")-- self.retrieved_knowledge.append(- {- "query": query,- "answer": answer,- }- )-- answer_len = len(answer) if answer else 0- summary = f"Retrieved context with {answer_len} characters for query: {query[:50]}..."-- return Observation(success=True, result={"answer": answer}, message=summary)-- async def _action_validate(self) -> Observation:- """Validate question"""- if not self.current_question:- return Observation(success=False, result=None, message="No question to validate")-- knowledge_parts = []- for k in self.retrieved_knowledge:- knowledge_parts.append(f"=== Query: {k['query']} ===")- answer = k.get("answer", "")- if answer:- # Truncate very long contexts- if len(answer) > 3000:- answer = answer[:3000] + "...[truncated]"- knowledge_parts.append(answer)- knowledge_parts.append("")-- validation_knowledge_str = (- "\n".join(knowledge_parts) if knowledge_parts else "No validation knowledge retrieved"- )-- prompt_template = self._prompts.get("validate", "")- prompt = prompt_template.format(- question=json.dumps(self.current_question, ensure_ascii=False, indent=2),- validation_knowledge=validation_knowledge_str,- )-- response = await self.client.chat.completions.create(- model=self.model,- messages=[- {"role": "system", "content": "You are a strict question validation expert"},- {"role": "user", "content": prompt},- ],- temperature=self._agent_params["temperature"],- max_tokens=self._agent_params["max_tokens"],- response_format={"type": "json_object"},- )-- result = json.loads(response.choices[0].message.content)- self.validation_result = result-- # Ensure issues and suggestions are lists- issues = result.get("issues", [])- if not isinstance(issues, list):- _logger.warning(f"Issues is not a list (type: {type(issues)}), converting...")- if isinstance(issues, dict):- issues = [issues]- else:- issues = []- result["issues"] = issues-- suggestions = result.get("suggestions", [])- if not isinstance(suggestions, list):- _logger.warning(f"Suggestions is not a list (type: {type(suggestions)}), converting...")- if isinstance(suggestions, dict):- suggestions = [suggestions]- else:- suggestions = []- result["suggestions"] = suggestions-- decision = result.get("decision")- issues_count = len(issues)-- return Observation(- success=True,- result=result,- message=f"Validation decision: {decision}, found {issues_count} issues",- )-- async def _action_request_modification(self) -> Observation:- """Request question modification"""- if not self.validation_result:- return Observation(- success=False,- result=None,- message="Error: Must execute validate action first to get validation result. Please execute validate to validate the question!",- )-- decision = self.validation_result.get("decision")- if decision != "request_modification":- return Observation(- success=False,- result=None,- message=f"Error: validate decision is '{decision}', should not execute request_modification. Please execute corresponding action based on validation decision!",- )-- if hasattr(self, "send_message") and self.send_message:- message = Message(- from_agent=self.agent_name,- to_agent="QuestionGenerationAgent",- message_type="request_modification",- content={- "issues": self.validation_result.get("issues", []),- "suggestions": self.validation_result.get("suggestions", []),- "reasoning": self.validation_result.get("reasoning", ""),- },- )- await self.send_message(message)-- return Observation(- success=True,- result=self.validation_result,- message="Modification request sent to question generation agent",- )-- async def _action_request_regeneration(self) -> Observation:- """Request question regeneration"""- if not self.validation_result:- return Observation(- success=False,- result=None,- message="Error: Must execute validate action first to get validation result. Please execute validate to validate the question!",- )-- decision = self.validation_result.get("decision")- if decision != "request_regeneration":- return Observation(- success=False,- result=None,- message=f"Error: validate decision is '{decision}', should not execute request_regeneration.",- )-- if hasattr(self, "send_message") and self.send_message:- message = Message(- from_agent=self.agent_name,- to_agent="QuestionGenerationAgent",- message_type="request_regeneration",- content={- "issues": self.validation_result.get("issues", []),- "suggestions": self.validation_result.get("suggestions", []),- "reasoning": self.validation_result.get("reasoning", ""),- },- )- await self.send_message(message)-- return Observation(- success=True,- result=self.validation_result,- message="Regeneration request sent to question generation agent",- )-- async def _action_approve_question(self) -> Observation:- """Validation passed, output final question"""- if not self.current_question:- return Observation(- success=False,- result=None,- message="Error: No question to approve. Please get question from inbox first.",- )-- if not self.validation_result:- return Observation(- success=False,- result=None,- message="Error: Must execute validate action first to get validation result, then can approve. Please execute validate action to validate the question!",- )-- decision = self.validation_result.get("decision")- if decision != "approve":- return Observation(- success=False,- result=None,- message=f"Error: validate decision is '{decision}', cannot execute approve_question. Should execute corresponding action.",- )-- final_result = {- "question": self.current_question,- "validation": self.validation_result,- "status": "approved",- }-- return Observation(success=True, result=final_result, message="Question validation passed!")diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.pyindex 5460a3efe..12c5f463b 100644--- a/src/agents/question/coordinator.py+++ b/src/agents/question/coordinator.py@@ -1,88 +1,42 @@#!/usr/bin/env python# -*- coding: utf-8 -*-"""-Agent coordinator responsible for managing collaboration between the question-generation agent-and the validation workflow.+AgentCoordinator - Orchestrates question generation workflow.++Refactored version:+- Uses specialized agents: RetrieveAgent, GenerateAgent, RelevanceAnalyzer+- No iterative validation loops - single-pass generation + relevance analysis+- All questions are accepted, classified as "high" or "partial" relevance"""-import asynciofrom collections.abc import Callable-import copyfrom datetime import datetimeimport json-import loggingfrom pathlib import Pathimport sysfrom typing import Any-from .agents import Message, QuestionGenerationAgent-from .validation_workflow import QuestionValidationWorkflow-# Add project root for importsproject_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))from src.logging import Logger, get_loggerfrom src.services.config import load_config_with_main-from src.tools.rag_tool import rag_search---def ensure_list(value: Any, default: list | None = None) -> list:- """- Ensure a value is a list, converting if necessary.-- Args:- value: Value to check/convert- default: Default value to return if conversion fails (default: [])-- Returns:- List: A list representation of the value- """- if default is None:- default = []-- if isinstance(value, list):- return value- if isinstance(value, dict):- # If it's a dict, try to extract values- return list(value.values()) if value else default- if isinstance(value, (str, int, float)):- # If it's a single value, wrap in list- return [value]- if value is None:- return default- # Try to convert to list- try:- return list(value)- except (TypeError, ValueError):- return default---def ensure_dict(value: Any, default: dict | None = None) -> dict:- """- Ensure a value is a dict, converting if necessary.-- Args:- value: Value to check/convert- default: Default value to return if conversion fails (default: {})-- Returns:- Dict: A dict representation of the value- """- if default is None:- default = {}- if isinstance(value, dict):- return value- if value is None:- return default- # Cannot safely convert non-dict to dict- return default+from .agents.generate_agent import GenerateAgent+from .agents.relevance_analyzer import RelevanceAnalyzer+from .agents.retrieve_agent import RetrieveAgentclass AgentCoordinator:"""- Coordinate interactions between QuestionGenerationAgent and QuestionValidationWorkflow.+ Coordinate question generation workflow using specialized agents.++ Workflow:+ 1. RetrieveAgent: Generate queries and retrieve knowledge+ 2. Plan: Generate question plan with focuses+ 3. GenerateAgent: Generate questions+ 4. RelevanceAnalyzer: Analyze relevance (no rejection, just classification)"""def __init__(@@ -90,69 +44,48 @@ class AgentCoordinator:api_key: str | None = None,base_url: str | None = None,api_version: str | None = None,- max_rounds: int = 10,+ max_rounds: int = 10, # Kept for backward compatibility, but not used for iterationkb_name: str | None = None,output_dir: str | None = None,+ language: str = "en",):"""Initialize the coordinator.++ Args:+ api_key: API key (optional, loaded from config if not provided)+ base_url: API endpoint (optional)+ api_version: API version for Azure (optional)+ max_rounds: Deprecated, kept for backward compatibility+ kb_name: Knowledge base name+ output_dir: Output directory for results+ language: Language for prompts ("en" or "zh")"""- self.max_rounds = max_roundsself.kb_name = kb_nameself.output_dir = output_dir+ self.language = language++ # Store API credentials for creating agents+ self._api_key = api_key+ self._base_url = base_url+ self._api_version = api_version- # Load configuration (with main.yaml merge) first- project_root = Path(__file__).parent.parent.parent.parent+ # Load configurationself.config = load_config_with_main("question_config.yaml", project_root)- # Initialize logger (from config)+ # Initialize loggerlog_dir = self.config.get("paths", {}).get("user_log_dir") or self.config.get("logging", {}).get("log_dir")- self.logger: Logger = get_logger("QuestionGen", log_dir=log_dir)+ self.logger: Logger = get_logger("QuestionCoordinator", log_dir=log_dir)- # Override max_rounds from config if available+ # Get config valuesquestion_cfg = self.config.get("question", {})- if isinstance(question_cfg, dict) and "max_rounds" in question_cfg:- self.max_rounds = question_cfg["max_rounds"]-- # Get parallel generation config from question sectionself.rag_query_count = question_cfg.get("rag_query_count", 3)- self.max_parallel_questions = question_cfg.get("max_parallel_questions", 3)-- # Store API credentials for creating multiple agents- self._api_key = api_key- self._base_url = base_url- self._api_version = api_version+ self.max_parallel_questions = question_cfg.get("max_parallel_questions", 1)+ self.rag_mode = question_cfg.get("rag_mode", "naive")- # Get config for generation agent- gen_agent_config = self.config.get("agents", {}).get("question_generation", {})- max_gen_iterations = gen_agent_config.get("max_iterations", 5)-- # Instantiate question-generation agent- self.question_agent = QuestionGenerationAgent(- api_key=api_key,- base_url=base_url,- api_version=api_version,- max_iterations=max_gen_iterations,- kb_name=kb_name,- token_stats_callback=self.update_token_stats,- )-- # Instantiate validation workflow (fixed pipeline)- self.validation_workflow = QuestionValidationWorkflow(- api_key=api_key,- base_url=base_url,- api_version=api_version,- kb_name=kb_name,- token_stats_callback=self.update_token_stats,- )-- # Message queue- self.message_queue = asyncio.Queue()- self._logging_suppressed = False-- # Token tracking+ # Token tracking - will be updated from BaseAgent shared statsself.token_stats = {"model": "gpt-4o-mini","calls": 0,@@ -162,1847 +95,183 @@ class AgentCoordinator:"cost": 0.0,}- # Agent status tracking- self.agent_status = {- "QuestionGenerationAgent": "pending",- "ValidationWorkflow": "pending",- "RetrievalTool": "pending",- }-# WebSocket callback for streaming updatesself._ws_callback: Callable | None = None- def set_ws_callback(self, callback: Callable):- """Set WebSocket callback for streaming updates to frontend."""- self._ws_callback = callback-- async def _send_ws_update(self, update_type: str, data: dict[str, Any]):- """Send update via WebSocket callback if available."""- if self._ws_callback:- try:- await self._ws_callback({"type": update_type, **data})- except Exception as e:- self.logger.debug(f"Failed to send WS update: {e}")-- def _update_agent_status(self, agent: str, status: str):- """Update agent status and notify frontend."""- self.agent_status[agent] = status- asyncio.create_task(- self._send_ws_update(- "agent_status", {"agent": agent, "status": status, "all_agents": self.agent_status}- )- )-- def update_token_stats(self, input_tokens: int = 0, output_tokens: int = 0, model: str = None):- """- Update token statistics. Can be called by external components.-- Args:- input_tokens: Number of input tokens- output_tokens: Number of output tokens- model: Model name (optional, will update if provided)- """- self.token_stats["calls"] += 1- self.token_stats["input_tokens"] += input_tokens- self.token_stats["output_tokens"] += output_tokens- self.token_stats["tokens"] = (- self.token_stats["input_tokens"] + self.token_stats["output_tokens"]- )- if model:- self.token_stats["model"] = model-- # Estimate cost (simplified pricing)- # gpt-4o-mini: $0.15/1M input, $0.60/1M output- self.token_stats["cost"] = (- self.token_stats["input_tokens"] * 0.00000015- + self.token_stats["output_tokens"] * 0.0000006- )-- asyncio.create_task(self._send_ws_update("token_stats", {"stats": self.token_stats}))-- def _update_token_stats(self, input_tokens: int = 0, output_tokens: int = 0, model: str = None):- """Internal alias for backwards compatibility."""- self.update_token_stats(input_tokens, output_tokens, model)-- async def send_message(self, message: Message):- """Send a message to the destination agent."""- await self.message_queue.put(message)-- async def deliver_messages(self):- """Deliver queued messages."""- while not self.message_queue.empty():- message = await self.message_queue.get()-- if message.to_agent == "QuestionGenerationAgent":- self.question_agent.receive_message(message)-- def _suppress_logging(self):- if self._logging_suppressed:- return- logging.basicConfig(level=logging.ERROR, force=True)- for logger_name in [- "lightrag",- "raganything",- "nano-vectordb",- "openai",- "httpx",- "httpcore",- ]:- logging.getLogger(logger_name).setLevel(logging.ERROR)- logging.getLogger(logger_name).propagate = False- self._logging_suppressed = True-- def _extract_json_from_markdown(self, content: str) -> str:- """Extract JSON from markdown code blocks.-- LLMs often wrap JSON in ```json ... ``` blocks. This method strips- the markdown formatting and any surrounding text.- """- if not content:- return content-- # Remove leading explanatory text (look for the first ```json or ```)- import re-- # Try to find JSON code block- json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"- matches = re.findall(json_block_pattern, content, re.DOTALL)-- if matches:- # Return the content inside the first code block- return matches[0].strip()-- # If no code blocks found, return as-is (might already be valid JSON)- return content.strip()-- async def _call_llm(- self,- system_prompt: str,- user_prompt: str,- response_format: dict[str, Any] | None = None,- stage: str = "",- ):- """Utility wrapper around the generation agent's LLM client."""- client = self.question_agent.client- model = self.question_agent.model-- kwargs = {- "model": model,- "messages": [- {"role": "system", "content": system_prompt},- {"role": "user", "content": user_prompt},- ],- "temperature": 0.2,- "timeout": 180.0, # Add timeout to prevent hanging- }- if response_format:- kwargs["response_format"] = response_format-- # Log the request details for debugging- self.logger.debug(- f"[{stage or 'coordinator'}] Calling LLM: model={model}, "- f"system_prompt_len={len(system_prompt)}, user_prompt_len={len(user_prompt)}, "- f"response_format={response_format}"- )-- try:- response = await client.chat.completions.create(**kwargs)- except Exception as e:- self.logger.error(- f"[{stage or 'coordinator'}] LLM API call failed: {type(e).__name__}: {e}"- )- self.logger.error(f"Request kwargs: {kwargs}")- raise RuntimeError(f"LLM call failed in stage '{stage}': {e}") from e-- # Extract response content with validation- if not response or not response.choices:- error_msg = f"[{stage or 'coordinator'}] LLM returned empty response or no choices"- self.logger.error(error_msg)- raise ValueError(error_msg)-- response_content = response.choices[0].message.content-- # Validate content is not None or empty- if response_content is None:- error_msg = (- f"[{stage or 'coordinator'}] LLM returned None content. Response: {response}"- )- self.logger.error(error_msg)- raise ValueError(error_msg)-- if not response_content.strip():- error_msg = (- f"[{stage or 'coordinator'}] LLM returned empty string. Response object: {response}"- )- self.logger.error(error_msg)- raise ValueError(error_msg)-- # Log successful response- self.logger.debug(- f"[{stage or 'coordinator'}] LLM response received: "- f"length={len(response_content)}, preview={response_content[:200]}..."- )-- # Track token usage- input_tokens = 0- output_tokens = 0- cost = 0.0- if hasattr(response, "usage") and response.usage:- input_tokens = response.usage.prompt_tokens- output_tokens = response.usage.completion_tokens- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006- self._update_token_stats(- input_tokens=input_tokens, output_tokens=output_tokens, model=model- )-- # Log LLM call with detailed information- self.logger.log_llm_call(- model=model,- stage=stage or "coordinator_call",- system_prompt=system_prompt,- user_prompt=user_prompt,- response=response_content,- agent_name="Coordinator",- input_tokens=input_tokens,- output_tokens=output_tokens,- cost=cost,- level="DEBUG",- )-- return response_content-- async def _generate_search_queries(- self, base_requirement: dict[str, Any], num_queries: int- ) -> list[str]:- """Backwards compatibility helper when a structured requirement already exists."""- text = json.dumps(base_requirement, ensure_ascii=False, indent=2)- return await self._generate_search_queries_from_text(text, num_queries)-- async def _generate_search_queries_from_text(- self, requirement_text: str, num_queries: int- ) -> list[str]:- """Use LLM to produce semantic search queries directly from natural-language text."""- system_prompt = (- "【Role】You are a knowledge base retrieval assistant, preparing for question generation.\n"- "\n"- "【Current Task】Generate knowledge point retrieval queries to find theoretical explanations, definitions, and theorems in the knowledge base.\n"- "⚠️ Key: You are not generating questions now! You are looking for theoretical knowledge needed for question generation!\n"- "\n"- "【Output Rules】\n"- "1. Only output pure knowledge point names (theorem names, concept names, method names)\n"- "2. Each query should be 2-5 words\n"- "3. Do not include functions, numerical values, or calculation tasks\n"- "4. Do not use questions or task descriptions\n"- )-- user_prompt = (- f"The user's question generation requirement is:\n{requirement_text}\n\n"- f"Please extract {num_queries} pure knowledge point names from it for knowledge base retrieval.\n\n"- "Correct examples:\n"- "✓ Taylor theorem\n"- "✓ Lagrange multipliers \n"- "✓ critical points\n\n"- "Incorrect examples (do not generate):\n"- "✗ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)\n"- "✗ Find and classify critical points (This is a task)\n"- "✗ Use Lagrange multipliers to find maximum (This is an instruction)\n\n"- f'Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.'- )-- try:- content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)- data = json.loads(content)-- # Ensure queries is a list- queries_raw = data.get("queries", [])- if not isinstance(queries_raw, list):- self.logger.warning(- f"Queries is not a list (type: {type(queries_raw)}), converting..."- )- if isinstance(queries_raw, dict):- # If it's a dict, try to extract values or convert to list- queries_raw = list(queries_raw.values()) if queries_raw else []- elif isinstance(queries_raw, str):- queries_raw = [queries_raw]- else:- queries_raw = []-- queries = [q.strip() for q in queries_raw if q and q.strip()]- except Exception as e:- self.logger.warning(f"Failed to generate search queries: {e}")- queries = []- if not queries:- queries = [requirement_text[:50]]- return queries[:num_queries]-- async def _single_rag_search(self, query: str) -> dict[str, Any]:- """Execute a single RAG search and return the raw answer."""- question_cfg = self.config.get("question", {})- rag_mode = question_cfg.get("rag_mode", "hybrid")-- result = await rag_search(- query=query,- kb_name=self.kb_name,- mode=rag_mode,- only_need_context=True,- )- return {- "query": query,- "answer": result.get("answer", ""),- "mode": result.get("mode", rag_mode),- }-- async def _gather_retrieval_context(self, queries: list[str]) -> list[dict[str, Any]]:- """Run retrieval for each query in parallel and collect the raw contexts."""- self._update_agent_status("RetrievalTool", "running")- self.logger.info(f"Retrieving knowledge for {len(queries)} queries...")-- # Execute all queries in parallel- tasks = [self._single_rag_search(query) for query in queries]- results = await asyncio.gather(*tasks, return_exceptions=True)-- retrievals = []- for i, result in enumerate(results):- query = queries[i]- if isinstance(result, Exception):- self.logger.warning(f"Retrieval failed for query '{query}': {result}")- continue-- self.logger.debug(f" → Query: {query[:50]}... (retrieved)")- retrievals.append(- {- "query": query,- "answer": result.get("answer", ""),- }- )-- self._update_agent_status("RetrievalTool", "done")- return retrievals-- def _summarize_retrievals(self, retrievals: list[dict[str, Any]]) -> str:- """Turn retrieval objects into a digest for the LLM."""- lines = []- for item in retrievals:- lines.append(f"=== Query: {item['query']} ===")- answer = item.get("answer", "")- if answer:- # Truncate very long answers- if len(answer) > 2000:- answer = answer[:2000] + "...[truncated]"- lines.append(answer)- lines.append("")- return "\n".join(lines) if lines else "No retrieval context available."-- def _save_question_result(- self,- question: dict[str, Any],- requirement: dict[str, Any],- validation: dict[str, Any],- round_num: int,- extended: bool = False,- ) -> str | None:- """- Save a single question result to disk.-- Args:- question: The generated question dict- requirement: The requirement dict (contains knowledge_point, difficulty, etc.)- validation: The validation result dict- round_num: Number of rounds taken- extended: Whether this is an extended question-- Returns:- The output directory path if saved successfully, None otherwise- """- if not self.output_dir:- return None-- try:- # Create timestamped subdirectory- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_path = Path(self.output_dir) / f"question_{timestamp}"- output_path.mkdir(parents=True, exist_ok=True)-- # Build result structure- result = {- "success": True,- "question": question,- "validation": validation,- "rounds": round_num,- }- if extended:- result["extended"] = True-- # Save result.json- with open(output_path / "result.json", "w", encoding="utf-8") as f:- json.dump(result, f, indent=2, ensure_ascii=False)-- # Build question.md- validation_status = "Extended" if extended else "Approved"- md_content = f"""# Generated Question--**Knowledge point**: {requirement.get("knowledge_point", question.get("knowledge_point", "N/A"))}-**Difficulty**: {requirement.get("difficulty", "N/A")}-**Type**: {requirement.get("question_type", question.get("question_type", "N/A"))}-------## Question-{question.get("question", "")}--"""- if question.get("options"):- md_content += "## Options\n"- for key, value in question.get("options", {}).items():- md_content += f"- **{key}**: {value}\n"- md_content += "\n"-- md_content += f"""-## Answer-{question.get("correct_answer", "")}--## Explanation-{question.get("explanation", "")}------**Validation**: {validation_status} after {round_num} round(s)-"""- with open(output_path / "question.md", "w", encoding="utf-8") as f:- f.write(md_content)-- self.logger.info(f"Question saved to: {output_path}")- return str(output_path)-- except Exception as e:- self.logger.warning(f"Failed to save question artifacts: {e}")- return None-- async def _check_retrieval_relevance(- self, requirement_text: str, knowledge_summary: str- ) -> bool:- """Use LLM to determine whether retrieval results match the user's request."""- system_prompt = (- "You evaluate whether retrieved knowledge is relevant to a user's request. "- 'Respond in JSON with key "relevant" (true/false) and optional "reason".'- )- user_prompt = (- f"User request:\n{requirement_text}\n\n"- f"Retrieved knowledge summary:\n{knowledge_summary}\n\n"- "Is the retrieved knowledge substantively relevant to the request?"- )- try:- content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)- parsed = json.loads(content)- return bool(parsed.get("relevant"))- except Exception as e:- self.logger.warning(f"Failed to check retrieval relevance: {e}")- return False-- async def _generate_child_requirements(- self, base_requirement: dict[str, Any], knowledge_summary: str, num_questions: int- ) -> list[dict[str, Any]]:- """Ask LLM to break the base requirement into multiple sub-requirements."""- system_prompt = (- "You are a curriculum designer. Given a base requirement and knowledge summary, "- "create distinct sub-requirements that all test the SAME knowledge point. "- "Each sub-requirement must describe a unique scenario and reasoning flow. "- 'Output JSON with key "requirements" (array of length requested) where each item has: '- '"title", "question_type", "difficulty", "additional_requirements".'- )- user_prompt = (- f"Base requirement:\n{json.dumps(base_requirement, ensure_ascii=False, indent=2)}\n\n"- f"Knowledge summary:\n{knowledge_summary}\n\n"- f"Generate exactly {num_questions} sub-requirements in JSON."- )- try:- content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)- parsed = json.loads(content)-- # Ensure requirements is a list- requirements_raw = parsed.get("requirements", [])- if not isinstance(requirements_raw, list):- self.logger.warning(- f"Requirements is not a list (type: {type(requirements_raw)}), converting..."- )- if isinstance(requirements_raw, dict):- # If it's a dict, try to extract values or convert to list- requirements_raw = list(requirements_raw.values()) if requirements_raw else []- else:- requirements_raw = []-- requirements = requirements_raw- except Exception as e:- self.logger.warning(f"Failed to generate sub-requirements: {e}")- requirements = []- return requirements[:num_questions]-- async def _interpret_requirement_text(self, requirement_text: str) -> dict[str, Any]:- """Convert a natural-language request into structured requirement fields."""- system_prompt = (- "You are an instruction parser for an exam-question generator. "- "Given a natural-language request, extract the core knowledge point, "- "difficulty (easy/medium/hard), preferred question type (choice/written), "- "and additional requirements. Return JSON with keys: "- '"knowledge_point", "difficulty", "question_type", "additional_requirements".'- )- user_prompt = f"Requirement:\n{requirement_text}\n\nReturn JSON only."- try:- content = await self._call_llm(system_prompt=system_prompt, user_prompt=user_prompt)- parsed = json.loads(content)- except Exception as e:- self.logger.warning(f"Failed to interpret requirement text: {e}")- parsed = {}-- knowledge_point = parsed.get("knowledge_point") or requirement_text[:60]- difficulty = (parsed.get("difficulty") or "medium").lower()- if difficulty not in {"easy", "medium", "hard"}:- difficulty = "medium"- question_type = (parsed.get("question_type") or "written").lower()- if question_type not in {"choice", "written"}:- question_type = "written"-- additional_requirements = parsed.get("additional_requirements") or requirement_text-- return {- "knowledge_point": knowledge_point,- "difficulty": difficulty,- "question_type": question_type,- "additional_requirements": additional_requirements,- }-- async def generate_question(self, requirement: dict[str, Any]) -> dict[str, Any]:- """- Full workflow for generating and validating a question.- """- # Reset agent status for this question- self.agent_status = {- "QuestionGenerationAgent": "pending",- "ValidationWorkflow": "pending",- "RetrievalTool": "pending",- }-- self.logger.section("Question Generation Workflow")- self.logger.info("Workflow started")- self.logger.info(f"Knowledge point: {requirement.get('knowledge_point')}")- self.logger.info(f"Difficulty: {requirement.get('difficulty')}")- self.logger.info(f"Question type: {requirement.get('question_type')}")-- # Send progress update- await self._send_ws_update(- "progress", {"stage": "generating", "progress": {"status": "initializing"}}- )-- # If this is a batch sub-requirement, show specific info- batch_index = requirement.get("batch_index")- additional_req = requirement.get("additional_requirements", "")- if batch_index and additional_req:- lines = additional_req.split("\n")- for line in lines:- if line.startswith("[Auto-derived sub requirement"):- title_part = line.split(":", 1)[1].strip().rstrip("]") if ":" in line else ""- self.logger.info(f"Sub-requirement: {title_part}")- break-- # Ensure noisy loggers are silenced- self._suppress_logging()-- # Provide requirement to the generation agent- self.question_agent.set_requirement(requirement)-- for round_num in range(1, self.max_rounds + 1):- self.logger.separator()- self.logger.stage(f"Round {round_num}/{self.max_rounds}")-- # Send progress update- await self._send_ws_update(- "progress",- {- "stage": "generating",- "progress": {"round": round_num, "max_rounds": self.max_rounds},- },- )-- self.logger.info("Stage 1: QuestionGenerationAgent starting...")- self.logger.debug(f" Knowledge point: {requirement.get('knowledge_point', 'N/A')}")- self.logger.debug(f" Difficulty: {requirement.get('difficulty', 'N/A')}")- self._update_agent_status("QuestionGenerationAgent", "running")-- # Register message callback- self.question_agent.send_message = self.send_message-- # Reset submission flag for the new round- self.question_agent.submitted = False-- # Build task description and context- if round_num == 1:- task = f"Generate a question that satisfies the requirement: {requirement.get('knowledge_point')}"- agent_context = {- "requirement": requirement,- "round_num": round_num,- "is_new_round": False,- }- else:- task = "Revise the question based on validation feedback"- agent_context = {- "requirement": requirement,- "round_num": round_num,- "is_new_round": True, # Notify the agent that a fresh round is starting- }-- # Execute the question-generation agent- question_result = await self.question_agent.run(- task=task, context=agent_context, send_message_callback=self.send_message- )-- if not question_result.get("success"):- self._update_agent_status("QuestionGenerationAgent", "error")- return {- "success": False,- "error": "question_agent_execution_failed",- "details": question_result,- }-- # Check for rejections FIRST (before checking if submitted)- result_data = question_result.get("result")- if isinstance(result_data, dict) and result_data.get("task_rejected"):- self.logger.separator()- self.logger.warning("Question generation rejected")- self._update_agent_status("QuestionGenerationAgent", "error")- return {- "success": False,- "error": "task_rejected",- "reason": result_data.get(- "reason", "Required knowledge is missing from the knowledge base."- ),- "message": "QuestionGenerationAgent rejected this task because the knowledge base lacks the required content.",- }-- # Ensure the agent submitted a question- if self.question_agent.submitted:- self.logger.success("QuestionGenerationAgent submitted a question")- self._update_agent_status("QuestionGenerationAgent", "done")- else:- self.logger.warning(- "QuestionGenerationAgent did not submit a question; moving to next round"- )- continue-- # Retrieve the submitted question from the queue (before delivering messages)- question = None- messages_to_deliver = []- while not self.message_queue.empty():- msg = await self.message_queue.get()- if msg.message_type == "validate_request":- question = msg.content.get("question")- else:- messages_to_deliver.append(msg)-- # Return non-question messages to the queue- for msg in messages_to_deliver:- await self.message_queue.put(msg)-- # Deliver other pending messages- await self.deliver_messages()-- if not question:- self.logger.warning("QuestionGenerationAgent did not submit a question")- continue-- self.logger.success("Question submitted for validation")-- self.logger.info("Stage 2: Validation workflow starting...")- self.logger.debug(f" Validating question: {question.get('question', '')[:60]}...")- self._update_agent_status("ValidationWorkflow", "running")-- # Send progress update- await self._send_ws_update(- "progress", {"stage": "validating", "progress": {"round": round_num}}- )-- # Attach knowledge point for validation retrieval- question["knowledge_point"] = requirement.get("knowledge_point", "")-- # Execute validation workflow (retrieve → validate → return)- # Pass reference question for innovation check- reference_question = requirement.get("reference_question")- validation_result = await self.validation_workflow.validate(- question, reference_question- )-- # Evaluate validation decision- decision = validation_result.get("decision")-- if decision == "approve":- self.logger.separator()- self.logger.success("Question approved by validation")- self._update_agent_status("ValidationWorkflow", "done")-- # Validate validation_result structure before building result- issues = validation_result.get("issues", [])- suggestions = validation_result.get("suggestions", [])-- # Log types for debugging- self.logger.debug(- f"Validation result - issues type: {type(issues)}, suggestions type: {type(suggestions)}"- )-- # Ensure issues and suggestions are lists- if not isinstance(issues, list):- self.logger.warning(- f"Issues is not a list (type: {type(issues)}), converting..."- )- if isinstance(issues, dict):- issues = [issues]- else:- issues = []-- if not isinstance(suggestions, list):- self.logger.warning(- f"Suggestions is not a list (type: {type(suggestions)}), converting..."- )- if isinstance(suggestions, dict):- suggestions = [suggestions]- else:- suggestions = []-- result = {- "success": True,- "question": question,- "validation": {- "decision": decision,- "issues": issues,- "suggestions": suggestions,- "reasoning": validation_result.get("reasoning", ""),- },- "rounds": round_num,- }-- # Log final result structure- self.logger.debug(- f"Result structure - validation.issues type: {type(result['validation']['issues'])}, validation.suggestions type: {type(result['validation']['suggestions'])}"- )-- # Persist results if output_dir is provided- if self.output_dir:- try:- # timestamped subdirectory- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_path = Path(self.output_dir) / f"question_{timestamp}"- output_path.mkdir(parents=True, exist_ok=True)-- # result JSON- with open(output_path / "result.json", "w", encoding="utf-8") as f:- json.dump(result, f, indent=2, ensure_ascii=False)-- # question markdown- md_content = f"""# Generated Question--**Knowledge point**: {requirement.get("knowledge_point")}-**Difficulty**: {requirement.get("difficulty")}-**Type**: {requirement.get("question_type")}-------## Question-{question.get("question")}--"""- if question.get("options"):- md_content += "## Options\n"- for key, value in question.get("options", {}).items():- md_content += f"- **{key}**: {value}\n"- md_content += "\n"-- md_content += f"""-## Answer-{question.get("correct_answer")}--## Explanation-{question.get("explanation")}------**Validation**: Approved after {round_num} round(s)-"""- with open(output_path / "question.md", "w", encoding="utf-8") as f:- f.write(md_content)-- self.logger.info(f"Results saved to: {output_path}")- result["output_dir"] = str(output_path)-- except Exception as e:- self.logger.warning(f"Failed to save artifacts: {e}")-- return result-- # Handle modification/regeneration decisions- if decision in ["request_modification", "request_regeneration"]:- self.logger.info(f"Validation decision: {decision}")- self.logger.debug(f"Issues: {validation_result.get('issues')}")- self.logger.debug(f"Suggestions: {validation_result.get('suggestions')}")- self._update_agent_status("ValidationWorkflow", "pending")-- # Send feedback back to the question agent- message = Message(- from_agent="QuestionValidationWorkflow",- to_agent="QuestionGenerationAgent",- message_type=decision,- content={- "issues": validation_result.get("issues", []),- "suggestions": validation_result.get("suggestions", []),- "reasoning": validation_result.get("reasoning", ""),- },- )- self.question_agent.receive_message(message)-- # Continue to next round- continue-- self.logger.warning(f"Unknown validation decision: {decision}")- continue-- self.logger.separator()- self.logger.warning(f"Maximum rounds reached ({self.max_rounds})")-- # Return as extended question instead of failure- last_question = self.question_agent.current_question- if last_question:- # Get extension analysis from validation workflow- # Build shared context from retrieved knowledge- shared_context = ""- if hasattr(self.question_agent, "retrieved_knowledge"):- for k in self.question_agent.retrieved_knowledge:- shared_context += f"{k.get('answer', '')}\n\n"-- extension_analysis = await self.validation_workflow.analyze_extension(- last_question, shared_context- )-- self.logger.info("Question marked as extended (beyond KB scope)")- return {- "success": True,- "question": last_question,- "validation": {- "decision": "extended",- "reasoning": extension_analysis.get("reasoning", ""),- "kb_connection": extension_analysis.get("kb_connection", ""),- "extended_aspect": extension_analysis.get("extended_aspect", ""),- },- "rounds": self.max_rounds,- "extended": True,- }- else:- return {- "success": False,- "error": f"Maximum rounds reached ({self.max_rounds}) without generating a question",- "last_question": None,- }-- async def generate_multiple_questions(- self,- base_requirement: dict[str, Any],- num_questions: int,- precomputed_queries: list[str] | None = None,- precomputed_retrievals: list[dict[str, Any]] | None = None,- precomputed_summary: str | None = None,- ) -> dict[str, Any]:- """- Generate multiple questions based on a single high-level requirement.- """- if num_questions <= 0:- raise ValueError("num_questions must be greater than zero")-- self._suppress_logging()-- # Step 1: plan retrieval queries and gather context- queries = precomputed_queries or await self._generate_search_queries(- base_requirement, max(3, num_questions)- )- retrievals = precomputed_retrievals or await self._gather_retrieval_context(queries)- knowledge_summary = precomputed_summary or self._summarize_retrievals(retrievals)-- if (- not retrievals- or not knowledge_summary- or knowledge_summary.strip() == "No retrieval context available."- ):- return {- "success": False,- "error": "knowledge_not_found",- "message": "Knowledge base does not contain relevant information for the request.",- }-- # Step 2: ask LLM to produce sub-requirements- child_requirements = await self._generate_child_requirements(- base_requirement, knowledge_summary, num_questions- )-- if not child_requirements:- # Fallback: simple numbered variants- child_requirements = [- {- "title": f"Variant #{idx}",- "question_type": base_requirement.get("question_type"),- "difficulty": base_requirement.get("difficulty"),- "additional_requirements": f"Create a distinct scenario #{idx} using the same knowledge point.",- }- for idx in range(1, num_questions + 1)- ]-- results: list[dict[str, Any]] = []- failures: list[dict[str, Any]] = []-- self.logger.section(f"Batch Generation: {num_questions} question(s)")-- for idx in range(1, num_questions + 1):- self.logger.separator("-")- self.logger.stage(f"Generating variant #{idx}/{num_questions}")-- # Send progress update- await self._send_ws_update(- "progress",- {"stage": "generating", "progress": {"current": idx, "total": num_questions}},- )-- # Clear Agent history, ensure each question is independent- self.question_agent.reset()-- requirement_variant = copy.deepcopy(base_requirement)- child_req = child_requirements[idx - 1] if idx - 1 < len(child_requirements) else {}-- if child_req.get("question_type"):- requirement_variant["question_type"] = child_req["question_type"]- if child_req.get("difficulty"):- requirement_variant["difficulty"] = child_req["difficulty"]-- existing_extra = requirement_variant.get("additional_requirements", "").strip()- child_extra = child_req.get("additional_requirements", "").strip()- title = child_req.get("title", f"Variant #{idx}")-- directive = (- f"[Auto-derived sub requirement #{idx}: {title}]\n"- "Maintain the exact same core knowledge point(s) as the base requirement.\n"- "Use the retrieved knowledge summary to shape the scenario.\n"- "Ensure the scenario and reasoning steps are distinct from other variants.\n"- f"{child_extra}"- )-- combined_requirements = "\n\n".join(- part for part in [existing_extra, directive] if part- )- requirement_variant["additional_requirements"] = combined_requirements- requirement_variant["batch_index"] = idx-- result = await self.generate_question(requirement_variant)-- if result.get("success"):- results.append(result)- else:- failures.append(- {"index": idx, "error": result.get("error"), "reason": result.get("reason")}- )- # If any child requirement fails (e.g., due to knowledge issues), stop the batch early- self.logger.error(f"Batch aborted due to failure while generating variant #{idx}")- break-- summary = {- "success": len(results) == num_questions and len(failures) == 0,- "requested": num_questions,- "completed": len(results),- "failed": len(failures),- "search_queries": queries,- "knowledge_summary": knowledge_summary,- "child_requirements": child_requirements,- "results": results,- "failures": failures,- }-- # Persist batch results if output_dir is provided- if self.output_dir:- try:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- out_path = Path(self.output_dir)- out_path.mkdir(parents=True, exist_ok=True)- batch_file = out_path / f"batch_{timestamp}.json"- with open(batch_file, "w", encoding="utf-8") as f:- json.dump(summary, f, indent=2, ensure_ascii=False)- summary["output_file"] = str(batch_file)- self.logger.info(f"Batch results saved to: {batch_file}")- except Exception as e:- self.logger.warning(f"Failed to save batch results: {e}")-- self.logger.section("Batch Generation Summary")- self.logger.info(f"Requested : {num_questions}")- self.logger.info(f"Completed : {len(results)}")- self.logger.info(f"Failed : {len(failures)}")-- return summary-- async def generate_questions_from_prompt(- self, requirement_text: str, num_questions: int- ) -> dict[str, Any]:- """- Entry point for users supplying only natural-language requirements.- """- self._suppress_logging()-- queries = await self._generate_search_queries_from_text(- requirement_text, max(3, num_questions)- )- retrievals = await self._gather_retrieval_context(queries)- knowledge_summary = self._summarize_retrievals(retrievals)-- # Check if any content was retrieved- has_content = any(retrieval.get("answer", "").strip() for retrieval in retrievals)-- if not has_content:- return {- "success": False,- "error": "knowledge_not_found",- "message": "Knowledge base does not contain relevant information for the request.",- "search_queries": queries,- "knowledge_summary": knowledge_summary,- }-- relevant = await self._check_retrieval_relevance(requirement_text, knowledge_summary)- if not relevant:- return {- "success": False,- "error": "knowledge_not_found",- "message": "Knowledge base appears unrelated to the requested topic.",- "search_queries": queries,- "knowledge_summary": knowledge_summary,- }-- base_requirement = await self._interpret_requirement_text(requirement_text)- return await self.generate_multiple_questions(- base_requirement,- num_questions,- precomputed_queries=queries,- precomputed_retrievals=retrievals,- precomputed_summary=knowledge_summary,- )-- async def _plan_sub_focuses(- self,- base_requirement: dict[str, Any],- shared_context: str,- num_questions: int,- ) -> list[dict[str, Any]]:- """Plan distinct sub-focuses for each question in one LLM call."""- system_prompt = (- "You are an educational content planner. Given a base requirement and knowledge context, "- "create distinct sub-focuses for generating multiple questions on the SAME topic. "- "Each sub-focus should describe a unique angle, scenario, or aspect to test. "- 'Output JSON with key "focuses" containing an array of objects, each with: '- '"id" (string like "q_1"), "focus" (string describing the specific angle), '- '"scenario_hint" (brief scenario suggestion).'- )- user_prompt = (- f"Base requirement:\n{json.dumps(base_requirement, ensure_ascii=False, indent=2)}\n\n"- f"Available knowledge context:\n{shared_context[:3000]}...\n\n"- f"Generate exactly {num_questions} distinct sub-focuses in JSON."- )- try:- content = await self._call_llm(- system_prompt=system_prompt, user_prompt=user_prompt, stage="plan_sub_focuses"- )- parsed = json.loads(content)- focuses = parsed.get("focuses", [])- if not isinstance(focuses, list):- focuses = []- except Exception as e:- self.logger.warning(f"Failed to plan sub-focuses: {e}")- focuses = []-- # Fallback: create simple numbered focuses- if len(focuses) < num_questions:- for i in range(len(focuses), num_questions):- focuses.append(- {- "id": f"q_{i + 1}",- "focus": f"Variant {i + 1}: Different scenario using the same knowledge point",- "scenario_hint": f"Create a distinct problem #{i + 1}",- }- )-- return focuses[:num_questions]-- async def _generate_single_question_with_context(- self,- question_id: str,- base_requirement: dict[str, Any],- focus: dict[str, Any],- shared_context: str,- full_plan: list[dict[str, Any]],- semaphore: asyncio.Semaphore,- ) -> dict[str, Any]:- """Generate a single question with shared context and full plan awareness."""- async with semaphore:- try:- # Send progress update- await self._send_ws_update(- "question_update",- {- "question_id": question_id,- "status": "generating",- "focus": focus.get("focus", ""),- },- )-- # Create a fresh agent for this question- gen_agent_config = self.config.get("agents", {}).get("question_generation", {})- max_gen_iterations = gen_agent_config.get("max_iterations", 5)-- question_agent = QuestionGenerationAgent(- api_key=self._api_key,- base_url=self._base_url,- api_version=self._api_version,- max_iterations=max_gen_iterations,- kb_name=self.kb_name,- token_stats_callback=self.update_token_stats,- )-- # Build requirement with focus and plan awareness- requirement_variant = copy.deepcopy(base_requirement)-- # Build plan summary to prevent duplication- other_focuses = [f for f in full_plan if f.get("id") != question_id]- plan_summary = "\n".join(- [f"- {f.get('id')}: {f.get('focus', 'N/A')}" for f in other_focuses]- )-- focus_directive = (- f"[Question {question_id}]\n"- f"Focus: {focus.get('focus', 'Generate a question')}\n"- f"Scenario hint: {focus.get('scenario_hint', '')}\n\n"- "IMPORTANT: The following focuses are assigned to OTHER questions in this batch. "- "You MUST create a question that is DISTINCT from these:\n"- f"{plan_summary}\n\n"- "Use the provided knowledge context to ensure accuracy."- )-- existing_extra = requirement_variant.get("additional_requirements", "").strip()- requirement_variant["additional_requirements"] = "\n\n".join(- filter(None, [existing_extra, focus_directive])- )- requirement_variant["batch_index"] = question_id- requirement_variant["_shared_context"] = shared_context-- # Set up the agent- question_agent.set_requirement(requirement_variant)-- # Pre-populate retrieved knowledge with shared context- question_agent.retrieved_knowledge = [- {- "query": "shared_batch_context",- "answer": shared_context,- }- ]-- # Create message queue for this agent- local_queue = asyncio.Queue()-- async def local_send_message(msg):- await local_queue.put(msg)-- question_agent.send_message = local_send_message-- # Run generation loop- for round_num in range(1, self.max_rounds + 1):- await self._send_ws_update(- "question_update",- {"question_id": question_id, "status": "generating", "round": round_num},- )-- question_agent.submitted = False- task = f"Generate a question based on the focus: {focus.get('focus', '')}"-- if round_num > 1:- task = "Revise the question based on validation feedback"-- question_result = await question_agent.run(- task=task,- context={"requirement": requirement_variant, "round_num": round_num},- send_message_callback=local_send_message,- )-- if not question_result.get("success"):- continue-- # Check for rejection- result_data = question_result.get("result")- if isinstance(result_data, dict) and result_data.get("task_rejected"):- return {- "success": False,- "question_id": question_id,- "error": "task_rejected",- "reason": result_data.get("reason", "Knowledge missing"),- }-- if not question_agent.submitted:- continue-- # Get submitted question from queue- question = None- while not local_queue.empty():- msg = await local_queue.get()- if msg.message_type == "validate_request":- question = msg.content.get("question")-- if not question:- continue-- # Validate- await self._send_ws_update(- "question_update",- {"question_id": question_id, "status": "validating", "round": round_num},- )-- question["knowledge_point"] = base_requirement.get("knowledge_point", "")- reference_question = base_requirement.get("reference_question")- validation_result = await self.validation_workflow.validate(- question, reference_question- )-- decision = validation_result.get("decision")-- if decision == "approve":- await self._send_ws_update(- "question_update", {"question_id": question_id, "status": "done"}- )-- # Save question to disk- output_dir = self._save_question_result(- question=question,- requirement=base_requirement,- validation=validation_result,- round_num=round_num,- extended=False,- )-- result = {- "success": True,- "question_id": question_id,- "question": question,- "validation": validation_result,- "rounds": round_num,- "focus": focus,- }- if output_dir:- result["output_dir"] = output_dir- return result-- # Send feedback for next round- if decision in ["request_modification", "request_regeneration"]:- message = Message(- from_agent="QuestionValidationWorkflow",- to_agent="QuestionGenerationAgent",- message_type=decision,- content={- "issues": validation_result.get("issues", []),- "suggestions": validation_result.get("suggestions", []),- "reasoning": validation_result.get("reasoning", ""),- },- )- question_agent.receive_message(message)-- # Max rounds reached - return as extended question instead of failure- last_question = question_agent.current_question- if last_question:- # Get extension analysis from validation workflow- extension_analysis = await self.validation_workflow.analyze_extension(- last_question, shared_context- )-- await self._send_ws_update(- "question_update",- {"question_id": question_id, "status": "done", "extended": True},- )-- validation = {- "decision": "extended",- "reasoning": extension_analysis.get("reasoning", ""),- "kb_connection": extension_analysis.get("kb_connection", ""),- "extended_aspect": extension_analysis.get("extended_aspect", ""),- }-- # Save extended question to disk- output_dir = self._save_question_result(- question=last_question,- requirement=base_requirement,- validation=validation,- round_num=self.max_rounds,- extended=True,- )-- result = {- "success": True,- "question_id": question_id,- "question": last_question,- "validation": validation,- "rounds": self.max_rounds,- "focus": focus,- "extended": True,- }- if output_dir:- result["output_dir"] = output_dir- return result- else:- # No question was generated at all- await self._send_ws_update(- "question_update", {"question_id": question_id, "status": "error"}- )- return {- "success": False,- "question_id": question_id,- "error": f"Max rounds ({self.max_rounds}) reached without generating a question",- }-- except Exception as e:- self.logger.error(f"Error generating question {question_id}: {e}")- await self._send_ws_update(- "question_update", {"question_id": question_id, "status": "error"}- )- return {- "success": False,- "question_id": question_id,- "error": str(e),- }-- async def generate_questions_parallel(- self,- base_requirement: dict[str, Any],- num_questions: int,- ) -> dict[str, Any]:- """- Generate multiple questions in parallel with shared context.-- New flow:- 1. Split user input into N RAG queries- 2. Run RAG queries in parallel- 3. Merge results into shared context- 4. Plan sub-focuses for all questions at once- 5. Generate questions in parallel (with semaphore control)- """- if num_questions <= 0:- raise ValueError("num_questions must be greater than zero")-- self._suppress_logging()-- # Send initial progress- await self._send_ws_update(- "progress",- {- "stage": "planning",- "progress": {"status": "splitting_queries"},- "total": num_questions,- },- )-- # Step 1: Split into RAG queries- self.logger.section(f"Parallel Generation: {num_questions} question(s)")- self.logger.info("Step 1: Splitting into RAG queries...")-- queries = await self._generate_search_queries(base_requirement, self.rag_query_count)- self.logger.info(f"Generated {len(queries)} search queries")-- # Step 2: Run RAG queries in parallel- await self._send_ws_update(- "progress",- {"stage": "researching", "progress": {"status": "retrieving"}, "queries": queries},- )- self.logger.info("Step 2: Retrieving knowledge in parallel...")-- retrievals = await self._gather_retrieval_context(queries)-- # Step 3: Merge into shared context- shared_context = self._summarize_retrievals(retrievals)-- # Check if we have any content- has_content = any(r.get("answer", "").strip() for r in retrievals)- if not has_content:- return {- "success": False,- "error": "knowledge_not_found",- "message": "Knowledge base does not contain relevant information for the request.",- "search_queries": queries,- }-- self.logger.info(f"Merged {len(retrievals)} retrieval results into shared context")-- # Step 4: Plan sub-focuses- await self._send_ws_update(- "progress", {"stage": "planning", "progress": {"status": "planning_focuses"}}- )- self.logger.info("Step 3: Planning sub-focuses for all questions...")-- sub_focuses = await self._plan_sub_focuses(base_requirement, shared_context, num_questions)- self.logger.info(f"Planned {len(sub_focuses)} sub-focuses")-- # Send focuses to frontend- await self._send_ws_update(- "progress",- {- "stage": "generating",- "progress": {"status": "starting_parallel"},- "total": num_questions,- "focuses": sub_focuses,- },- )-- # Step 5: Generate questions in parallel- self.logger.info(- f"Step 4: Generating {num_questions} questions in parallel (max {self.max_parallel_questions} concurrent)..."- )-- semaphore = asyncio.Semaphore(self.max_parallel_questions)-- tasks = [- self._generate_single_question_with_context(- question_id=focus.get("id", f"q_{i + 1}"),- base_requirement=base_requirement,- focus=focus,- shared_context=shared_context,- full_plan=sub_focuses,- semaphore=semaphore,- )- for i, focus in enumerate(sub_focuses)- ]-- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Step 6: Aggregate results- successes = []- failures = []-- for i, result in enumerate(results):- if isinstance(result, Exception):- failures.append(- {- "question_id": f"q_{i + 1}",- "error": str(result),- }- )- elif result.get("success"):- successes.append(result)- else:- failures.append(- {- "question_id": result.get("question_id", f"q_{i + 1}"),- "error": result.get("error", "Unknown error"),- "reason": result.get("reason", ""),- }- )-- summary = {- "success": len(successes) == num_questions,- "requested": num_questions,- "completed": len(successes),- "failed": len(failures),- "search_queries": queries,- "shared_context": shared_context[:500] + "..."- if len(shared_context) > 500- else shared_context,- "sub_focuses": sub_focuses,- "results": successes,- "failures": failures,- }-- # Persist results if output_dir is provided- if self.output_dir:- try:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- out_path = Path(self.output_dir)- out_path.mkdir(parents=True, exist_ok=True)- batch_file = out_path / f"parallel_batch_{timestamp}.json"- with open(batch_file, "w", encoding="utf-8") as f:- json.dump(summary, f, indent=2, ensure_ascii=False)- summary["output_file"] = str(batch_file)- self.logger.info(f"Results saved to: {batch_file}")- except Exception as e:- self.logger.warning(f"Failed to save results: {e}")-- # Send completion- await self._send_ws_update(- "progress",- {- "stage": "complete",- "completed": len(successes),- "failed": len(failures),- "total": num_questions,- },- )-- self.logger.section("Parallel Generation Summary")- self.logger.info(f"Requested : {num_questions}")- self.logger.info(f"Completed : {len(successes)}")- self.logger.info(f"Failed : {len(failures)}")-- return summary-- # =========================================================================- # Custom Mode Methods - New streamlined flow without iteration- # =========================================================================-- async def _single_rag_search_naive(self, query: str) -> dict[str, Any]:- """Execute a single RAG search using naive mode."""- result = await rag_search(- query=query,- kb_name=self.kb_name,- mode="naive",- only_need_context=True,- )- return {- "query": query,- "answer": result.get("answer", ""),- "mode": "naive",- }-- async def _gather_retrieval_context_naive(self, queries: list[str]) -> list[dict[str, Any]]:- """Run retrieval for each query in parallel using naive mode."""- self._update_agent_status("RetrievalTool", "running")- self.logger.info(- f"Retrieving background knowledge for {len(queries)} queries (naive mode)..."- )-- # Execute all queries in parallel- tasks = [self._single_rag_search_naive(query) for query in queries]- results = await asyncio.gather(*tasks, return_exceptions=True)-- retrievals = []- for i, result in enumerate(results):- query = queries[i]- if isinstance(result, Exception):- self.logger.warning(f"Retrieval failed for query '{query}': {result}")- continue-- self.logger.debug(f" → Query: {query[:50]}... (retrieved)")- retrievals.append(- {- "query": query,- "answer": result.get("answer", ""),- }- )-- self._update_agent_status("RetrievalTool", "done")- return retrievals-- async def _generate_question_plan(- self,- base_requirement: dict[str, Any],- knowledge_summary: str,- num_questions: int,- ) -> dict[str, Any]:- """- Generate a question plan with focuses for each question.-- Args:- base_requirement: Base requirement with knowledge_point, difficulty, question_type- knowledge_summary: Summary of retrieved background knowledge- num_questions: Number of questions to generate-- Returns:- Plan dict with "focuses" array containing {id, focus, type} for each question- """- difficulty = base_requirement.get("difficulty", "medium")- question_type = base_requirement.get("question_type", "written")- knowledge_point = base_requirement.get("knowledge_point", "")-- system_prompt = (- "You are an educational content planner. Given a topic, difficulty level, "- "question type, and background knowledge, create a structured question plan.\n\n"- "Each question focus should:\n"- "1. Test a specific aspect or angle of the knowledge point\n"- "2. Be distinct from other focuses (different scenarios, applications, or perspectives)\n"- "3. Match the specified difficulty level\n"- "4. Be achievable with the provided background knowledge\n\n"- "CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks (```json). "- "Do not include any explanatory text before or after the JSON. "- "Your response must start with { and end with }.\n\n"- 'Output JSON with key "focuses" containing an array of objects, each with:\n'- '- "id": string like "q_1", "q_2", etc.\n'- '- "focus": string describing what specific aspect this question will test\n'- '- "type": "choice" or "written" (should match the requested type)\n'- )-- user_prompt = (- f"Topic/Knowledge Point: {knowledge_point}\n"- f"Difficulty: {difficulty}\n"- f"Question Type: {question_type}\n"- f"Number of Questions: {num_questions}\n\n"- f"Background Knowledge:\n{knowledge_summary[:3000]}...\n\n"- f"Generate exactly {num_questions} distinct question focuses in JSON format."- )-- try:- content = await self._call_llm(- system_prompt=system_prompt, user_prompt=user_prompt, stage="generate_question_plan"- )-- # Validate content before JSON parsing- if not content or content.strip() == "":- self.logger.error("LLM returned empty content for question plan generation")- self.logger.error(f"Response content: {repr(content)}")- focuses = []- else:- try:- # Extract JSON from markdown code blocks if present- json_content = self._extract_json_from_markdown(content)- parsed = json.loads(json_content)- focuses = parsed.get("focuses", [])- if not isinstance(focuses, list):- focuses = []- except json.JSONDecodeError as json_err:- self.logger.error(f"JSON parsing failed for question plan: {json_err}")- self.logger.error(f"Response content (first 500 chars): {content[:500]}")- focuses = []- except Exception as e:- self.logger.warning(f"Failed to generate question plan: {e}")- focuses = []-- # Fallback: create simple numbered focuses- if len(focuses) < num_questions:- for i in range(len(focuses), num_questions):- focuses.append(- {- "id": f"q_{i + 1}",- "focus": f"Aspect {i + 1} of {knowledge_point}",- "type": question_type,- }- )-- # Ensure all focuses have the correct type- for focus in focuses:- if "type" not in focus:- focus["type"] = question_type- if "id" not in focus:- focus["id"] = f"q_{focuses.index(focus) + 1}"-- return {- "knowledge_point": knowledge_point,- "difficulty": difficulty,- "question_type": question_type,- "num_questions": num_questions,- "focuses": focuses[:num_questions],- }-- def _save_knowledge_json(- self,- batch_dir: Path,- queries: list[str],- retrievals: list[dict[str, Any]],- ) -> str:- """Save background knowledge to knowledge.json."""- knowledge_data = {- "queries": queries,- "retrievals": retrievals,- "total_queries": len(queries),- "successful_retrievals": len([r for r in retrievals if r.get("answer")]),- }-- knowledge_file = batch_dir / "knowledge.json"- with open(knowledge_file, "w", encoding="utf-8") as f:- json.dump(knowledge_data, f, indent=2, ensure_ascii=False)-- self.logger.info(f"Background knowledge saved to: {knowledge_file}")- return str(knowledge_file)-- def _save_plan_json(self, batch_dir: Path, plan: dict[str, Any]) -> str:- """Save question plan to plan.json."""- plan_file = batch_dir / "plan.json"- with open(plan_file, "w", encoding="utf-8") as f:- json.dump(plan, f, indent=2, ensure_ascii=False)-- self.logger.info(f"Question plan saved to: {plan_file}")- return str(plan_file)-- def _save_custom_question_result(- self,- batch_dir: Path,- question_id: str,- question: dict[str, Any],- validation: dict[str, Any],- focus: dict[str, Any],- ) -> str:- """Save a single question result in custom mode."""- question_dir = batch_dir / question_id- question_dir.mkdir(parents=True, exist_ok=True)-- # Build result structure- result = {- "question_id": question_id,- "focus": focus,- "question": question,- "validation": validation,- }-- # Save result.json- result_file = question_dir / "result.json"- with open(result_file, "w", encoding="utf-8") as f:- json.dump(result, f, indent=2, ensure_ascii=False)-- # Build question.md- relevance = validation.get("relevance", "unknown")- kb_coverage = validation.get("kb_coverage", "")- extension_points = validation.get("extension_points", "")-- md_content = f"""# Generated Question--**Focus**: {focus.get("focus", "N/A")}-**Type**: {focus.get("type", question.get("question_type", "N/A"))}-------## Question-{question.get("question", "")}--"""- if question.get("options"):- md_content += "## Options\n"- for key, value in question.get("options", {}).items():- md_content += f"- **{key}**: {value}\n"- md_content += "\n"-- md_content += f"""-## Answer-{question.get("correct_answer", "")}+ def _update_token_stats(self):+ """Update token_stats from BaseAgent's shared LLMStats for the question module."""+ from src.agents.base_agent import BaseAgent-## Explanation-{question.get("explanation", "")}+ try:+ stats = BaseAgent.get_stats("question")+ summary = stats.get_summary()++ self.token_stats = {+ "model": summary.get("model", "gpt-4o-mini"),+ "calls": summary.get("calls", 0),+ "tokens": summary.get("total_tokens", 0),+ "input_tokens": summary.get("input_tokens", 0),+ "output_tokens": summary.get("output_tokens", 0),+ "cost": summary.get("cost", 0.0),+ }+ except Exception as e:+ self.logger.debug(f"Failed to update token stats: {e}")----+ def set_ws_callback(self, callback: Callable):+ """Set WebSocket callback for streaming updates to frontend."""+ self._ws_callback = callback-## Relevance Analysis+ async def _send_ws_update(self, update_type: str, data: dict[str, Any]):+ """Send update via WebSocket callback if available."""+ if self._ws_callback:+ try:+ await self._ws_callback({"type": update_type, **data})+ except Exception as e:+ self.logger.debug(f"Failed to send WS update: {e}")-**Relevance Level**: {relevance}+ def _create_retrieve_agent(self) -> RetrieveAgent:+ """Create a RetrieveAgent instance."""+ return RetrieveAgent(+ kb_name=self.kb_name,+ rag_mode=self.rag_mode,+ language=self.language,+ api_key=self._api_key,+ base_url=self._base_url,+ api_version=self._api_version,+ )-**Knowledge Base Coverage**:-{kb_coverage}-"""- if extension_points:- md_content += f"""-**Extension Points**:-{extension_points}-"""+ def _create_generate_agent(self) -> GenerateAgent:+ """Create a GenerateAgent instance."""+ return GenerateAgent(+ language=self.language,+ api_key=self._api_key,+ base_url=self._base_url,+ api_version=self._api_version,+ )- md_file = question_dir / "question.md"- with open(md_file, "w", encoding="utf-8") as f:- f.write(md_content)+ def _create_relevance_analyzer(self) -> RelevanceAnalyzer:+ """Create a RelevanceAnalyzer instance."""+ return RelevanceAnalyzer(+ language=self.language,+ api_key=self._api_key,+ base_url=self._base_url,+ api_version=self._api_version,+ )- return str(question_dir)+ # =========================================================================+ # Main Entry Points+ # =========================================================================- async def _generate_single_question_custom(+ async def generate_question(self,- focus: dict[str, Any],- base_requirement: dict[str, Any],- knowledge_summary: str,+ requirement: dict[str, Any],) -> dict[str, Any]:"""- Generate a single question without iteration loop (custom mode).+ Generate a single question with relevance analysis.++ This is used by Mimic mode and for single question generation.++ Args:+ requirement: Question requirement dictReturns:- Dict with question data+ Dict with:+ - success: bool+ - question: Generated question dict+ - analysis: Relevance analysis result+ - rounds: Always 1 (no iteration)"""- question_id = focus.get("id", "q_1")- question_type = focus.get("type", base_requirement.get("question_type", "written"))- focus_text = focus.get("focus", "")- knowledge_point = base_requirement.get("knowledge_point", "")- difficulty = base_requirement.get("difficulty", "medium")+ self.logger.section("Single Question Generation")+ self.logger.info(f"Knowledge point: {requirement.get('knowledge_point', 'N/A')}")- system_prompt = (- "You are a professional question designer. Generate a high-quality exam question "- "based on the provided focus and background knowledge.\n\n"- "Requirements:\n"- "1. The question must align with the specified focus\n"- "2. Use the background knowledge to ensure accuracy\n"- "3. Match the difficulty level\n"- "4. Provide a detailed explanation\n\n"- "CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks (```json). "- "Do not include any explanatory text before or after the JSON. "- "Your response must start with { and end with }.\n"+ await self._send_ws_update(+ "progress", {"stage": "generating", "progress": {"status": "initializing"}})- if question_type == "choice":- output_format = """Output JSON format:-{- "question_type": "choice",- "question": "question content",- "options": {"A": "...", "B": "...", "C": "...", "D": "..."},- "correct_answer": "A/B/C/D",- "explanation": "detailed explanation"-}"""- else:- output_format = """Output JSON format:-{- "question_type": "written",- "question": "question content",- "correct_answer": "detailed answer",- "explanation": "detailed explanation"-}"""-- user_prompt = (- f"Knowledge Point: {knowledge_point}\n"- f"Focus: {focus_text}\n"- f"Difficulty: {difficulty}\n"- f"Question Type: {question_type}\n\n"- f"Background Knowledge:\n{knowledge_summary[:4000]}\n\n"- f"{output_format}"+ # Step 1: Retrieve knowledge+ retrieve_agent = self._create_retrieve_agent()+ retrieval_result = await retrieve_agent.process(+ requirement=requirement,+ num_queries=self.rag_query_count,)- try:- content = await self._call_llm(- system_prompt=system_prompt,- user_prompt=user_prompt,- stage=f"generate_question_{question_id}",- )+ if not retrieval_result.get("has_content"):+ self.logger.warning("No relevant knowledge found")+ return {+ "success": False,+ "error": "knowledge_not_found",+ "message": "Knowledge base does not contain relevant information.",+ }- # Validate content before JSON parsing- if not content or content.strip() == "":- self.logger.error(f"LLM returned empty content for question {question_id}")- self.logger.error(f"Response content: {repr(content)}")- return {- "success": False,- "error": "LLM returned empty response",- }+ knowledge_context = retrieval_result["summary"]- try:- # Extract JSON from markdown code blocks if present- json_content = self._extract_json_from_markdown(content)- question = json.loads(json_content)- question["knowledge_point"] = knowledge_point- return {- "success": True,- "question": question,- }- except json.JSONDecodeError as json_err:- self.logger.error(f"JSON parsing failed for question {question_id}: {json_err}")- self.logger.error(f"Response content (first 500 chars): {content[:500]}")- return {- "success": False,- "error": f"Invalid JSON response: {str(json_err)}",- }- except Exception as e:- self.logger.error(f"Failed to generate question {question_id}: {e}")+ # Step 2: Generate question+ generate_agent = self._create_generate_agent()++ # Check if this is mimic mode (has reference_question)+ reference_question = requirement.get("reference_question")++ gen_result = await generate_agent.process(+ requirement=requirement,+ knowledge_context=knowledge_context,+ reference_question=reference_question,+ )++ if not gen_result.get("success"):+ self.logger.error(f"Question generation failed: {gen_result.get('error')}")return {"success": False,- "error": str(e),+ "error": gen_result.get("error", "Generation failed"),}+ question = gen_result["question"]++ # Step 3: Analyze relevance+ analyzer = self._create_relevance_analyzer()+ analysis = await analyzer.process(+ question=question,+ knowledge_context=knowledge_context,+ )++ self.logger.success(f"Question generated with {analysis['relevance']} relevance")++ # Build result (compatible with old format)+ result = {+ "success": True,+ "question": question,+ "validation": {+ "decision": "approve", # Always approve+ "relevance": analysis["relevance"],+ "kb_coverage": analysis["kb_coverage"],+ "extension_points": analysis.get("extension_points", ""),+ },+ "rounds": 1, # No iteration+ }++ # Save to disk if output_dir is set+ if self.output_dir:+ self._save_question_result(result, requirement)++ # Update token stats from shared LLMStats+ self._update_token_stats()++ return result+async def generate_questions_custom(self,- base_requirement: dict[str, Any],+ requirement: dict[str, Any],num_questions: int,) -> dict[str, Any]:"""- Custom mode: Generate questions with the new streamlined flow.+ Custom mode: Generate multiple questions from a requirement.Flow:- 1. Researching: Generate RAG queries, retrieve with naive mode, save knowledge.json- 2. Planning: Generate question plan, save plan.json- 3. Generating: For each focus, generate question + relevance analysis+ 1. Researching: Retrieve background knowledge+ 2. Planning: Generate question plan with focuses+ 3. Generating: Generate each question + relevance analysisArgs:- base_requirement: Dict with knowledge_point, difficulty, question_type+ requirement: Base requirement dict (knowledge_point, difficulty, question_type)num_questions: Number of questions to generateReturns:@@ -2011,7 +280,7 @@ class AgentCoordinator:if num_questions <= 0:raise ValueError("num_questions must be greater than zero")- self._suppress_logging()+ self.logger.section(f"Custom Mode Generation: {num_questions} question(s)")# Create batch directorytimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")@@ -2019,100 +288,74 @@ class AgentCoordinator:if batch_dir:batch_dir.mkdir(parents=True, exist_ok=True)- self.logger.section(f"Custom Mode Generation: {num_questions} question(s)")-# =====================================================================- # Stage 1: Researching - Retrieve background knowledge+ # Stage 1: Researching# =====================================================================self.logger.stage("Stage 1: Researching")await self._send_ws_update("progress",- {- "stage": "researching",- "progress": {"status": "generating_queries"},- "total": num_questions,- },- )-- # Generate search queries- requirement_text = json.dumps(base_requirement, ensure_ascii=False)- queries = await self._generate_search_queries_from_text(- requirement_text, self.rag_query_count+ {"stage": "researching", "progress": {"status": "retrieving"}, "total": num_questions},)- self.logger.info(f"Generated {len(queries)} search queries: {queries}")- await self._send_ws_update(- "progress",- {"stage": "researching", "progress": {"status": "retrieving"}, "queries": queries},+ retrieve_agent = self._create_retrieve_agent()+ retrieval_result = await retrieve_agent.process(+ requirement=requirement,+ num_queries=self.rag_query_count,)- # Retrieve using naive mode- retrievals = await self._gather_retrieval_context_naive(queries)- knowledge_summary = self._summarize_retrievals(retrievals)-- # Check if we have any content- has_content = any(r.get("answer", "").strip() for r in retrievals)- if not has_content:- self.logger.warning("No content retrieved from knowledge base")+ if not retrieval_result.get("has_content"):+ self.logger.warning("No relevant knowledge found")return {"success": False,"error": "knowledge_not_found",- "message": "Knowledge base does not contain relevant information for the request.",- "search_queries": queries,+ "message": "Knowledge base does not contain relevant information.",+ "search_queries": retrieval_result.get("queries", []),}+ knowledge_context = retrieval_result["summary"]+ queries = retrieval_result["queries"]+# Save knowledge.jsonif batch_dir:- self._save_knowledge_json(batch_dir, queries, retrievals)+ self._save_knowledge_json(batch_dir, retrieval_result)- await self._send_ws_update(- "progress", {"stage": "researching", "progress": {"status": "completed"}}- )await self._send_ws_update("knowledge_saved", {"queries": queries})# =====================================================================- # Stage 2: Planning - Generate question plan+ # Stage 2: Planning# =====================================================================self.logger.stage("Stage 2: Planning")await self._send_ws_update("progress", {"stage": "planning", "progress": {"status": "creating_plan"}})- plan = await self._generate_question_plan(- base_requirement, knowledge_summary, num_questions- )+ plan = await self._generate_question_plan(requirement, knowledge_context, num_questions)focuses = plan.get("focuses", [])- self.logger.info(f"Generated plan with {len(focuses)} focuses")# Save plan.jsonif batch_dir:self._save_plan_json(batch_dir, plan)- await self._send_ws_update(- "progress",- {"stage": "planning", "progress": {"status": "completed"}, "focuses": focuses},- )await self._send_ws_update("plan_ready", {"plan": plan, "focuses": focuses})# =====================================================================- # Stage 3: Generating - Generate each question+ # Stage 3: Generating# =====================================================================self.logger.stage("Stage 3: Generating")await self._send_ws_update("progress",- {- "stage": "generating",- "progress": {"current": 0, "total": num_questions},- "focuses": focuses,- },+ {"stage": "generating", "progress": {"current": 0, "total": num_questions}},)results = []failures = []+ generate_agent = self._create_generate_agent()+ analyzer = self._create_relevance_analyzer()+for idx, focus in enumerate(focuses):question_id = focus.get("id", f"q_{idx + 1}")- self.logger.info(f"Generating question {question_id}: {focus.get('focus', '')[:50]}...")+ self.logger.info(f"Generating question {question_id}")await self._send_ws_update("question_update",@@ -2123,11 +366,11 @@ class AgentCoordinator:},)- # Generate question (single pass, no iteration)- gen_result = await self._generate_single_question_custom(+ # Generate question+ gen_result = await generate_agent.process(+ requirement=requirement,+ knowledge_context=knowledge_context,focus=focus,- base_requirement=base_requirement,- knowledge_summary=knowledge_summary,)if not gen_result.get("success"):@@ -2145,32 +388,36 @@ class AgentCoordinator:question = gen_result["question"]- # Perform relevance analysis+ # Analyze relevanceawait self._send_ws_update("question_update", {"question_id": question_id, "status": "analyzing"})- validation = await self.validation_workflow.analyze_relevance(+ analysis = await analyzer.process(question=question,- knowledge_summary=knowledge_summary,+ knowledge_context=knowledge_context,)- # Save result- if batch_dir:- self._save_custom_question_result(- batch_dir=batch_dir,- question_id=question_id,- question=question,- validation=validation,- focus=focus,- )+ # Build validation dict (compatible with frontend)+ validation = {+ "decision": "approve",+ "relevance": analysis["relevance"],+ "kb_coverage": analysis["kb_coverage"],+ "extension_points": analysis.get("extension_points", ""),+ }+ # Save resultresult = {"question_id": question_id,"focus": focus,"question": question,- "validation": validation,+ "analysis": analysis,+ "validation": validation, # For frontend compatibility}++ if batch_dir:+ self._save_custom_question_result(batch_dir, result)+results.append(result)await self._send_ws_update(@@ -2181,14 +428,11 @@ class AgentCoordinator:{"question_id": question_id,"question": question,- "validation": validation,+ "validation": validation, # Frontend expects 'validation'"focus": focus,"index": idx,- "rounds": 1, # Custom mode has single-pass generation},)-- # Update progressawait self._send_ws_update("progress",{"stage": "generating", "progress": {"current": idx + 1, "total": num_questions}},@@ -2208,13 +452,14 @@ class AgentCoordinator:"failures": failures,}- # Save summary.jsonif batch_dir:summary_file = batch_dir / "summary.json"with open(summary_file, "w", encoding="utf-8") as f:json.dump(summary, f, indent=2, ensure_ascii=False)summary["output_dir"] = str(batch_dir)- self.logger.info(f"Summary saved to: {summary_file}")++ # Update token stats from shared LLMStats+ self._update_token_stats()await self._send_ws_update("progress",@@ -2226,9 +471,248 @@ class AgentCoordinator:},)- self.logger.section("Custom Mode Generation Summary")- self.logger.info(f"Requested : {num_questions}")- self.logger.info(f"Completed : {len(results)}")- self.logger.info(f"Failed : {len(failures)}")+ self.logger.section("Generation Summary")+ self.logger.info(f"Requested: {num_questions}")+ self.logger.info(f"Completed: {len(results)}")+ self.logger.info(f"Failed: {len(failures)}")return summary++ # =========================================================================+ # Helper Methods+ # =========================================================================++ async def _generate_question_plan(+ self,+ requirement: dict[str, Any],+ knowledge_context: str,+ num_questions: int,+ ) -> dict[str, Any]:+ """+ Generate a question plan with distinct focuses.++ Args:+ requirement: Base requirement+ knowledge_context: Retrieved knowledge summary+ num_questions: Number of questions++ Returns:+ Plan dict with focuses array+ """+ from src.services.llm import complete as llm_complete+ from src.services.llm.config import get_llm_config++ llm_config = get_llm_config()++ system_prompt = (+ "You are an educational content planner. Create distinct question focuses "+ "that test different aspects of the same topic.\n\n"+ "CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.\n"+ 'Output JSON with key "focuses" containing an array of objects, each with:\n'+ '- "id": string like "q_1", "q_2"\n'+ '- "focus": string describing what aspect to test\n'+ f'- "type": "{requirement.get("question_type", "written")}"'+ )++ # Truncate knowledge context consistently (4000 chars across all agents)+ truncated_knowledge = (+ knowledge_context[:4000] if len(knowledge_context) > 4000 else knowledge_context+ )+ truncation_suffix = "...[truncated]" if len(knowledge_context) > 4000 else ""++ user_prompt = (+ f"Topic: {requirement.get('knowledge_point', '')}\n"+ f"Difficulty: {requirement.get('difficulty', 'medium')}\n"+ f"Question Type: {requirement.get('question_type', 'written')}\n"+ f"Number: {num_questions}\n\n"+ f"Knowledge:\n{truncated_knowledge}{truncation_suffix}\n\n"+ f"Generate exactly {num_questions} distinct focuses in JSON."+ )++ try:+ response = await llm_complete(+ prompt=user_prompt,+ system_prompt=system_prompt,+ model=llm_config.model,+ api_key=self._api_key or llm_config.api_key,+ base_url=self._base_url or llm_config.base_url,+ api_version=self._api_version,+ response_format={"type": "json_object"},+ temperature=0.3,+ )++ data = json.loads(response)+ focuses = data.get("focuses", [])+ if not isinstance(focuses, list):+ focuses = []++ except Exception as e:+ self.logger.warning(f"Failed to generate plan: {e}")+ focuses = []++ # Fallback: create simple focuses+ if len(focuses) < num_questions:+ question_type = requirement.get("question_type", "written")+ for i in range(len(focuses), num_questions):+ focuses.append(+ {+ "id": f"q_{i + 1}",+ "focus": f"Aspect {i + 1} of {requirement.get('knowledge_point', 'topic')}",+ "type": question_type,+ }+ )++ return {+ "knowledge_point": requirement.get("knowledge_point", ""),+ "difficulty": requirement.get("difficulty", "medium"),+ "question_type": requirement.get("question_type", "written"),+ "num_questions": num_questions,+ "focuses": focuses[:num_questions],+ }++ def _save_question_result(+ self,+ result: dict[str, Any],+ requirement: dict[str, Any],+ ) -> str | None:+ """Save a single question result to disk."""+ if not self.output_dir:+ return None++ try:+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ output_path = Path(self.output_dir) / f"question_{timestamp}"+ output_path.mkdir(parents=True, exist_ok=True)++ # Save result.json+ with open(output_path / "result.json", "w", encoding="utf-8") as f:+ json.dump(result, f, indent=2, ensure_ascii=False)++ # Save question.md+ question = result.get("question", {})+ validation = result.get("validation", {})++ md_content = f"""# Generated Question++**Knowledge point**: {requirement.get("knowledge_point", question.get("knowledge_point", "N/A"))}+**Difficulty**: {requirement.get("difficulty", "N/A")}+**Type**: {question.get("question_type", "N/A")}+**Relevance**: {validation.get("relevance", "N/A")}++---++## Question+{question.get("question", "")}++"""+ if question.get("options"):+ md_content += "## Options\n"+ for key, value in question.get("options", {}).items():+ md_content += f"- **{key}**: {value}\n"+ md_content += "\n"++ md_content += f"""+## Answer+{question.get("correct_answer", "")}++## Explanation+{question.get("explanation", "")}++---++## Relevance Analysis++**KB Coverage**: {validation.get("kb_coverage", "")}+"""+ if validation.get("extension_points"):+ md_content += f"\n**Extension Points**: {validation.get('extension_points', '')}"++ with open(output_path / "question.md", "w", encoding="utf-8") as f:+ f.write(md_content)++ self.logger.info(f"Result saved to: {output_path}")+ return str(output_path)++ except Exception as e:+ self.logger.warning(f"Failed to save result: {e}")+ return None++ def _save_knowledge_json(+ self,+ batch_dir: Path,+ retrieval_result: dict[str, Any],+ ):+ """Save knowledge.json for a batch."""+ knowledge_file = batch_dir / "knowledge.json"+ with open(knowledge_file, "w", encoding="utf-8") as f:+ json.dump(+ {+ "queries": retrieval_result.get("queries", []),+ "retrievals": retrieval_result.get("retrievals", []),+ },+ f,+ indent=2,+ ensure_ascii=False,+ )++ def _save_plan_json(self, batch_dir: Path, plan: dict[str, Any]):+ """Save plan.json for a batch."""+ plan_file = batch_dir / "plan.json"+ with open(plan_file, "w", encoding="utf-8") as f:+ json.dump(plan, f, indent=2, ensure_ascii=False)++ def _save_custom_question_result(+ self,+ batch_dir: Path,+ result: dict[str, Any],+ ):+ """Save a single question result in custom mode."""+ question_id = result.get("question_id", "q_unknown")+ question_dir = batch_dir / question_id+ question_dir.mkdir(parents=True, exist_ok=True)++ # Save result.json+ with open(question_dir / "result.json", "w", encoding="utf-8") as f:+ json.dump(result, f, indent=2, ensure_ascii=False)++ # Save question.md+ question = result.get("question", {})+ analysis = result.get("analysis", {})+ focus = result.get("focus", {})++ md_content = f"""# Generated Question++**Focus**: {focus.get("focus", "N/A")}+**Type**: {question.get("question_type", "N/A")}+**Relevance**: {analysis.get("relevance", "N/A")}++---++## Question+{question.get("question", "")}++"""+ if question.get("options"):+ md_content += "## Options\n"+ for key, value in question.get("options", {}).items():+ md_content += f"- **{key}**: {value}\n"+ md_content += "\n"++ md_content += f"""+## Answer+{question.get("correct_answer", "")}++## Explanation+{question.get("explanation", "")}++---++## Relevance Analysis++**KB Coverage**: {analysis.get("kb_coverage", "")}+"""+ if analysis.get("extension_points"):+ md_content += f"\n**Extension Points**: {analysis.get('extension_points', '')}"++ with open(question_dir / "question.md", "w", encoding="utf-8") as f:+ f.write(md_content)diff --git a/src/agents/question/prompts/en/generate_agent.yaml b/src/agents/question/prompts/en/generate_agent.yamlnew file mode 100644index 000000000..b6a6482ad--- /dev/null+++ b/src/agents/question/prompts/en/generate_agent.yaml@@ -0,0 +1,78 @@+system: |+ You are a professional Question Generation Agent. Your responsibilities are:+ 1. Generate high-quality questions based on requirements+ 2. Use retrieved background knowledge to ensure accuracy+ 3. Express knowledge in the same way as the knowledge base++ Important notes:+ - Questions must be rigorous and accurate, based on knowledge base content+ - Calculation problems should have substantial computation, not too simple+ - Use the provided background knowledge as the foundation for question generation+ - Multiple choice questions must have only one correct answer+ - Solutions/explanations should be detailed and clear+ - Chain-of-thought: reason internally step-by-step, but only output the final JSON++generate: |+ Generate a question based on the following information:++ Requirements:+ {requirements}++ Focus/Angle:+ {focus}++ Background Knowledge:+ {knowledge}++ Thinking instructions:+ - First, silently plan the scenario and reasoning steps to ensure the question is coherent.+ - Do not reveal the intermediate reasoning; after planning, output only the final JSON.++ CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.+ Your response must start with {{ and end with }}.++ Please generate a question in JSON format:+ {{+ "question_type": "choice" or "written",+ "question": "question content",+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // only for multiple choice+ "correct_answer": "correct answer",+ "explanation": "detailed explanation"+ }}++generate_with_reference: |+ Generate a new question that draws inspiration from the following reference but is clearly distinct in scenario and reasoning:++ Reference question:+ {reference_question}++ Requirements:+ {requirements}++ Background Knowledge:+ {knowledge}++ Requirements:+ 1. **Maintain same core knowledge and difficulty**: Concepts being tested must stay aligned+ 2. **Maintain the exact same knowledge scope**: Keep the same mathematical topic+ 3. **Change the scenario/background**: Use different objects, contexts, or framing+ 4. **Change the calculation process**: Rearrange steps or add sub-questions+ 5. **Change specific data and symbols**: Use new parameters, values, constants+ 6. **Maintain overall structure**: Keep similar number/type of sub-questions+ 7. **Forbidden**:+ - Only modifying numerical values or variable names+ - Repeating the same statement with an added explanation+ - Copying the same setup without new twists++ CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.+ Your response must start with {{ and end with }}.++ Please generate question in JSON format:+ {{+ "question_type": "choice" or "written",+ "question": "question content",+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // only for multiple choice+ "correct_answer": "correct answer",+ "explanation": "detailed explanation"+ }}+diff --git a/src/agents/question/prompts/en/generation_agent.yaml b/src/agents/question/prompts/en/generation_agent.yamldeleted file mode 100644index 0356bc9e0..000000000--- a/src/agents/question/prompts/en/generation_agent.yaml+++ /dev/null@@ -1,110 +0,0 @@-system: |- You are a professional Question Generation Agent. Your responsibilities are:- 1. Generate high-quality questions based on requirements- 2. Use retrieved background knowledge to ensure accuracy- 3. Express knowledge in the same way as the knowledge base-- **Workflow**:- 1. Understand question requirements (knowledge point, difficulty, question type, etc.)- 2. Use the provided background knowledge to generate the question- 3. Ensure the question is rigorous and accurate- 4. Submit question for relevance analysis-- **Important notes**:- - Questions must be rigorous and accurate, based on knowledge base content- - Calculation problems should have substantial computation, not too simple- - Use the provided background knowledge as the foundation for question generation- - Multiple choice questions must have only one correct answer- - Solutions/explanations should be detailed and clear, using the same narrative style as knowledge base- - **Chain-of-thought discipline**:- - Always reason internally in a deliberate, step-by-step manner. First outline the new scenario, then plan how the solution should proceed, and finally produce the answer.- - Do not expose chain-of-thought text in the final JSON; keep the reasoning internal and ensure the final output is coherent and precise.--generate: |- Generate a question based on the following information:-- Requirements:- {requirements}-- Retrieved knowledge:- {knowledge}-- Thinking instructions:- - First, silently plan the scenario and reasoning steps (chain-of-thought) to ensure the question is coherent.- - Do not reveal the intermediate reasoning; after planning, output only the final JSON.-- Please generate a question in JSON format:- {{- "question_type": "choice" or "written",- "question": "question content",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # only for multiple choice- "correct_answer": "correct answer",- "explanation": "detailed explanation"- }}--generate_with_reference: |- Generate a new question that draws inspiration from the following reference but is clearly distinct in scenario and reasoning:-- Reference question:- {reference_question}-- Requirements:- {requirements}-- Retrieved knowledge:- {knowledge}-- Requirements:- 1. **Maintain same core knowledge and difficulty**: Concepts being tested must stay aligned- 2. **Maintain the exact same knowledge scope**: Infer the primary mathematical concepts from the reference and keep them identical (e.g., if the reference focuses on planar line parametrization, remain within that topic; do NOT escalate to surfaces, directional derivatives, or unrelated advanced subjects).- 3. **Change the scenario/background**: Use different objects, coordinate systems, physical contexts, or story framing. Simply reusing the same geometric shape or statement with different numbers is forbidden.- 4. **Change the calculation process / add new reasoning steps**: Rearrange the solution steps, introduce an additional sub-question, or require an extra computation compared to the reference.- 5. **Change specific data and symbols**: Use new parameters, coordinate values, constants, etc.- 6. **Maintain overall structure**: Keep the number/type of sub-questions comparable (if the reference has multiple parts, yours can also have multiple parts, but they must not be identical).- 7. **Explicitly forbidden**:- - Only modifying numerical values or variable names- - Repeating the same statement with an added explanation- - Copying the same geometric/object setup without new twists- - Introducing higher-level or unrelated knowledge points that are absent from the reference-- Innovation examples:- - ✅ Good innovation: Change the geometric object (tetrahedron→pyramid with an apex not on axes), request an extra computation (e.g., find area + volume), use a different method (e.g., projection instead of simple dot product).- - ❌ Insufficient innovation: Same tetrahedron on coordinate axes with identical statement, even if an explanation is added. Adding extra commentary does NOT count as innovation.-- Thinking instructions:- - Deliberately plan the new scenario and reasoning steps step-by-step.- - Keep the chain-of-thought internal; only output the final JSON.-- Please generate question in JSON format:- {{- "question_type": "choice" or "written",- "question": "question content",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # only for multiple choice- "correct_answer": "correct answer",- "explanation": "detailed explanation"- }}--refine: |- Please modify the question based on validation feedback:-- Original question:- {original_question}-- Validation feedback:- {feedback}-- Retrieved knowledge:- {knowledge}-- Thinking instructions:- - Reflect on the validation feedback step-by-step, plan the adjustments mentally, then update the question.- - Keep the reasoning private; only output the final JSON.-- Please revise the question in JSON format:- {{- "question_type": "choice" or "written",- "question": "question content",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # only for multiple choice- "correct_answer": "correct answer",- "explanation": "detailed explanation"- }}diff --git a/src/agents/question/prompts/en/relevance_analyzer.yaml b/src/agents/question/prompts/en/relevance_analyzer.yamlnew file mode 100644index 000000000..adc69bca1--- /dev/null+++ b/src/agents/question/prompts/en/relevance_analyzer.yaml@@ -0,0 +1,42 @@+system: |+ You are an educational content analyst specializing in analyzing the relationship+ between exam questions and knowledge base content.++ Your task is to analyze the relevance between a question and the knowledge base,+ NOT to validate or reject the question. All questions are accepted.++analyze_relevance: |+ Analyze the relevance between the following exam question and the knowledge base content.++ Question:+ {question}++ Knowledge Base Content:+ {knowledge}++ Please analyze and provide a JSON response with the following structure:+ {{+ "relevance": "high" or "partial",+ "kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests. List the key knowledge points that are directly relevant.",+ "extension_points": "If relevance is 'partial', describe what aspects of this question extend beyond the knowledge base content. What additional knowledge does it require? Leave empty if relevance is 'high'."+ }}++ Guidelines for determining relevance:+ 1. "high" - The question can be fully answered using only the knowledge base content. All concepts, methods, and required knowledge are present in the KB.+ 2. "partial" - The question is related to the KB content but requires some knowledge beyond what's provided. The KB serves as a foundation but the question extends to additional areas.++ For kb_coverage:+ - Be specific about which concepts from the KB are being tested+ - Reference the actual content from the KB where possible+ - Explain how the KB content relates to the question++ For extension_points (only when relevance is "partial"):+ - Identify what additional knowledge is needed+ - Explain how the question extends from the KB foundation+ - Keep the tone positive - extensions are valuable for learning++ CRITICAL: Return ONLY valid JSON. Do not wrap in markdown code blocks.+ Your response must start with {{ and end with }}.++ Output only the JSON, no additional text.+diff --git a/src/agents/question/prompts/en/retrieve_agent.yaml b/src/agents/question/prompts/en/retrieve_agent.yamlnew file mode 100644index 000000000..4e72e6357--- /dev/null+++ b/src/agents/question/prompts/en/retrieve_agent.yaml@@ -0,0 +1,33 @@+system: |+ You are a knowledge base retrieval assistant, preparing for question generation.++ Your task is to generate knowledge point retrieval queries to find theoretical explanations,+ definitions, and theorems in the knowledge base.++ Key principle: You are NOT generating questions now! You are looking for theoretical knowledge+ needed for question generation.++generate_queries: |+ The user's question generation requirement is:+ {requirement_text}++ Please extract {num_queries} pure knowledge point names for knowledge base retrieval.++ Output Rules:+ 1. Only output pure knowledge point names (theorem names, concept names, method names)+ 2. Each query should be 2-5 words+ 3. Do not include functions, numerical values, or calculation tasks+ 4. Do not use questions or task descriptions++ Correct examples:+ ✓ Taylor theorem+ ✓ Lagrange multipliers+ ✓ critical points++ Incorrect examples (do not generate):+ ✗ Apply Taylor's Theorem to approximate f(x,y)=... (This is a question)+ ✗ Find and classify critical points (This is a task)+ ✗ Use Lagrange multipliers to find maximum (This is an instruction)++ Return in JSON format: {{"queries": ["knowledge point 1", "knowledge point 2", ...]}}, containing exactly {num_queries} knowledge point names.+diff --git a/src/agents/question/prompts/en/validation_agent.yaml b/src/agents/question/prompts/en/validation_agent.yamldeleted file mode 100644index a034a5ff8..000000000--- a/src/agents/question/prompts/en/validation_agent.yaml+++ /dev/null@@ -1,63 +0,0 @@-system: |- You are a professional question validation Agent. Your responsibilities are:- 1. Verify the rigor and correctness of questions- 2. Use the retrieve tool to search the knowledge base and independently verify answers- 3. Based on validation results, decide: approve, request modification, or request regeneration-- **Validation Criteria**:- 1. Is the question statement clear and unambiguous?- 2. Can the answer be derived from knowledge base content? (Be lenient - if core concepts are covered, it's acceptable)- 3. Do multiple-choice questions have only one correct answer?- 4. Is the explanation detailed and accurate?- 5. For questions involving calculations, is the answer correct?- 6. Does the explanation use the same narrative approach as the knowledge base?- 7. For knowledge points that are obviously below the knowledge base level, they may not need to appear in the knowledge base (e.g., basic arithmetic operations used in solving calculus problems)-- **Important Principles**:- - **Questions that extend beyond KB content are valuable** - they encourage broader learning- - **Be lenient with validation** - if the core concepts are related, accept the question- - **Cannot skip the validate step and directly approve**-- **Action Choices**:- - **Approve (approve_question)**: Use when validate result is approve- - **Modify (request_modification)**: Use when validate result is request_modification (for minor issues)- - **Regenerate (request_regeneration)**: Use ONLY when validate result is request_regeneration AND the content is completely irrelevant--validate: |- Please validate the following question:-- Question:- {question}-- Retrieved validation knowledge:- {validation_knowledge}-- Please perform validation and output in JSON format:- {{- "decision": "approve" or "request_modification" or "request_regeneration",- "issues": ["Issue 1", "Issue 2", ...], # List of discovered issues- "suggestions": ["Suggestion 1", "Suggestion 2", ...], # List of modification suggestions- "reasoning": "Detailed explanation of validation reasoning"- }}-- Validation Points:- 1. **Retrieval Result Sufficiency (Lenient Judgment)**:- - If the retrieved knowledge covers the core concepts of the question, it is sufficient- - Questions that extend beyond the KB content can still be valuable for learning- - Only request regeneration when the content is **completely irrelevant**- 2. Can the answer be derived from the retrieved knowledge? (Basic knowledge can be assumed)- 3. Do multiple-choice questions have only one correct answer?- 4. Is the question statement clear?- 5. Is the explanation sufficient?- 6. If there are calculations, are the results correct?-- **Validation Principles**:- - ✅ Be lenient: If core concepts are covered, the question should be accepted- - ✅ Questions extending beyond KB content are valuable - they show broader application- - ❌ **Only use request_regeneration for completely irrelevant content**- - ❌ Cannot use your own knowledge to validate; must rely on retrieved knowledge-- **Decision Guidelines**:- - "approve": Question is valid and well-aligned with knowledge base- - "request_modification": Minor issues that can be fixed with adjustments- - "request_regeneration": ONLY when content is completely irrelevant to the knowledge basediff --git a/src/agents/question/prompts/en/validation_workflow.yaml b/src/agents/question/prompts/en/validation_workflow.yamldeleted file mode 100644index 90c79c6a3..000000000--- a/src/agents/question/prompts/en/validation_workflow.yaml+++ /dev/null@@ -1,88 +0,0 @@-validate: |- Please validate the following question:-- Question:- {question}-- {reference_section}-- Retrieved validation knowledge:- {validation_knowledge}-- Please perform validation and output in JSON format:- {{- "decision": "approve" or "request_modification" or "request_regeneration",- "issues": ["issue1", "issue2", ...], # List of found issues- "suggestions": ["suggestion1", "suggestion2", ...], # List of modification suggestions- "reasoning": "Detailed explanation of validation reasoning"- }}-- Validation criteria:- 1. **Retrieved knowledge sufficiency (lenient judgment)**:- - ⚠️ **Important**: Knowledge base may not contain basic/low-level knowledge points, as students are assumed to have mastered them- - If question involves basic knowledge (e.g. vector dot product, magnitude, basic calculus formulas), but retrieved results are more advanced content, this is **acceptable**- - **Judgment criterion**: Is retrieved knowledge related to the question's **core knowledge points**? If question tests application of advanced concepts and you retrieved that advanced concept, it should be accepted even without basic formulas- - Only request regeneration when retrieved knowledge is **completely irrelevant** or **core knowledge points don't match**-- {innovation_section}-- 2. **Knowledge level judgment**:- - If retrieved knowledge is **higher level** than basic knowledge required by question, knowledge base assumes these basics are mastered- - Example: Question uses vector dot product, retrieved multivariable calculus content → **acceptable** (calculus courses assume students know vectors)- - Example: Question tests Lagrange multipliers, retrieved Lagrange multipliers → **acceptable** (even without basic partial derivative definition)-- 3. Can answer be derived from retrieved knowledge? (Consider basic knowledge may not be in knowledge base)- 4. Do multiple choice questions have only one correct answer?- 5. Is question statement clear?- 6. Is explanation sufficient?- 7. If calculation involved, is result correct?-- **Validation principles**:- - ✅ Be lenient with basic knowledge: If question uses basic knowledge but retrieved more advanced related content, should accept- - ✅ Focus on core knowledge points: As long as question's core points are reflected in retrieval results, knowledge is sufficient- - ✅ Questions that extend beyond KB content are valuable: They encourage broader learning- - ❌ Still need to validate based on retrieval results: Cannot use your own knowledge, but can reasonably infer basics are mastered- - ❌ Only request regeneration when completely irrelevant: Only require regeneration when retrieval results are **completely unrelated** to question's core content-- **Example judgments**:- - ✅ Accept: Question uses vector operations + retrieved linear algebra advanced content- - ✅ Accept: Question uses basic differentiation + retrieved multivariable calculus content- - ✅ Accept: Question uses trigonometric functions + retrieved complex analysis content- - ⚠️ Request modification (not regeneration): Question partially related but needs adjustment- - ❌ Request regeneration: Question tests Lagrange multipliers + retrieved probability theory content (completely irrelevant)--innovation_section: |- **Special check for mimicking questions**:- - **Innovation check**: Compare the generated question with the reference question- - ⚠️ **Insufficient innovation** - If only numbers/symbols changed while scenario, wording, structure, and solution process remain the same, or if the generator merely adds an explanation to the same statement, you MUST return request_modification or request_regeneration.- - Examples of insufficient innovation:- * Only changed coordinates from (1,2,3) to (4,5,6), everything else same- * Only changed parameter from k to m, calculation process identical- * Only swapped numerical values, question structure completely same- - ⚠️ Adding explanations or extra words without changing the scenario/requirements does NOT count as innovation.- - ✅ **Sufficient innovation** should include:- * Changed geometric objects or mathematical structures- * Changed calculation approach or solution method- * Changed question scenario or context- * Changed what is being solved for (e.g. from angle to projection)- - If innovation is insufficient, add to issues: "Insufficient innovation: only data changed, scenario and process identical to reference"--relevance_analysis: |- Analyze the relevance between the following exam question and the knowledge base content.-- Question:- {question}-- Knowledge Base Content:- {knowledge}-- Please analyze and provide a JSON response:- {{- "relevance": "high" or "partial",- "kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests.",- "extension_points": "If relevance is 'partial', describe what aspects extend beyond the knowledge base. Leave empty if 'high'."- }}-- Guidelines:- - "high": Question can be fully answered using only the knowledge base content- - "partial": Question is related but requires some knowledge beyond what's provideddiff --git a/src/agents/question/prompts/zh/generate_agent.yaml b/src/agents/question/prompts/zh/generate_agent.yamlnew file mode 100644index 000000000..435afb012--- /dev/null+++ b/src/agents/question/prompts/zh/generate_agent.yaml@@ -0,0 +1,78 @@+system: |+ 你是一个专业的题目生成 Agent。你的职责是:+ 1. 根据要求生成高质量的题目+ 2. 使用检索到的背景知识确保准确性+ 3. 用与知识库相同的方式表达知识++ 重要说明:+ - 题目必须严谨准确,基于知识库内容+ - 计算题应有实质性的计算,不能太简单+ - 使用提供的背景知识作为题目生成的基础+ - 选择题必须只有一个正确答案+ - 解答/解释应详细清晰+ - 思维链:内部逐步推理,但只输出最终的 JSON++generate: |+ 根据以下信息生成题目:++ 要求:+ {requirements}++ 焦点/角度:+ {focus}++ 背景知识:+ {knowledge}++ 思考说明:+ - 首先,默默地规划场景和推理步骤,确保题目连贯。+ - 不要透露中间推理;规划后只输出最终的 JSON。++ 关键:只返回有效的 JSON。不要用 markdown 代码块包装。+ 你的回复必须以 {{ 开始,以 }} 结束。++ 请以 JSON 格式生成题目:+ {{+ "question_type": "choice" 或 "written",+ "question": "题目内容",+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // 仅选择题需要+ "correct_answer": "正确答案",+ "explanation": "详细解释"+ }}++generate_with_reference: |+ 生成一道新题目,从以下参考题目获取灵感,但在场景和推理上明显不同:++ 参考题目:+ {reference_question}++ 要求:+ {requirements}++ 背景知识:+ {knowledge}++ 要求:+ 1. **保持相同的核心知识和难度**:测试的概念必须保持一致+ 2. **保持完全相同的知识范围**:保持相同的数学主题+ 3. **改变场景/背景**:使用不同的对象、情境或框架+ 4. **改变计算过程**:重新安排步骤或添加子问题+ 5. **改变具体数据和符号**:使用新的参数、值、常数+ 6. **保持整体结构**:保持相似数量/类型的子问题+ 7. **禁止**:+ - 只修改数值或变量名+ - 重复相同的陈述并添加解释+ - 复制相同的设置而没有新的变化++ 关键:只返回有效的 JSON。不要用 markdown 代码块包装。+ 你的回复必须以 {{ 开始,以 }} 结束。++ 请以 JSON 格式生成题目:+ {{+ "question_type": "choice" 或 "written",+ "question": "题目内容",+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} // 仅选择题需要+ "correct_answer": "正确答案",+ "explanation": "详细解释"+ }}+diff --git a/src/agents/question/prompts/zh/generation_agent.yaml b/src/agents/question/prompts/zh/generation_agent.yamldeleted file mode 100644index 904927b9e..000000000--- a/src/agents/question/prompts/zh/generation_agent.yaml+++ /dev/null@@ -1,110 +0,0 @@-system: |- 你是一个专业的题目生成Agent。你的职责是:- 1. 根据需求生成高质量的题目- 2. 使用检索到的背景知识确保准确性- 3. 以与知识库相同的方式表达知识-- **工作流程**:- 1. 理解题目需求(知识点、难度、题型等)- 2. 使用提供的背景知识生成题目- 3. 确保题目严谨准确- 4. 提交题目进行相关性分析-- **重要提示**:- - 题目必须严谨准确,基于知识库内容- - 计算题应有实质性的计算,不能太简单- - 使用提供的背景知识作为出题的基础- - 选择题必须只有一个正确答案- - 解答/解释应详细清晰,使用与知识库相同的叙述风格- - **思维链纪律**:- - 始终以深思熟虑、逐步的方式进行内部推理。首先概述新场景,然后规划解题步骤,最后产生答案。- - 不要在最终JSON中暴露思维链文本;保持内部推理,确保最终输出连贯准确。--generate: |- 根据以下信息生成一道题目:-- 需求:- {requirements}-- 检索到的知识:- {knowledge}-- 思考说明:- - 首先,默默规划场景和推理步骤(思维链),确保题目连贯。- - 不要透露中间推理过程;规划后,只输出最终的JSON。-- 请以JSON格式生成题目:- {{- "question_type": "choice" 或 "written",- "question": "题目内容",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # 仅选择题需要- "correct_answer": "正确答案",- "explanation": "详细解释"- }}--generate_with_reference: |- 生成一道受以下参考题启发但在场景和推理上明显不同的新题目:-- 参考题目:- {reference_question}-- 需求:- {requirements}-- 检索到的知识:- {knowledge}-- 要求:- 1. **保持相同的核心知识和难度**:被测试的概念必须保持一致- 2. **保持完全相同的知识范围**:从参考题推断主要数学概念并保持相同(例如,如果参考题关注平面直线参数化,就保持在该主题内;不要升级到曲面、方向导数或无关的高级主题)- 3. **改变场景/背景**:使用不同的对象、坐标系、物理背景或故事框架。禁止简单地重用相同的几何形状或陈述,只改变数字- 4. **改变计算过程/添加新的推理步骤**:重新安排解题步骤,引入额外的子问题,或要求比参考题多的计算- 5. **改变具体数据和符号**:使用新的参数、坐标值、常数等- 6. **保持整体结构**:保持子问题的数量/类型相当(如果参考题有多个部分,你的也可以有多个部分,但不能完全相同)- 7. **明确禁止**:- - 仅修改数值或变量名- - 重复相同的陈述只是添加解释- - 复制相同的几何/对象设置而没有新的变化- - 引入参考题中没有的更高级或无关的知识点-- 创新示例:- - ✅ 好的创新:改变几何对象(四面体→顶点不在坐标轴上的棱锥),要求额外的计算(如求面积+体积),使用不同的方法(如投影而非简单点积)- - ❌ 创新不足:坐标轴上相同的四面体,陈述相同,即使添加了解释。添加额外评论不算创新。-- 思考说明:- - 深思熟虑地逐步规划新场景和推理步骤。- - 保持思维链内部;只输出最终的JSON。-- 请以JSON格式生成题目:- {{- "question_type": "choice" 或 "written",- "question": "题目内容",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # 仅选择题需要- "correct_answer": "正确答案",- "explanation": "详细解释"- }}--refine: |- 请根据验证反馈修改题目:-- 原题目:- {original_question}-- 验证反馈:- {feedback}-- 检索到的知识:- {knowledge}-- 思考说明:- - 逐步反思验证反馈,在心里规划调整,然后更新题目。- - 保持推理私密;只输出最终的JSON。-- 请以JSON格式修改题目:- {{- "question_type": "choice" 或 "written",- "question": "题目内容",- "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}} # 仅选择题需要- "correct_answer": "正确答案",- "explanation": "详细解释"- }}diff --git a/src/agents/question/prompts/zh/relevance_analyzer.yaml b/src/agents/question/prompts/zh/relevance_analyzer.yamlnew file mode 100644index 000000000..93fa3395d--- /dev/null+++ b/src/agents/question/prompts/zh/relevance_analyzer.yaml@@ -0,0 +1,40 @@+system: |+ 你是一位教育内容分析师,专门分析考试题目与知识库内容之间的关系。++ 你的任务是分析题目与知识库的相关性,而不是验证或拒绝题目。所有题目都被接受。++analyze_relevance: |+ 分析以下考试题目与知识库内容之间的相关性。++ 题目:+ {question}++ 知识库内容:+ {knowledge}++ 请分析并提供以下结构的 JSON 响应:+ {{+ "relevance": "high" 或 "partial",+ "kb_coverage": "具体描述这道题目测试了知识库中的哪些概念、理论或方法。列出直接相关的关键知识点。",+ "extension_points": "如果相关性是 'partial',描述这道题目的哪些方面超出了知识库内容。它需要什么额外的知识?如果相关性是 'high' 则留空。"+ }}++ 判断相关性的指南:+ 1. "high" - 题目可以完全使用知识库内容来回答。所有概念、方法和所需知识都在知识库中。+ 2. "partial" - 题目与知识库内容相关,但需要一些超出提供内容的知识。知识库作为基础,但题目扩展到了额外的领域。++ 对于 kb_coverage:+ - 具体说明正在测试知识库中的哪些概念+ - 尽可能参考知识库中的实际内容+ - 解释知识库内容与题目的关系++ 对于 extension_points(仅当相关性为 "partial" 时):+ - 确定需要什么额外知识+ - 解释题目如何从知识库基础扩展+ - 保持积极的语气 - 扩展对学习有价值++ 关键:只返回有效的 JSON。不要用 markdown 代码块包装。+ 你的回复必须以 {{ 开始,以 }} 结束。++ 只输出 JSON,不要有其他文字。+diff --git a/src/agents/question/prompts/zh/retrieve_agent.yaml b/src/agents/question/prompts/zh/retrieve_agent.yamlnew file mode 100644index 000000000..adbce15b5--- /dev/null+++ b/src/agents/question/prompts/zh/retrieve_agent.yaml@@ -0,0 +1,31 @@+system: |+ 你是一个知识库检索助手,正在为题目生成做准备。++ 你的任务是生成知识点检索查询,以在知识库中找到理论解释、定义和定理。++ 关键原则:你现在不是在生成题目!你是在寻找题目生成所需的理论知识。++generate_queries: |+ 用户的题目生成需求是:+ {requirement_text}++ 请提取 {num_queries} 个纯粹的知识点名称用于知识库检索。++ 输出规则:+ 1. 只输出纯粹的知识点名称(定理名、概念名、方法名)+ 2. 每个查询应为2-5个词+ 3. 不要包含函数、数值或计算任务+ 4. 不要使用问句或任务描述++ 正确示例:+ ✓ 泰勒定理+ ✓ 拉格朗日乘数法+ ✓ 临界点++ 错误示例(不要生成):+ ✗ 应用泰勒定理近似 f(x,y)=... (这是一个题目)+ ✗ 找出并分类临界点 (这是一个任务)+ ✗ 使用拉格朗日乘数法求最大值 (这是一个指令)++ 以 JSON 格式返回:{{"queries": ["知识点1", "知识点2", ...]}}, 包含恰好 {num_queries} 个知识点名称。+diff --git a/src/agents/question/prompts/zh/validation_agent.yaml b/src/agents/question/prompts/zh/validation_agent.yamldeleted file mode 100644index 41b93b9c6..000000000--- a/src/agents/question/prompts/zh/validation_agent.yaml+++ /dev/null@@ -1,63 +0,0 @@-system: |- 你是一个专业的题目验证Agent。你的职责是:- 1. 验证题目的严谨性和正确性- 2. 使用retrieve工具搜索知识库,独立验证答案- 3. 根据验证结果决定:通过、请求修改或请求重新生成-- **验证标准**:- 1. 题目表述是否清晰无歧义?- 2. 答案是否能从知识库内容推导?(宽松判断 - 如果核心概念相关,可以接受)- 3. 选择题是否只有一个正确答案?- 4. 解释是否详细准确?- 5. 对于涉及计算的题目,答案是否正确?- 6. 解释是否使用与知识库相同的叙述方式?- 7. 对于明显低于知识库水平的知识点,它们可能不需要出现在知识库中(例如,解微积分问题时使用的基本算术运算)-- **重要原则**:- - **拓展知识库内容的题目是有价值的** - 它们鼓励更广泛的学习- - **验证时要宽松** - 如果核心概念相关,应接受题目- - **不能跳过validate步骤直接通过**-- **行动选择**:- - **通过 (approve_question)**:当validate结果是approve时使用- - **修改 (request_modification)**:当validate结果是request_modification时使用(针对小问题)- - **重新生成 (request_regeneration)**:仅当validate结果是request_regeneration且内容完全不相关时使用--validate: |- 请验证以下题目:-- 题目:- {question}-- 检索到的验证知识:- {validation_knowledge}-- 请进行验证并以JSON格式输出:- {{- "decision": "approve" 或 "request_modification" 或 "request_regeneration",- "issues": ["问题1", "问题2", ...], # 发现的问题列表- "suggestions": ["建议1", "建议2", ...], # 修改建议列表- "reasoning": "验证推理的详细说明"- }}-- 验证要点:- 1. **检索结果充分性(宽松判断)**:- - 如果检索到的知识涵盖了题目的核心概念,就是充分的- - 拓展知识库内容的题目对学习仍有价值- - 只有当内容**完全不相关**时才请求重新生成- 2. 答案能否从检索到的知识推导?(可以假设基础知识已掌握)- 3. 选择题是否只有一个正确答案?- 4. 题目表述是否清晰?- 5. 解释是否充分?- 6. 如果有计算,结果是否正确?-- **验证原则**:- - ✅ 宽松判断:如果核心概念相关,题目应被接受- - ✅ 拓展知识库内容的题目是有价值的 - 它们展示了更广泛的应用- - ❌ **只在内容完全不相关时使用request_regeneration**- - ❌ 不能使用自己的知识验证;必须依赖检索到的知识-- **决策指南**:- - "approve":题目有效且与知识库对齐良好- - "request_modification":有小问题可以通过调整修复- - "request_regeneration":仅当内容与知识库完全不相关时diff --git a/src/agents/question/prompts/zh/validation_workflow.yaml b/src/agents/question/prompts/zh/validation_workflow.yamldeleted file mode 100644index ef8296081..000000000--- a/src/agents/question/prompts/zh/validation_workflow.yaml+++ /dev/null@@ -1,88 +0,0 @@-validate: |- 请验证以下题目:-- 题目:- {question}-- {reference_section}-- 检索到的验证知识:- {validation_knowledge}-- 请进行验证并以JSON格式输出:- {{- "decision": "approve" 或 "request_modification" 或 "request_regeneration",- "issues": ["问题1", "问题2", ...], # 发现的问题列表- "suggestions": ["建议1", "建议2", ...], # 修改建议列表- "reasoning": "验证推理的详细说明"- }}-- 验证标准:- 1. **检索知识充分性(宽松判断)**:- - ⚠️ **重要**:知识库可能不包含基础/低级知识点,因为假设学生已经掌握- - 如果题目涉及基础知识(如向量点积、模、基本微积分公式),但检索结果是更高级的内容,这是**可以接受的**- - **判断标准**:检索到的知识是否与题目的**核心知识点**相关?如果题目测试高级概念的应用,且你检索到了该高级概念,即使没有基础公式也应该接受- - 只有当检索知识**完全不相关**或**核心知识点不匹配**时才返回"request_regeneration"-- {innovation_section}-- 2. **知识层次判断**:- - 如果检索到的知识**高于**题目所需的基础知识,知识库假设这些基础已经掌握- - 例如:题目使用向量点积,检索到多元微积分内容 → **可接受**(微积分课程假设学生了解向量)- - 例如:题目测试拉格朗日乘数法,检索到拉格朗日乘数法 → **可接受**(即使没有偏导数的基本定义)-- 3. 答案能否从检索知识推导?(考虑基础知识可能不在知识库中)- 4. 选择题是否只有一个正确答案?- 5. 题目表述是否清晰?- 6. 解释是否充分?- 7. 如果涉及计算,结果是否正确?-- **验证原则**:- - ✅ 对基础知识宽容:如果题目使用基础知识但检索到更高级的相关内容,应该接受- - ✅ 关注核心知识点:只要题目的核心知识点在检索结果中有所体现,知识就是充分的- - ✅ 拓展知识库内容的题目是有价值的:它们鼓励更广泛的学习- - ❌ 仍需基于检索结果验证:不能使用你自己的知识,但可以合理推断基础已被掌握- - ❌ 只在完全不相关时要求重新生成:只有当检索结果与题目核心内容**完全无关**时才要求重新生成-- **判断示例**:- - ✅ 接受:题目使用向量运算 + 检索到线性代数高级内容- - ✅ 接受:题目使用基本微分 + 检索到多元微积分内容- - ✅ 接受:题目使用三角函数 + 检索到复分析内容- - ⚠️ 请求修改(非重新生成):题目部分相关但需要调整- - ❌ 请求重新生成:题目测试拉格朗日乘数法 + 检索到概率论内容(完全不相关)--innovation_section: |- **仿题特别检查**:- - **创新检查**:比较生成的题目与参考题目- - ⚠️ **创新不足** - 如果仅改变数字/符号而场景、措辞、结构和解题过程保持不变,或者生成者仅对相同陈述添加解释,你必须返回request_modification或request_regeneration。- - 创新不足的示例:- * 只改变坐标从(1,2,3)到(4,5,6),其他完全相同- * 只改变参数从k到m,计算过程完全相同- * 只交换数值,题目结构完全相同- - ⚠️ 仅添加解释或额外文字而不改变场景/要求不算创新。- - ✅ **充分创新**应包括:- * 改变几何对象或数学结构- * 改变计算方法或解题方法- * 改变题目场景或背景- * 改变求解目标(如从夹角到投影)- - 如果创新不足,添加到issues:"创新不足:仅改变数据,场景和过程与参考题相同"--relevance_analysis: |- 分析以下考试题目与知识库内容之间的相关性。-- 题目:- {question}-- 知识库内容:- {knowledge}-- 请分析并以JSON格式输出:- {{- "relevance": "high" 或 "partial",- "kb_coverage": "具体描述这道题目考查了知识库中的哪些概念、理论或方法。",- "extension_points": "如果相关性为'partial',描述哪些方面延展了知识库的内容。如果为'high'则留空。"- }}-- 判断标准:- - "high":题目可以完全使用知识库内容来回答- - "partial":题目与知识库相关,但需要一些知识库之外的知识diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.pydeleted file mode 100644index bf727e5e2..000000000--- a/src/agents/question/validation_workflow.py+++ /dev/null@@ -1,613 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Question Validation Workflow: retrieve -> validate -> return.--Uses unified LLM Factory for all LLM calls, supporting:-- Cloud providers (OpenAI, Anthropic, DeepSeek, etc.)-- Local providers (Ollama, LM Studio, vLLM, etc.)-- Automatic retry with exponential backoff-"""--from collections.abc import Callable-import json-import os-from pathlib import Path-import sys-from typing import Any--# Add project root to path-project_root = Path(__file__).parent.parent.parent.parent-sys.path.insert(0, str(project_root))--from src.logging import get_logger-from src.services.config import get_agent_params, load_config_with_main-from src.services.llm import complete as llm_complete-from src.services.llm.capabilities import supports_response_format-from src.services.llm.config import get_llm_config-from src.services.prompt import get_prompt_manager-from src.tools.rag_tool import rag_search--# Module logger-logger = get_logger("QuestionValidation")---class QuestionValidationWorkflow:- """Question validation workflow - fixed pipeline"""-- def __init__(- self,- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- model: str | None = None,- kb_name: str | None = None,- token_stats_callback: Callable | None = None,- language: str = "en",- ):- """- Initialize validation workflow.-- Args:- api_key: API key- base_url: API endpoint- api_version: API version (for Azure OpenAI)- model: Model name- kb_name: Knowledge base name- token_stats_callback: Callback function to update token statistics- language: Language for prompts ("en" or "zh")- """- # Load LLM configuration via unified config system- try:- llm_config = get_llm_config()- self.api_key = api_key or llm_config.api_key- self.base_url = base_url or llm_config.base_url- self.api_version = api_version or llm_config.api_version- self.binding = llm_config.binding or "openai"- self.model = model or llm_config.model- except Exception:- # Fallback to environment variables- self.api_key = api_key or os.getenv("LLM_API_KEY")- self.base_url = base_url or os.getenv("LLM_HOST")- self.api_version = api_version or os.getenv("LLM_API_VERSION")- self.binding = os.getenv("LLM_BINDING", "openai")- self.model = model or os.getenv("LLM_MODEL")-- 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."- )-- self.kb_name = kb_name- self.token_stats_callback = token_stats_callback- self.language = language-- # Load prompts using unified PromptManager- self._prompts = get_prompt_manager().load_prompts(- module_name="question",- agent_name="validation_workflow",- language=language,- )-- # Get agent parameters from unified config- self._agent_params = get_agent_params("question")-- # Load config for RAG settings- self._config = load_config_with_main("question_config.yaml", project_root)-- async def validate(- self, question: dict[str, Any], reference_question: str | None = None- ) -> dict[str, Any]:- """- Validate question - fixed pipeline: retrieve → validate → return-- Args:- question: Question content- {- "question_type": str,- "question": str,- "options": Dict (for multiple choice),- "correct_answer": str,- "explanation": str,- "knowledge_point": str (optional)- }-- Returns:- Dict: Validation result- {- "decision": "approve" | "request_modification" | "request_regeneration",- "issues": List[str],- "suggestions": List[str],- "reasoning": str,- "retrieved_knowledge": List[Dict]- }- """- logger.info("Starting question validation")-- # Step 1: Retrieve related knowledge- logger.info("Step 1/2: Retrieving validation knowledge")- retrieved_knowledge = await self._retrieve_knowledge(question)- logger.debug(f"Retrieved {len(retrieved_knowledge)} knowledge items")-- # Step 2: Validate question- logger.info("Step 2/2: Validating question")- validation_result = await self._validate_question(- question, retrieved_knowledge, reference_question- )- logger.info(f"Validation decision: {validation_result['decision']}")-- # Add retrieved knowledge to result- validation_result["retrieved_knowledge"] = retrieved_knowledge-- logger.success("Validation completed")-- return validation_result-- async def _generate_retrieval_query(self, question: dict[str, Any]) -> str:- """Use LLM to generate retrieval query"""- knowledge_point = question.get("knowledge_point", "")- question_text = question.get("question", "")- options = question.get("options", {})- correct_answer = question.get("correct_answer", "")-- system_prompt = "You are a professional knowledge retrieval expert."-- prompt = f"""Analyze the following question and generate a concise retrieval query to retrieve relevant knowledge from the knowledge base to validate this question.--Question information:-- Knowledge point: {knowledge_point}-- Question: {question_text}-"""-- if options:- prompt += f"- Options: {json.dumps(options, ensure_ascii=False)}\n"- if correct_answer:- prompt += f"- Answer: {correct_answer}\n"-- prompt += """-Please extract the **core knowledge points and concepts** involved in the question and generate a concise retrieval query (no more than 100 words).--Requirements:-1. Extract core mathematical/physical concepts, theorems, methods from the question-2. If specific formulas or algorithms exist, extract key terminology-3. Do not include specific numerical values and details from the question-4. Query should be able to retrieve theoretical knowledge needed to validate the question--Output the retrieval query directly, no additional content.-"""-- # Call LLM via unified Factory (supports all providers with retry)- response_content = await llm_complete(- prompt=prompt,- system_prompt=system_prompt,- model=self.model,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- binding=self.binding,- temperature=0.3,- )-- 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 available- if self.token_stats_callback:- self.token_stats_callback(- input_tokens=input_tokens_est, output_tokens=output_tokens_est, model=self.model- )-- # Log LLM call with detailed information- logger.log_llm_call(- model=self.model,- stage="generate_query",- system_prompt=system_prompt,- user_prompt=prompt,- response=response_content,- agent_name="QuestionValidationWorkflow",- input_tokens=input_tokens_est,- output_tokens=output_tokens_est,- cost=0.0, # Cost estimation would require pricing info- level="DEBUG",- )-- return response_content-- async def _retrieve_knowledge(self, question: dict[str, Any]) -> list[dict[str, Any]]:- """Retrieve knowledge needed for validation."""- # Use LLM to generate retrieval query- query = await self._generate_retrieval_query(question)-- logger.debug(f"LLM generated query: {query[:100]}...")-- # Get RAG mode from config- question_cfg = self._config.get("question", {})- rag_mode = question_cfg.get("rag_mode", "hybrid")-- # Execute retrieval using unified RAG tool- try:- result = await rag_search(- query=query,- kb_name=self.kb_name,- mode=rag_mode,- only_need_context=True,- )-- # Return retrieval results with raw answer- retrieved = []- if result and result.get("answer"):- retrieved.append(- {- "query": query,- "answer": result.get("answer", ""),- }- )-- return retrieved-- except Exception as e:- logger.warning(f"Retrieval failed: {e!s}")- return []-- async def _validate_question(- self,- question: dict[str, Any],- retrieved_knowledge: list[dict[str, Any]],- reference_question: str = None,- ) -> dict[str, Any]:- """Validate question"""- knowledge_str = self._format_knowledge(retrieved_knowledge)-- question_str = json.dumps(question, ensure_ascii=False, indent=2)-- reference_section = ""- innovation_section = ""- if reference_question:- reference_section = f"""Reference question (for comparison):-{reference_question}-"""- innovation_section = self._prompts.get("innovation_section", "")-- prompt_template = self._prompts.get("validate", "")- prompt = prompt_template.format(- question=question_str,- reference_section=reference_section,- innovation_section=innovation_section,- validation_knowledge=knowledge_str,- )-- system_prompt = "You are a professional question validation expert who strictly validates questions based on knowledge base content."-- try:- # Build kwargs for LLM Factory- llm_kwargs = {- "temperature": self._agent_params["temperature"],- "max_tokens": self._agent_params["max_tokens"],- }-- # Only add response_format if the provider supports it- if supports_response_format(self.binding, self.model):- llm_kwargs["response_format"] = {"type": "json_object"}-- # Call LLM via unified Factory (supports all providers with retry)- response_content = await llm_complete(- prompt=prompt,- system_prompt=system_prompt,- model=self.model,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- binding=self.binding,- **llm_kwargs,- )-- # Update token statistics if callback is available- if self.token_stats_callback:- # Rough estimation: ~4 chars per token- input_tokens = (len(system_prompt) + len(prompt)) // 4- output_tokens = len(response_content) // 4- self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model- )-- # Log LLM call with detailed information- logger.log_llm_call(- model=self.model,- stage="validate",- system_prompt=system_prompt,- user_prompt=prompt,- response=response_content,- agent_name="QuestionValidationWorkflow",- input_tokens=0,- output_tokens=0,- cost=0.0,- level="DEBUG",- )-- result = json.loads(response_content)-- # Ensure issues and suggestions are lists (handle case where LLM returns dict)- issues = result.get("issues", [])- if not isinstance(issues, list):- if isinstance(issues, dict):- # If issues is a dict, convert to list- issues = [issues]- else:- issues = []-- suggestions = result.get("suggestions", [])- if not isinstance(suggestions, list):- if isinstance(suggestions, dict):- # If suggestions is a dict, convert to list- suggestions = [suggestions]- else:- suggestions = []-- return {- "decision": result.get("decision", "request_regeneration"),- "issues": issues,- "suggestions": suggestions,- "reasoning": result.get("reasoning", ""),- }-- except Exception as e:- logger.warning(f"Validation failed: {e!s}")- return {- "decision": "request_regeneration",- "issues": [f"Validation error: {e!s}"],- "suggestions": ["Please regenerate the question"],- "reasoning": "An error occurred during validation",- }-- def _format_knowledge(self, retrieved_knowledge: list[dict[str, Any]]) -> str:- """Format retrieved knowledge."""- if not retrieved_knowledge:- return "No validation knowledge retrieved"-- knowledge_parts = []- for k in retrieved_knowledge:- knowledge_parts.append(f"=== Query: {k['query']} ===")- answer = k.get("answer", "")- if answer:- # Truncate very long answers- if len(answer) > 3000:- answer = answer[:3000] + "...[truncated]"- knowledge_parts.append(answer)- knowledge_parts.append("")-- return (- "\n".join(knowledge_parts) if knowledge_parts else "No validation knowledge retrieved"- )-- async def analyze_extension(- self, question: dict[str, Any], shared_context: str- ) -> dict[str, Any]:- """- Analyze how a question extends beyond the knowledge base.-- This is called when a question doesn't pass validation after max rounds,- to provide insights about how it relates to and extends from the KB.-- Args:- question: The question that wasn't fully validated- shared_context: The shared knowledge context from RAG-- Returns:- Dict with:- - kb_connection: How the question relates to the knowledge base- - extended_aspect: What knowledge areas the question extends to- - reasoning: Detailed explanation- """- logger.info("Analyzing question extension from knowledge base")-- question_str = json.dumps(question, ensure_ascii=False, indent=2)-- # Truncate context if too long- context_str = shared_context- if len(context_str) > 4000:- context_str = context_str[:4000] + "...[truncated]"-- system_prompt = "You are an educational content analyst specializing in identifying knowledge connections and learning extensions."-- prompt = f"""Analyze how the following question relates to and extends from the knowledge base content.--Question:-{question_str}--Knowledge Base Content:-{context_str}--Please analyze from the perspective of knowledge extension and provide a JSON response:-{{- "kb_connection": "Describe how this question connects to the knowledge base content. What concepts, theories, or methods from the KB are relevant to this question?",- "extended_aspect": "Describe what knowledge areas this question extends to beyond the core KB content. What additional concepts, applications, or perspectives does it explore?",- "reasoning": "Provide a detailed explanation of the relationship between this question and the knowledge base, and why this extension is valuable for learning."-}}--Guidelines:-1. Focus on the POSITIVE aspects - this is an "extended" question that goes beyond basic KB content-2. kb_connection should identify the foundation concepts from the KB that the question builds upon-3. extended_aspect should highlight what new learning opportunities this question provides-4. Keep the analysis constructive and educational--Output only the JSON, no additional text."""-- try:- # Build kwargs for LLM Factory- llm_kwargs = {"temperature": 0.3}-- # Only add response_format if the provider supports it- if supports_response_format(self.binding, self.model):- llm_kwargs["response_format"] = {"type": "json_object"}-- # Call LLM via unified Factory (supports all providers with retry)- response_content = await llm_complete(- prompt=prompt,- system_prompt=system_prompt,- model=self.model,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- binding=self.binding,- **llm_kwargs,- )-- # Update token statistics- if self.token_stats_callback:- input_tokens = (len(system_prompt) + len(prompt)) // 4- output_tokens = len(response_content) // 4- self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model- )-- result = json.loads(response_content)-- logger.info("Extension analysis completed")-- return {- "kb_connection": result.get("kb_connection", ""),- "extended_aspect": result.get("extended_aspect", ""),- "reasoning": result.get("reasoning", ""),- }-- except Exception as e:- logger.warning(f"Extension analysis failed: {e!s}")- return {- "kb_connection": "Unable to analyze connection to knowledge base",- "extended_aspect": "This question explores areas beyond the core knowledge base content",- "reasoning": f"Analysis could not be completed: {e!s}",- }-- async def analyze_relevance(- self,- question: dict[str, Any],- knowledge_summary: str,- ) -> dict[str, Any]:- """- Analyze the relevance between a question and the knowledge base content.-- This is used in custom mode where we don't iterate - we just analyze- how the question relates to the knowledge base.-- Args:- question: The generated question dict- knowledge_summary: Summary of background knowledge from RAG-- Returns:- Dict with:- - relevance: "high" or "partial"- - kb_coverage: Description of what KB content the question tests- - extension_points: Description of any extensions (only if partial)- """- logger.info("Analyzing question relevance to knowledge base")-- question_str = json.dumps(question, ensure_ascii=False, indent=2)-- # Truncate context if too long- context_str = knowledge_summary- if len(context_str) > 4000:- context_str = context_str[:4000] + "...[truncated]"-- system_prompt = "You are an educational content analyst specializing in analyzing the relationship between exam questions and knowledge base content."-- prompt = f"""Analyze the relevance between the following exam question and the knowledge base content.--Question:-{question_str}--Knowledge Base Content:-{context_str}--Please analyze and provide a JSON response with the following structure:-{{- "relevance": "high" or "partial",- "kb_coverage": "Describe specifically what concepts, theories, or methods from the knowledge base this question tests. List the key knowledge points that are directly relevant.",- "extension_points": "If relevance is 'partial', describe what aspects of this question extend beyond the knowledge base content. What additional knowledge does it require? Leave empty if relevance is 'high'."-}}--Guidelines for determining relevance:-1. "high" - The question can be fully answered using only the knowledge base content. All concepts, methods, and required knowledge are present in the KB.-2. "partial" - The question is related to the KB content but requires some knowledge beyond what's provided. The KB serves as a foundation but the question extends to additional areas.--For kb_coverage:-- Be specific about which concepts from the KB are being tested-- Reference the actual content from the KB where possible-- Explain how the KB content relates to the question--For extension_points (only when relevance is "partial"):-- Identify what additional knowledge is needed-- Explain how the question extends from the KB foundation-- Keep the tone positive - extensions are valuable for learning--Output only the JSON, no additional text."""-- try:- # Build kwargs for LLM Factory- llm_kwargs = {"temperature": 0.3}-- # Only add response_format if the provider supports it- if supports_response_format(self.binding, self.model):- llm_kwargs["response_format"] = {"type": "json_object"}-- # Call LLM via unified Factory (supports all providers with retry)- response_content = await llm_complete(- prompt=prompt,- system_prompt=system_prompt,- model=self.model,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- binding=self.binding,- **llm_kwargs,- )-- # Update token statistics- if self.token_stats_callback:- input_tokens = (len(system_prompt) + len(prompt)) // 4- output_tokens = len(response_content) // 4- self.token_stats_callback(- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model- )-- # Log LLM call- logger.log_llm_call(- model=self.model,- stage="analyze_relevance",- system_prompt=system_prompt,- user_prompt=prompt,- response=response_content,- agent_name="QuestionValidationWorkflow",- input_tokens=0,- output_tokens=0,- cost=0.0,- level="DEBUG",- )-- result = json.loads(response_content)-- relevance = result.get("relevance", "partial")- if relevance not in ["high", "partial"]:- relevance = "partial"-- logger.info(f"Relevance analysis completed: {relevance}")-- return {- "relevance": relevance,- "kb_coverage": result.get("kb_coverage", ""),- "extension_points": result.get("extension_points", "")- if relevance == "partial"- else "",- }-- except Exception as e:- logger.warning(f"Relevance analysis failed: {e!s}")- return {- "relevance": "partial",- "kb_coverage": "Unable to analyze knowledge base coverage",- "extension_points": f"Analysis could not be completed: {e!s}",- }diff --git a/src/api/main.py b/src/api/main.pyindex e6c3e1f06..cf864fca0 100644--- a/src/api/main.py+++ b/src/api/main.py@@ -9,12 +9,11 @@ from src.api.routers import (agent_config,chat,co_writer,+ config,dashboard,- embedding_provider,guide,ideagen,knowledge,- llm_provider,notebook,question,research,@@ -179,9 +178,8 @@ app.include_router(guide.router, prefix="/api/v1/guide", tags=["guide"])app.include_router(ideagen.router, prefix="/api/v1/ideagen", tags=["ideagen"])app.include_router(settings.router, prefix="/api/v1/settings", tags=["settings"])app.include_router(system.router, prefix="/api/v1/system", tags=["system"])-app.include_router(llm_provider.router, prefix="/api/v1/config/llm", tags=["config"])-app.include_router(embedding_provider.router, prefix="/api/v1/config/embedding", tags=["config"])-app.include_router(agent_config.router, prefix="/api/v1/config", tags=["config"])+app.include_router(config.router, prefix="/api/v1/config", tags=["config"])+app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"])@app.get("/")diff --git a/src/api/routers/config.py b/src/api/routers/config.pynew file mode 100644index 000000000..76589441a--- /dev/null+++ b/src/api/routers/config.py@@ -0,0 +1,601 @@+"""+Unified Configuration API Router+=================================++Provides REST API for managing configurations for:+- LLM (Language Models)+- Embedding Models+- TTS (Text-to-Speech)+- Search Providers+"""++import os+from typing import Any, Dict, List, Literal, Optional++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from src.services.config import (+ ConfigType,+ get_config_manager,+)+from src.services.llm import complete as llm_complete, sanitize_url++router = APIRouter()+++# ==================== Request/Response Models ====================++class ConfigBase(BaseModel):+ """Base configuration model."""+ name: str = Field(..., description="Display name for this configuration")+ provider: str = Field(..., description="Provider type")+++class LLMConfigCreate(ConfigBase):+ """LLM configuration for creation."""+ base_url: str | Dict[str, str] = Field(..., description="API endpoint or {'use_env': 'VAR_NAME'}")+ api_key: str | Dict[str, str] = Field(..., description="API key or {'use_env': 'VAR_NAME'}")+ model: str = Field(..., description="Model name")+ api_version: Optional[str] = None+++class EmbeddingConfigCreate(ConfigBase):+ """Embedding configuration for creation."""+ base_url: str | Dict[str, str]+ api_key: str | Dict[str, str]+ model: str+ dimensions: int = 3072+ api_version: Optional[str] = None+++class TTSConfigCreate(ConfigBase):+ """TTS configuration for creation."""+ base_url: str | Dict[str, str]+ api_key: str | Dict[str, str]+ model: str+ voice: str = "alloy"+ api_version: Optional[str] = None+++class SearchConfigCreate(ConfigBase):+ """Search configuration for creation.++ Uses unified SEARCH_API_KEY environment variable.+ """+ api_key: str | Dict[str, str] = Field(..., description="API key or {'use_env': 'SEARCH_API_KEY'}")+++class ConfigUpdate(BaseModel):+ """Configuration update model."""+ name: Optional[str] = None+ provider: Optional[str] = None+ base_url: Optional[str | Dict[str, str]] = None+ api_key: Optional[str | Dict[str, str]] = None+ model: Optional[str] = None+ dimensions: Optional[int] = None+ voice: Optional[str] = None+ api_version: Optional[str] = None+++class SetActiveRequest(BaseModel):+ """Request to set active configuration."""+ config_id: str+++class TestConnectionRequest(BaseModel):+ """Request to test a connection.++ base_url and api_key can be either:+ - A string value+ - A dict with {"use_env": "VAR_NAME"} to load from environment+ """+ provider: str+ base_url: str | Dict[str, str]+ api_key: str | Dict[str, str]+ model: str+ dimensions: Optional[int] = None # For embedding models+ voice: Optional[str] = None # For TTS models+++def resolve_env_value(value: str | Dict[str, str], fallback: str = "") -> str:+ """+ Resolve a value that may be a string or {"use_env": "VAR_NAME"}.++ If value is a dict with use_env, fetch from environment variable.+ Otherwise return the string value directly.+ """+ if isinstance(value, dict) and "use_env" in value:+ env_var = value["use_env"]+ return os.environ.get(env_var, fallback)+ return value if isinstance(value, str) else fallback+++class ConfigStatusResponse(BaseModel):+ """Response for configuration status."""+ llm: Dict[str, Any]+ embedding: Dict[str, Any]+ tts: Dict[str, Any]+ search: Dict[str, Any]+++class PortsResponse(BaseModel):+ """Response for port configuration."""+ backend_port: int+ frontend_port: int+++# ==================== Status Endpoints ====================+[email protected]("/status", response_model=ConfigStatusResponse)+async def get_config_status():+ """+ Get configuration status for all services.+ Shows which service has active configuration and what it is.+ """+ manager = get_config_manager()++ def get_status(config_type: ConfigType) -> Dict[str, Any]:+ active = manager.get_active_config(config_type)+ env_status = manager.get_env_status(config_type)+ configs = manager.list_configs(config_type)+ active_config = next((c for c in configs if c.get("is_active")), None)++ return {+ "configured": bool(active and active.get("model" if config_type != ConfigType.SEARCH else "provider")),+ "active_config_id": active_config.get("id") if active_config else "default",+ "active_config_name": active_config.get("name") if active_config else "Default",+ "model": active.get("model") if active else None,+ "provider": active.get("provider") if active else None,+ "env_configured": env_status,+ "total_configs": len(configs),+ }++ return ConfigStatusResponse(+ llm=get_status(ConfigType.LLM),+ embedding=get_status(ConfigType.EMBEDDING),+ tts=get_status(ConfigType.TTS),+ search=get_status(ConfigType.SEARCH),+ )++[email protected]("/ports", response_model=PortsResponse)+async def get_ports():+ """Get current port configuration (read-only)."""+ return PortsResponse(+ backend_port=int(os.environ.get("BACKEND_PORT", 8000)),+ frontend_port=int(os.environ.get("FRONTEND_PORT", 3000)),+ )++[email protected]("/providers/{config_type}")+async def get_providers(config_type: Literal["llm", "embedding", "tts", "search"]):+ """Get available provider options for a configuration type."""+ manager = get_config_manager()+ ct = ConfigType(config_type)+ return {"providers": manager.get_provider_options(ct)}+++# ==================== LLM Configuration Endpoints ====================+[email protected]("/llm")+async def list_llm_configs():+ """List all LLM configurations."""+ manager = get_config_manager()+ return {"configs": manager.list_configs(ConfigType.LLM)}++[email protected]("/llm")+async def add_llm_config(config: LLMConfigCreate):+ """Add a new LLM configuration."""+ manager = get_config_manager()+ data = config.model_dump()+ result = manager.add_config(ConfigType.LLM, data)+ return result++[email protected]("/llm/{config_id}")+async def update_llm_config(config_id: str, updates: ConfigUpdate):+ """Update an LLM configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot update default configuration")++ manager = get_config_manager()+ result = manager.update_config(ConfigType.LLM, config_id, updates.model_dump(exclude_none=True))+ if not result:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return result++[email protected]("/llm/{config_id}")+async def delete_llm_config(config_id: str):+ """Delete an LLM configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot delete default configuration")++ manager = get_config_manager()+ success = manager.delete_config(ConfigType.LLM, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration deleted"}++[email protected]("/llm/{config_id}/active")+async def set_active_llm_config(config_id: str):+ """Set an LLM configuration as active."""+ manager = get_config_manager()+ success = manager.set_active_config(ConfigType.LLM, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration activated", "active_id": config_id}++[email protected]("/llm/test")+async def test_llm_connection(request: TestConnectionRequest):+ """Test connection to an LLM provider."""+ try:+ # Resolve use_env references to actual values+ base_url = resolve_env_value(request.base_url)+ api_key = resolve_env_value(request.api_key)++ # Validate required fields+ if not base_url:+ return {"success": False, "message": "Base URL is required"}+ if not request.model:+ return {"success": False, "message": "Model name is required"}++ base_url = sanitize_url(base_url)+ api_key = api_key or "sk-no-key-required"++ response = await llm_complete(+ model=request.model,+ prompt="Hello, are you working?",+ system_prompt="You are a helpful assistant. Reply with 'Yes'.",+ api_key=api_key,+ base_url=base_url,+ binding=request.provider,+ max_tokens=200,+ )+ return {"success": True, "message": "Connection successful", "response": response[:100]}+ except Exception as e:+ return {"success": False, "message": f"Connection failed: {str(e)}"}++[email protected]("/llm/{config_id}/test")+async def test_llm_config_by_id(config_id: str):+ """Test connection for an existing LLM configuration by ID."""+ try:+ manager = get_config_manager()++ if config_id == "default":+ # Get default config from env+ config = manager.get_default_config(ConfigType.LLM)+ else:+ # Find config by ID+ configs = manager.list_configs(ConfigType.LLM)+ config = next((c for c in configs if c.get("id") == config_id), None)+ if not config:+ return {"success": False, "message": f"Configuration '{config_id}' not found"}+ # Resolve use_env references for user configs+ config = manager.resolve_config_env_values(config)++ if not config or not config.get("base_url"):+ return {"success": False, "message": "Configuration is incomplete (missing base_url)"}++ base_url = sanitize_url(config.get("base_url", ""))+ api_key = config.get("api_key") or "sk-no-key-required"+ model = config.get("model", "")+ provider = config.get("provider", "openai")++ response = await llm_complete(+ model=model,+ prompt="Hello, are you working?",+ system_prompt="You are a helpful assistant. Reply with 'Yes'.",+ api_key=api_key,+ base_url=base_url,+ binding=provider,+ max_tokens=200,+ )+ return {"success": True, "message": "Connection successful", "response": response[:100]}+ except Exception as e:+ return {"success": False, "message": f"Connection failed: {str(e)}"}+++# ==================== Embedding Configuration Endpoints ====================+[email protected]("/embedding")+async def list_embedding_configs():+ """List all embedding configurations."""+ manager = get_config_manager()+ return {"configs": manager.list_configs(ConfigType.EMBEDDING)}++[email protected]("/embedding")+async def add_embedding_config(config: EmbeddingConfigCreate):+ """Add a new embedding configuration."""+ manager = get_config_manager()+ data = config.model_dump()+ result = manager.add_config(ConfigType.EMBEDDING, data)+ return result++[email protected]("/embedding/{config_id}")+async def update_embedding_config(config_id: str, updates: ConfigUpdate):+ """Update an embedding configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot update default configuration")++ manager = get_config_manager()+ result = manager.update_config(ConfigType.EMBEDDING, config_id, updates.model_dump(exclude_none=True))+ if not result:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return result++[email protected]("/embedding/{config_id}")+async def delete_embedding_config(config_id: str):+ """Delete an embedding configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot delete default configuration")++ manager = get_config_manager()+ success = manager.delete_config(ConfigType.EMBEDDING, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration deleted"}++[email protected]("/embedding/{config_id}/active")+async def set_active_embedding_config(config_id: str):+ """Set an embedding configuration as active."""+ manager = get_config_manager()+ success = manager.set_active_config(ConfigType.EMBEDDING, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration activated", "active_id": config_id}++[email protected]("/embedding/test")+async def test_embedding_connection(request: TestConnectionRequest):+ """Test connection to an embedding provider."""+ try:+ from src.services.embedding.client import EmbeddingClient+ from src.services.embedding.config import EmbeddingConfig++ # Resolve use_env references+ base_url = resolve_env_value(request.base_url)+ api_key = resolve_env_value(request.api_key)++ # Validate required fields+ if not base_url:+ return {"success": False, "message": "Base URL is required"}+ if not request.model:+ return {"success": False, "message": "Model name is required"}+ if not request.dimensions:+ return {"success": False, "message": "Dimensions is required for embedding models"}++ # Create a test config with dimensions+ test_config = EmbeddingConfig(+ model=request.model,+ api_key=api_key or "sk-no-key-required",+ base_url=base_url,+ binding=request.provider,+ dim=request.dimensions,+ )++ # Create a temporary client for testing+ client = EmbeddingClient(test_config)+ # Use embed() method with a list of texts+ embeddings = await client.embed(["test"])+ if embeddings and len(embeddings) > 0 and len(embeddings[0]) > 0:+ return {"success": True, "message": f"Connection successful (dim={len(embeddings[0])})"}+ return {"success": False, "message": "Failed to generate embeddings"}+ except Exception as e:+ return {"success": False, "message": f"Connection failed: {str(e)}"}++[email protected]("/embedding/{config_id}/test")+async def test_embedding_config_by_id(config_id: str):+ """Test connection for an existing embedding configuration by ID."""+ try:+ from src.services.embedding.client import EmbeddingClient+ from src.services.embedding.config import EmbeddingConfig++ manager = get_config_manager()++ if config_id == "default":+ config = manager.get_default_config(ConfigType.EMBEDDING)+ else:+ configs = manager.list_configs(ConfigType.EMBEDDING)+ config = next((c for c in configs if c.get("id") == config_id), None)+ if not config:+ return {"success": False, "message": f"Configuration '{config_id}' not found"}+ config = manager.resolve_config_env_values(config)++ if not config or not config.get("base_url"):+ return {"success": False, "message": "Configuration is incomplete (missing base_url)"}++ # Create a test config+ test_config = EmbeddingConfig(+ model=config.get("model", ""),+ api_key=config.get("api_key") or "sk-no-key-required",+ base_url=config.get("base_url", ""),+ binding=config.get("provider", "openai"),+ dim=config.get("dimensions", 3072),+ )++ # Create a temporary client for testing+ client = EmbeddingClient(test_config)+ # Use embed() method with a list of texts+ embeddings = await client.embed(["test"])+ if embeddings and len(embeddings) > 0 and len(embeddings[0]) > 0:+ return {"success": True, "message": f"Connection successful (dim={len(embeddings[0])})"}+ return {"success": False, "message": "Failed to generate embeddings"}+ except Exception as e:+ return {"success": False, "message": f"Connection failed: {str(e)}"}+++# ==================== TTS Configuration Endpoints ====================+[email protected]("/tts")+async def list_tts_configs():+ """List all TTS configurations."""+ manager = get_config_manager()+ return {"configs": manager.list_configs(ConfigType.TTS)}++[email protected]("/tts")+async def add_tts_config(config: TTSConfigCreate):+ """Add a new TTS configuration."""+ manager = get_config_manager()+ data = config.model_dump()+ result = manager.add_config(ConfigType.TTS, data)+ return result++[email protected]("/tts/{config_id}")+async def update_tts_config(config_id: str, updates: ConfigUpdate):+ """Update a TTS configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot update default configuration")++ manager = get_config_manager()+ result = manager.update_config(ConfigType.TTS, config_id, updates.model_dump(exclude_none=True))+ if not result:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return result++[email protected]("/tts/{config_id}")+async def delete_tts_config(config_id: str):+ """Delete a TTS configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot delete default configuration")++ manager = get_config_manager()+ success = manager.delete_config(ConfigType.TTS, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration deleted"}++[email protected]("/tts/{config_id}/active")+async def set_active_tts_config(config_id: str):+ """Set a TTS configuration as active."""+ manager = get_config_manager()+ success = manager.set_active_config(ConfigType.TTS, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration activated", "active_id": config_id}++[email protected]("/tts/test")+async def test_tts_connection(request: TestConnectionRequest):+ """Test connection to a TTS provider."""+ try:+ from openai import AsyncOpenAI++ # Resolve use_env references+ base_url = resolve_env_value(request.base_url)+ api_key = resolve_env_value(request.api_key)++ # Validate required fields+ if not base_url:+ return {"success": False, "message": "Base URL is required"}+ if not request.model:+ return {"success": False, "message": "Model name is required"}++ # Test by creating client and checking if we can reach the API+ client = AsyncOpenAI(+ api_key=api_key or "sk-no-key-required",+ base_url=base_url,+ )+ # Just verify we can create the client - actual TTS test would require audio generation+ return {"success": True, "message": "TTS configuration validated"}+ except Exception as e:+ return {"success": False, "message": f"Connection failed: {str(e)}"}++[email protected]("/tts/{config_id}/test")+async def test_tts_config_by_id(config_id: str):+ """Test connection for an existing TTS configuration by ID."""+ try:+ from openai import AsyncOpenAI++ manager = get_config_manager()++ if config_id == "default":+ config = manager.get_default_config(ConfigType.TTS)+ else:+ configs = manager.list_configs(ConfigType.TTS)+ config = next((c for c in configs if c.get("id") == config_id), None)+ if not config:+ return {"success": False, "message": f"Configuration '{config_id}' not found"}+ config = manager.resolve_config_env_values(config)++ if not config or not config.get("base_url"):+ return {"success": False, "message": "Configuration is incomplete (missing base_url)"}++ # Test by creating client+ client = AsyncOpenAI(+ api_key=config.get("api_key") or "sk-no-key-required",+ base_url=config.get("base_url", ""),+ )+ return {"success": True, "message": "TTS configuration validated"}+ except Exception as e:+ return {"success": False, "message": f"Connection failed: {str(e)}"}+++# ==================== Search Configuration Endpoints ====================+[email protected]("/search")+async def list_search_configs():+ """List all search configurations."""+ manager = get_config_manager()+ return {"configs": manager.list_configs(ConfigType.SEARCH)}++[email protected]("/search")+async def add_search_config(config: SearchConfigCreate):+ """Add a new search configuration."""+ manager = get_config_manager()+ data = config.model_dump()+ result = manager.add_config(ConfigType.SEARCH, data)+ return result++[email protected]("/search/{config_id}")+async def update_search_config(config_id: str, updates: ConfigUpdate):+ """Update a search configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot update default configuration")++ manager = get_config_manager()+ result = manager.update_config(ConfigType.SEARCH, config_id, updates.model_dump(exclude_none=True))+ if not result:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return result++[email protected]("/search/{config_id}")+async def delete_search_config(config_id: str):+ """Delete a search configuration."""+ if config_id == "default":+ raise HTTPException(status_code=400, detail="Cannot delete default configuration")++ manager = get_config_manager()+ success = manager.delete_config(ConfigType.SEARCH, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration deleted"}++[email protected]("/search/{config_id}/active")+async def set_active_search_config(config_id: str):+ """Set a search configuration as active."""+ manager = get_config_manager()+ success = manager.set_active_config(ConfigType.SEARCH, config_id)+ if not success:+ raise HTTPException(status_code=404, detail="Configuration not found")+ return {"message": "Configuration activated", "active_id": config_id}+diff --git a/src/api/routers/embedding_provider.py b/src/api/routers/embedding_provider.pydeleted file mode 100644index 1afb1872d..000000000--- a/src/api/routers/embedding_provider.py+++ /dev/null@@ -1,450 +0,0 @@-"""-Embedding Provider API Router-==============================--Manages embedding provider configurations via REST API.-"""--from typing import Any, Dict, List--from fastapi import APIRouter, HTTPException-from pydantic import BaseModel--from src.services.embedding.provider_config import (- EmbeddingProvider,- embedding_provider_config_manager,-)--router = APIRouter()---class TestConnectionRequest(BaseModel):- """Request model for testing embedding provider connection."""-- binding: str- base_url: str- api_key: str = "" # Optional for local providers- model: str- dimensions: int = 1024- requires_key: bool = True--[email protected]("/", response_model=List[EmbeddingProvider])-async def list_providers():- """- List all configured embedding providers.- If no providers exist, auto-create one from current .env configuration.- """- providers = embedding_provider_config_manager.list_providers()-- if not providers:- try:- from src.services.embedding import get_embedding_config-- current_config = get_embedding_config()-- default_provider = EmbeddingProvider(- name=f"Current ({current_config.binding})",- binding=current_config.binding,- base_url=current_config.base_url or "",- api_key=current_config.api_key or "",- model=current_config.model,- dimensions=current_config.dim,- is_active=True,- input_type=current_config.input_type,- normalized=current_config.normalized,- truncate=current_config.truncate,- )-- embedding_provider_config_manager.add_provider(default_provider)- providers = [default_provider]- except Exception as e:- print(f"Warning: Could not auto-create provider from .env: {e}")-- return providers--[email protected]("/", response_model=EmbeddingProvider)-async def add_provider(provider: EmbeddingProvider):- """Add a new embedding provider."""- try:- return embedding_provider_config_manager.add_provider(provider)- except ValueError as e:- raise HTTPException(status_code=400, detail=str(e))--[email protected]("/{name}", response_model=EmbeddingProvider)-async def update_provider(name: str, updates: Dict[str, Any]):- """Update an existing embedding provider."""- provider = embedding_provider_config_manager.update_provider(name, updates)- if not provider:- raise HTTPException(status_code=404, detail="Provider not found")- return provider--[email protected]("/{name}")-async def delete_provider(name: str):- """Delete an embedding provider."""- success = embedding_provider_config_manager.delete_provider(name)- if not success:- raise HTTPException(status_code=404, detail="Provider not found")- return {"message": "Provider deleted"}--[email protected]("/active", response_model=EmbeddingProvider)-async def set_active_provider(name_payload: Dict[str, str]):- """Set the active embedding provider."""- name = name_payload.get("name")- if not name:- raise HTTPException(status_code=400, detail="Name is required")-- provider = embedding_provider_config_manager.set_active_provider(name)- if not provider:- raise HTTPException(status_code=404, detail="Provider not found")- return provider--[email protected]("/test", response_model=Dict[str, Any])-async def test_connection(request: TestConnectionRequest):- """Test connection to an embedding provider."""- try:- from src.services.embedding import reset_embedding_client- from src.services.embedding.config import EmbeddingConfig-- base_url = request.base_url.rstrip("/")-- api_key_to_use = request.api_key- if not request.requires_key and not api_key_to_use:- api_key_to_use = "no-key-required"-- test_config = EmbeddingConfig(- binding=request.binding,- model=request.model,- api_key=api_key_to_use,- base_url=base_url,- dim=request.dimensions,- )-- reset_embedding_client()-- from src.services.embedding.client import EmbeddingClient-- test_client = EmbeddingClient(config=test_config)-- embeddings = await test_client.embed(["Hello, testing embedding service"])-- if not embeddings or not embeddings[0]:- return {- "success": False,- "message": "Connection succeeded but received empty embeddings",- }-- reset_embedding_client()-- return {- "success": True,- "message": "Connection successful",- "dimensions": len(embeddings[0]),- "expected_dimensions": request.dimensions,- }-- except Exception as e:- from src.services.embedding import reset_embedding_client-- reset_embedding_client()-- return {"success": False, "message": f"Connection failed: {str(e)}"}--[email protected]("/current/info", response_model=Dict[str, Any])-async def get_current_model_info():- """Get information about the currently active embedding model."""- try:- from src.services.embedding import get_embedding_client, get_embedding_config-- config = get_embedding_config()- client = get_embedding_client()-- # Get adapter info- adapter = client.manager.get_active_adapter()- model_info = adapter.get_model_info()-- return {- "binding": config.binding,- "model": config.model,- "dimensions": config.dim,- "base_url": config.base_url,- "max_tokens": config.max_tokens,- "request_timeout": config.request_timeout,- "input_type": config.input_type,- "adapter_info": model_info,- }- except Exception as e:- raise HTTPException(status_code=500, detail=f"Failed to get model info: {str(e)}")--[email protected]("/{name}/models", response_model=Dict[str, Any])-async def list_available_models(name: str):- """- List available models for a provider (supports Ollama and LM Studio).-- Args:- name: Provider name to query-- Returns:- Dictionary with available models and their information- """- try:- provider = embedding_provider_config_manager.get_provider(name)- if not provider:- raise HTTPException(status_code=404, detail=f"Provider '{name}' not found")-- if provider.binding == "ollama":- import httpx-- base_url = provider.base_url.rstrip("/")-- async with httpx.AsyncClient(timeout=10) as client:- try:- response = await client.get(f"{base_url}/api/tags")- response.raise_for_status()- data = response.json()-- embedding_models = []- for model in data.get("models", []):- model_name = model.get("name", "")- if any(- keyword in model_name.lower()- for keyword in [- "embed",- "nomic",- "minilm",- "mpnet",- "bge",- "mxbai",- "snowflake",- "arctic",- ]- ):- embedding_models.append(- {- "name": model_name,- "size": model.get("size", 0),- "modified": model.get("modified_at", ""),- "digest": model.get("digest", ""),- }- )-- return {- "provider": name,- "binding": provider.binding,- "models": embedding_models,- "total": len(embedding_models),- }-- except httpx.ConnectError:- raise HTTPException(- status_code=503,- detail=f"Cannot connect to Ollama at {base_url}. Ensure Ollama is running.",- )- except httpx.HTTPError as e:- raise HTTPException(- status_code=503, detail=f"Failed to connect to Ollama: {str(e)}"- )-- elif provider.binding == "lm_studio":- import httpx-- base_url = provider.base_url.rstrip("/")- if base_url.endswith("/v1"):- base_url = base_url[:-3]-- async with httpx.AsyncClient(timeout=10) as client:- try:- response = await client.get(f"{base_url}/v1/models")- response.raise_for_status()- data = response.json()-- models = []- for model in data.get("data", []):- models.append(- {- "name": model.get("id", ""),- "owned_by": model.get("owned_by", ""),- "created": model.get("created", 0),- }- )-- return {- "provider": name,- "binding": provider.binding,- "models": models,- "total": len(models),- }-- except httpx.ConnectError:- raise HTTPException(- status_code=503,- detail=f"Cannot connect to LM Studio at {base_url}. Ensure LM Studio is running.",- )- except httpx.HTTPError as e:- raise HTTPException(- status_code=503, detail=f"Failed to connect to LM Studio: {str(e)}"- )- else:- from src.services.embedding.provider import get_embedding_provider_manager-- manager = get_embedding_provider_manager()- adapter_class = manager.ADAPTER_MAPPING.get(provider.binding)-- if adapter_class and hasattr(adapter_class, "MODELS_INFO"):- models_info = adapter_class.MODELS_INFO- models = []-- for model_name, info in models_info.items():- if isinstance(info, dict):- models.append(- {- "name": model_name,- "dimensions": info.get("default", info.get("dimensions", [])),- "info": info,- }- )- else:- models.append(- {- "name": model_name,- "dimensions": info,- }- )-- return {- "provider": name,- "binding": provider.binding,- "models": models,- "total": len(models),- "note": "These are known models. Provider may support additional models.",- }-- return {- "provider": name,- "binding": provider.binding,- "models": [],- "total": 0,- "note": f"Model listing not supported for {provider.binding}",- }-- except HTTPException:- raise- except Exception as e:- raise HTTPException(status_code=500, detail=f"Failed to list models: {str(e)}")--[email protected]("/validate", response_model=Dict[str, Any])-async def validate_provider_config(provider: EmbeddingProvider):- """- Validate a provider configuration without saving it.-- Checks:- - Server connectivity- - Model availability- - Dimension compatibility- """- try:- import httpx-- base_url = provider.base_url.rstrip("/")-- results = {- "valid": True,- "checks": {},- "warnings": [],- "errors": [],- }-- # Check 1: Server connectivity- try:- if provider.binding == "ollama":- async with httpx.AsyncClient(timeout=5) as client:- response = await client.get(f"{base_url}/api/tags")- response.raise_for_status()- results["checks"]["server_reachable"] = True- else:- results["checks"]["server_reachable"] = True- except Exception as e:- results["checks"]["server_reachable"] = False- results["errors"].append(f"Cannot reach server at {base_url}: {str(e)}")- results["valid"] = False-- # Check 2: Model availability (Ollama only)- if provider.binding == "ollama" and results["checks"]["server_reachable"]:- try:- async with httpx.AsyncClient(timeout=5) as client:- response = await client.get(f"{base_url}/api/tags")- data = response.json()-- available_models = [m.get("name", "") for m in data.get("models", [])]- model_available = any(provider.model in m for m in available_models)-- results["checks"]["model_available"] = model_available-- if not model_available:- results["warnings"].append(- f"Model '{provider.model}' not found. Available: {', '.join(available_models[:5])}"- )- except Exception as e:- results["checks"]["model_available"] = False- results["warnings"].append(f"Could not verify model availability: {str(e)}")-- # Check 3: Dimension compatibility- from src.services.embedding.provider import get_embedding_provider_manager-- manager = get_embedding_provider_manager()- adapter_class = manager.ADAPTER_MAPPING.get(provider.binding)-- if adapter_class and hasattr(adapter_class, "MODELS_INFO"):- models_info = adapter_class.MODELS_INFO-- if provider.model in models_info:- expected_dims = models_info[provider.model]-- if isinstance(expected_dims, dict):- supported_dims = expected_dims.get("dimensions", [])- if isinstance(supported_dims, list):- if provider.dimensions not in supported_dims:- results["warnings"].append(- f"Dimension {provider.dimensions} not in supported list: {supported_dims}"- )- else:- expected = expected_dims.get("default", supported_dims)- if provider.dimensions != expected:- results["warnings"].append(- f"Expected {expected} dimensions, got {provider.dimensions}"- )- else:- if provider.dimensions != expected_dims:- results["warnings"].append(- f"Expected {expected_dims} dimensions, got {provider.dimensions}"- )-- results["checks"]["dimensions_compatible"] = len(results["warnings"]) == 0-- # Check 4: API key requirement- requires_key = provider.binding not in [- "ollama",- "lollms",- "lm_studio",- "text_generation_webui",- "localai",- ]-- if requires_key and not provider.api_key:- results["errors"].append(f"API key required for {provider.binding}")- results["valid"] = False-- results["checks"]["api_key_valid"] = not requires_key or bool(provider.api_key)-- return results-- except Exception as e:- raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.pyindex 47f147d22..6ae04f380 100644--- a/src/api/routers/knowledge.py+++ b/src/api/routers/knowledge.py@@ -121,8 +121,12 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer):async def run_upload_processing_task(- kb_name: str, base_dir: str, api_key: str, base_url: str, uploaded_file_paths: list[str],- rag_provider: str = None+ kb_name: str,+ base_dir: str,+ api_key: str,+ base_url: str,+ uploaded_file_paths: list[str],+ rag_provider: str = None,):"""Background task for processing uploaded files"""task_manager = TaskIDManager.get_instance()@@ -208,7 +212,7 @@ async def get_rag_providers():"""Get list of available RAG providers."""try:from src.services.rag.service import RAGService-+providers = RAGService.list_providers()return {"providers": providers}except Exception as e:@@ -316,8 +320,10 @@ async def delete_knowledge_base(kb_name: str):@router.post("/{kb_name}/upload")async def upload_files(- kb_name: str, background_tasks: BackgroundTasks, files: list[UploadFile] = File(...),- rag_provider: str = Form(None)+ kb_name: str,+ background_tasks: BackgroundTasks,+ files: list[UploadFile] = File(...),+ rag_provider: str = Form(None),):"""Upload files to a knowledge base and process them in background."""try:@@ -406,8 +412,10 @@ async def upload_files(@router.post("/create")async def create_knowledge_base(- background_tasks: BackgroundTasks, name: str = Form(...), files: list[UploadFile] = File(...),- rag_provider: str = Form("raganything")+ background_tasks: BackgroundTasks,+ name: str = Form(...),+ files: list[UploadFile] = File(...),+ rag_provider: str = Form("raganything"),):"""Create a new knowledge base and initialize it with files."""try:diff --git a/src/api/routers/llm_provider.py b/src/api/routers/llm_provider.pydeleted file mode 100644index 9de2eb076..000000000--- a/src/api/routers/llm_provider.py+++ /dev/null@@ -1,161 +0,0 @@-from typing import Any, Dict, List, Literal--from fastapi import APIRouter, HTTPException-from pydantic import BaseModel--from src.services.llm import (- complete as llm_complete,-)-from src.services.llm import (- fetch_models as llm_fetch_models,-)-from src.services.llm import (- get_mode_info,- get_provider_presets,- sanitize_url,-)-from src.services.llm.provider import LLMProvider, provider_manager--router = APIRouter()---class TestConnectionRequest(BaseModel):- binding: str- base_url: str- api_key: str- model: str- requires_key: bool = True # Default to True for backward compatibility- provider_type: Literal["api", "local"] = "local" # New field--[email protected]("/", response_model=List[LLMProvider])-async def list_providers():- """List all configured LLM providers."""- return provider_manager.list_providers()--[email protected]("/", response_model=LLMProvider)-async def add_provider(provider: LLMProvider):- """Add a new LLM provider."""- try:- return provider_manager.add_provider(provider)- except ValueError as e:- raise HTTPException(status_code=400, detail=str(e))--[email protected]("/{name}/", response_model=LLMProvider)-async def update_provider(name: str, updates: Dict[str, Any]):- """Update an existing LLM provider."""- provider = provider_manager.update_provider(name, updates)- if not provider:- raise HTTPException(status_code=404, detail="Provider not found")- return provider--[email protected]("/")-async def delete_provider_by_query(name: str):- """Delete an LLM provider (query param version)."""- success = provider_manager.delete_provider(name)- if not success:- raise HTTPException(status_code=404, detail="Provider not found")- return {"message": "Provider deleted"}--[email protected]("/{name}/")-async def delete_provider(name: str):- """Delete an LLM provider."""- success = provider_manager.delete_provider(name)- if not success:- raise HTTPException(status_code=404, detail="Provider not found")- return {"message": "Provider deleted"}--[email protected]("/active/", response_model=LLMProvider)-async def set_active_provider(name_payload: Dict[str, str]):- """Set the active LLM provider."""- name = name_payload.get("name")- if not name:- raise HTTPException(status_code=400, detail="Name is required")-- provider = provider_manager.set_active_provider(name)- if not provider:- raise HTTPException(status_code=404, detail="Provider not found")- return provider--[email protected]("/test/", response_model=Dict[str, Any])-async def test_connection(request: TestConnectionRequest):- """Test connection to an LLM provider."""- try:- # Use unified sanitize_url for consistent URL handling- # Handles Ollama, LM Studio, and other local servers- base_url = sanitize_url(request.base_url)-- # Simple test prompt- if not request.requires_key and not request.api_key:- # Inject dummy key if not required and not provided- # This satisfies the OpenAI client library which demands a key- api_key_to_use = "sk-no-key-required"- else:- api_key_to_use = request.api_key-- response = await llm_complete(- model=request.model,- prompt="Hello, are you working?",- system_prompt="You are a helpful assistant. Reply with 'Yes'.",- api_key=api_key_to_use,- base_url=base_url,- binding=request.binding,- max_tokens=200,- )- return {"success": True, "message": "Connection successful", "response": response}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}--[email protected]("/models/", response_model=Dict[str, Any])-async def fetch_available_models(request: TestConnectionRequest):- """Fetch available models from the provider."""- try:- # Use unified sanitize_url for consistent URL handling- base_url = sanitize_url(request.base_url)-- models = await llm_fetch_models(- binding=request.binding,- base_url=base_url,- api_key=request.api_key if request.requires_key else None,- )- return {"success": True, "models": models}- except Exception as e:- return {"success": False, "message": f"Failed to fetch models: {str(e)}"}---# ==================== LLM Mode Endpoints ====================--[email protected]("/mode/", response_model=Dict[str, Any])-async def get_llm_mode_info():- """- Get information about the current LLM configuration mode.-- Returns:- Dict containing:- - mode: Current deployment mode ('api', 'local', or 'hybrid')- - active_provider: Active provider info (if any)- - env_configured: Whether env vars are properly configured- - effective_source: Which config source is being used ('env' or 'provider')- """- return get_mode_info()--[email protected]("/presets/", response_model=Dict[str, Any])-async def get_presets():- """- Get provider presets for API and Local providers.-- Returns:- Dict containing:- - api: API provider presets (OpenAI, Anthropic, DeepSeek, etc.)- - local: Local provider presets (Ollama, LM Studio, vLLM, etc.)- """- return get_provider_presets()diff --git a/src/api/routers/notebook.py b/src/api/routers/notebook.pyindex 438e92c9b..38b99680c 100644--- a/src/api/routers/notebook.py+++ b/src/api/routers/notebook.py@@ -45,7 +45,7 @@ class AddRecordRequest(BaseModel):"""Add record request"""notebook_ids: list[str]- record_type: Literal["solve", "question", "research", "co_writer"]+ record_type: Literal["solve", "question", "research", "co_writer", "chat"]title: struser_query: stroutput: strdiff --git a/src/api/routers/question.py b/src/api/routers/question.pyindex f629a8506..abc2afb01 100644--- a/src/api/routers/question.py+++ b/src/api/routers/question.py@@ -9,10 +9,10 @@ import tracebackfrom fastapi import APIRouter, WebSocket, WebSocketDisconnectfrom src.agents.question import AgentCoordinator-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.tools.question import mimic_exam_questionsfrom src.utils.document_validator import DocumentValidatorfrom src.utils.error_utils import format_exception_message@@ -96,13 +96,19 @@ async def websocket_mimic_generate(websocket: WebSocket):ANSI_ESCAPE_PATTERN = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")class StdoutInterceptor:- def __init__(self, queue):+ def __init__(self, queue, original):self.queue = queue- self.original_stdout = sys.stdout+ self.original_stdout = original+ self._closed = Falsedef write(self, message):+ if self._closed:+ return# Write to terminal first (with ANSI codes for color)- self.original_stdout.write(message)+ try:+ self.original_stdout.write(message)+ except Exception:+ pass# Strip ANSI escape codes before sending to frontendclean_message = ANSI_ESCAPE_PATTERN.sub("", message).strip()# Then send to frontend (non-blocking)@@ -119,9 +125,18 @@ async def websocket_mimic_generate(websocket: WebSocket):passdef flush(self):- self.original_stdout.flush()+ if not self._closed:+ try:+ self.original_stdout.flush()+ except Exception:+ pass++ def close(self):+ """Mark interceptor as closed to prevent further writes."""+ self._closed = True- sys.stdout = StdoutInterceptor(log_queue)+ interceptor = StdoutInterceptor(log_queue, original_stdout)+ sys.stdout = interceptortry:await websocket.send_json(@@ -256,13 +271,22 @@ async def websocket_mimic_generate(websocket: WebSocket):f"Mimic generation complete: {len(generated)} succeeded, {len(failed)} failed")- await websocket.send_json({"type": "complete"})+ try:+ await websocket.send_json({"type": "complete"})+ except (RuntimeError, WebSocketDisconnect):+ logger.debug("WebSocket closed before complete signal could be sent")else:error_msg = result.get("error", "Unknown error")- await websocket.send_json({"type": "error", "content": error_msg})+ try:+ await websocket.send_json({"type": "error", "content": error_msg})+ except (RuntimeError, WebSocketDisconnect):+ passlogger.error(f"Mimic generation failed: {error_msg}")finally:+ # Close interceptor and restore stdout+ if "interceptor" in locals():+ interceptor.close()sys.stdout = original_stdoutexcept WebSocketDisconnect:@@ -275,13 +299,27 @@ async def websocket_mimic_generate(websocket: WebSocket):except Exception:passfinally:+ # Ensure stdout is always restoredsys.stdout = original_stdout++ # Clean up pusher taskif pusher_task:try:pusher_task.cancel()await pusher_task+ except asyncio.CancelledError:+ pass # Expected when cancellingexcept Exception:pass++ # Drain any remaining items in the queue+ try:+ while not log_queue.empty():+ log_queue.get_nowait()+ except Exception:+ pass++ # Close WebSockettry:await websocket.close()except Exception:@@ -386,21 +424,12 @@ async def websocket_question_generate(websocket: WebSocket):logger.debug("WebSocket closed, stopping question generation")return- # Send initial agent status- try:- await websocket.send_json(- {"type": "agent_status", "all_agents": coordinator.agent_status}- )- except (RuntimeError, WebSocketDisconnect):- logger.debug("WebSocket closed, stopping question generation")- return-# Use custom mode generation (new streamlined flow)logger.info(f"Starting custom mode generation for {count} question(s)")# Use the new custom generation methodbatch_result = await coordinator.generate_questions_custom(- base_requirement=requirement,+ requirement=requirement,num_questions=count,)diff --git a/src/api/routers/settings.py b/src/api/routers/settings.pyindex 4f971a939..92f283594 100644--- a/src/api/routers/settings.py+++ b/src/api/routers/settings.py@@ -1,308 +1,66 @@"""-Settings API Router-Manages user settings: theme, language, environment variables, etc.+Settings API Router (Simplified)+================================++Manages basic UI settings: theme, language, sidebar customization.+Configuration for LLM/Embedding/TTS/Search is handled by the unified config service."""import json-import osfrom pathlib import Path-from typing import Any, Dict, Literal+from typing import List, Literal, Optional-from fastapi import APIRouter, HTTPException+from fastapi import APIRouterfrom pydantic import BaseModel-from src.services.embedding import get_embedding_config-from src.services.llm import get_llm_config-from src.services.tts import get_tts_config-from src.utils.config_manager import ConfigManager-router = APIRouter()-config_manager = ConfigManager()--# ==================== Environment Variables Configuration ====================-# Define all supported environment variables with descriptions-# These variables can be modified at runtime without restarting the server--ENV_VAR_DEFINITIONS = {- # LLM Mode Configuration- "LLM_MODE": {- "description": "LLM deployment mode: 'api' (cloud only), 'local' (self-hosted only), 'hybrid' (both, use active provider)",- "category": "llm",- "required": False,- "default": "hybrid",- "sensitive": False,- },- # LLM Configuration (supports both cloud and local)- "LLM_BINDING": {- "description": "LLM protocol type: openai (for OpenAI-compatible APIs including Ollama, vLLM), anthropic (for Claude)",- "category": "llm",- "required": False,- "default": "openai",- "sensitive": False,- },- "LLM_MODEL": {- "description": "Model name. Cloud: gpt-4o, deepseek-chat. Local: llama3.2, qwen2.5, mistral-nemo",- "category": "llm",- "required": True,- "default": "",- "sensitive": False,- },- "LLM_HOST": {- "description": "API endpoint. Cloud: https://api.openai.com/v1. Local: http://localhost:11434/v1 (Ollama), http://localhost:1234/v1 (LM Studio)",- "category": "llm",- "required": True,- "default": "",- "sensitive": False,- },- "LLM_API_KEY": {- "description": "API key (required for cloud, optional for local - use 'ollama' or any string for Ollama)",- "category": "llm",- "required": True,- "default": "",- "sensitive": True,- },- "LLM_API_VERSION": {- "description": "API version for Azure OpenAI (e.g., 2024-02-15-preview)",- "category": "llm",- "required": False,- "default": "",- "sensitive": False,- },- # Embedding Configuration (supports both cloud and local)- "EMBEDDING_BINDING": {- "description": "Embedding provider: openai, ollama, lm_studio, azure_openai, jina, cohere, huggingface",- "category": "embedding",- "required": False,- "default": "openai",- "sensitive": False,- },- "EMBEDDING_MODEL": {- "description": "Model name. Cloud: text-embedding-3-large. Local: nomic-embed-text, mxbai-embed-large",- "category": "embedding",- "required": True,- "default": "",- "sensitive": False,- },- "EMBEDDING_DIMENSION": {- "description": "Vector dimension: 3072 (text-embedding-3-large), 768 (nomic-embed-text), 1024 (mxbai)",- "category": "embedding",- "required": False,- "default": "3072",- "sensitive": False,- },- "EMBEDDING_HOST": {- "description": "API endpoint. Cloud: https://api.openai.com/v1. Local: http://localhost:11434 (Ollama)",- "category": "embedding",- "required": True,- "default": "",- "sensitive": False,- },- "EMBEDDING_API_KEY": {- "description": "API key (required for cloud providers, not needed for Ollama/local)",- "category": "embedding",- "required": False,- "default": "",- "sensitive": True,- "conditional": "Required for cloud providers (OpenAI, Jina, Cohere, etc.). Not needed for Ollama or local models.",- },- "EMBEDDING_API_VERSION": {- "description": "API version for Azure OpenAI (e.g., 2024-02-15-preview)",- "category": "embedding",- "required": False,- "default": "",- "sensitive": False,- },- # TTS Configuration (OpenAI compatible API)- "TTS_MODEL": {- "description": "OpenAI TTS model (tts-1 for speed, tts-1-hd for quality)",- "category": "tts",- "required": False,- "default": "",- "sensitive": False,- },- "TTS_URL": {- "description": "OpenAI compatible API endpoint (e.g., https://api.openai.com/v1)",- "category": "tts",- "required": False,- "default": "",- "sensitive": False,- },- "TTS_API_KEY": {- "description": "TTS API authentication key (OpenAI API Key)",- "category": "tts",- "required": False,- "default": "",- "sensitive": True,- },- "TTS_BINDING": {- "description": "TTS service provider type (openai, azure_openai)",- "category": "tts",- "required": False,- "default": "openai",- "sensitive": False,- },- "TTS_BINDING_API_VERSION": {- "description": "API version for Azure OpenAI TTS (e.g., 2024-02-15-preview)",- "category": "tts",- "required": False,- "default": "",- "sensitive": False,- },- "TTS_VOICE": {- "description": "Default voice: alloy, echo, fable, onyx, nova, shimmer",- "category": "tts",- "required": False,- "default": "alloy",- "sensitive": False,- },- # Web Search Configuration- "SEARCH_PROVIDER": {- "description": "Default search provider: perplexity, baidu, tavily, exa, serper, jina",- "category": "search",- "required": False,- "default": "perplexity",- "sensitive": False,- },- "PERPLEXITY_API_KEY": {- "description": "Perplexity API key for AI-powered search (https://perplexity.ai/settings/api)",- "category": "search",- "required": False,- "default": "",- "sensitive": True,- },- "BAIDU_API_KEY": {- "description": "Baidu API key for AI search (https://console.bce.baidu.com/ai_apaas/resource)",- "category": "search",- "required": False,- "default": "",- "sensitive": True,- },- "TAVILY_API_KEY": {- "description": "Tavily API key for research-focused search (https://tavily.com)",- "category": "search",- "required": False,- "default": "",- "sensitive": True,- },- "EXA_API_KEY": {- "description": "Exa API key for neural/embeddings search (https://dashboard.exa.ai)",- "category": "search",- "required": False,- "default": "",- "sensitive": True,- },- "SERPER_API_KEY": {- "description": "Serper API key for Google SERP results (https://serper.dev)",- "category": "search",- "required": False,- "default": "",- "sensitive": True,- },- "JINA_API_KEY": {- "description": "Jina API key for SERP with content extraction (https://jina.ai/reader) - optional, has free tier",- "category": "search",- "required": False,- "default": "",- "sensitive": True,- },-}-# Categories for organizing the UI-ENV_CATEGORIES = {- "llm": {- "name": "LLM Configuration",- "description": "LLM settings for AI reasoning. Supports cloud APIs (OpenAI, DeepSeek) and local servers (Ollama, LM Studio).",- "icon": "brain",- },- "embedding": {- "name": "Embedding Configuration",- "description": "Embedding settings for RAG. Supports cloud (OpenAI) and local (Ollama with nomic-embed-text).",- "icon": "database",- },- "tts": {- "name": "TTS Configuration",- "description": "Text-to-Speech settings (OpenAI-compatible API).",- "icon": "volume",- },- "search": {- "name": "Web Search Configuration",- "description": "Web search providers: Perplexity, Baidu, Tavily, Exa, Serper, Jina",- "icon": "search",- },-}+# Settings file path for UI preferences (stored in settings folder with other configs)+SETTINGS_FILE = (+ Path(__file__).parent.parent.parent.parent / "data" / "user" / "settings" / "interface.json"+)-# Settings file path (for local client/UI prefs not appropriate for main.yaml)-SETTINGS_FILE = Path(__file__).parent.parent.parent.parent / "data" / "user" / "settings.json"+# Default sidebar navigation order+DEFAULT_SIDEBAR_NAV_ORDER = {+ "start": ["/", "/history", "/knowledge", "/notebook"],+ "learnResearch": ["/question", "/solver", "/guide", "/ideagen", "/research", "/co_writer"],+}# Default UI settingsDEFAULT_UI_SETTINGS = {"theme": "light",- "language": "en", # Interface language- "output_language": "en", # Output preference (legacy, might move to main.yaml)+ "language": "en",+ "sidebar_description": "✨ Data Intelligence Lab @ HKU",+ "sidebar_nav_order": DEFAULT_SIDEBAR_NAV_ORDER,}+class SidebarNavOrder(BaseModel):+ start: List[str]+ learnResearch: List[str]++class UISettings(BaseModel):theme: Literal["light", "dark"] = "light"language: Literal["zh", "en"] = "en"- output_language: Literal["zh", "en"] = "en"---class FullSettingsResponse(BaseModel):- ui: UISettings- config: Dict[str, Any]- env: Dict[str, str]+ sidebar_description: Optional[str] = None+ sidebar_nav_order: Optional[SidebarNavOrder] = None-# Environment variable models-class EnvVarInfo(BaseModel):- """Information about a single environment variable"""+class ThemeUpdate(BaseModel):+ theme: Literal["light", "dark"]- key: str- value: str- description: str- category: str- required: bool- default: str- sensitive: bool- is_set: bool # Whether the variable has a non-empty value+class LanguageUpdate(BaseModel):+ language: Literal["zh", "en"]-class EnvCategoryInfo(BaseModel):- """Information about an environment variable category"""- id: str- name: str+class SidebarDescriptionUpdate(BaseModel):description: str- icon: str---class EnvConfigResponse(BaseModel):- """Response for environment configuration"""-- variables: list[EnvVarInfo]- categories: list[EnvCategoryInfo]---class EnvVarUpdate(BaseModel):- """Single environment variable update"""-- key: str- value: str---class EnvConfigUpdate(BaseModel):- """Batch environment variables update"""-- variables: list[EnvVarUpdate]-class ConfigUpdate(BaseModel):- config: Dict[str, Any]---class ThemeUpdate(BaseModel):- theme: Literal["light", "dark"]+class SidebarNavOrderUpdate(BaseModel):+ nav_order: SidebarNavOrderdef load_ui_settings() -> dict:@@ -324,33 +82,10 @@ def save_ui_settings(settings: dict):json.dump(settings, f, ensure_ascii=False, indent=2)[email protected]("", response_model=FullSettingsResponse)async def get_settings():- """- Get all settings:- 1. UI preferences (theme, etc)- 2. Backend Configuration (main.yaml)- 3. Environment Info (models, etc)- """- ui_settings = load_ui_settings()- main_config = config_manager.load_config()- env_info = config_manager.get_env_info()-- return {"ui": ui_settings, "config": main_config, "env": env_info}--[email protected]("/config")-async def update_config(update: ConfigUpdate):- """Update main.yaml configuration"""- # Filter out immutable sections if needed (e.g. server port),- # but for now we trust `save_config` to handle the merge.- # Ideally should validate against a schema.-- success = config_manager.save_config(update.config)- if not success:- raise HTTPException(status_code=500, detail="Failed to save configuration")-- return config_manager.load_config()+ """Get UI settings."""+ return {"ui": load_ui_settings()}@router.put("/theme")@@ -362,6 +97,15 @@ async def update_theme(update: ThemeUpdate):return {"theme": update.theme}[email protected]("/language")+async def update_language(update: LanguageUpdate):+ """Update UI language"""+ current_ui = load_ui_settings()+ current_ui["language"] = update.language+ save_ui_settings(current_ui)+ return {"language": update.language}++@router.put("/ui")async def update_ui_settings(update: UISettings):"""Update all UI settings"""@@ -390,485 +134,31 @@ async def get_themes():}-# Legacy/Specific endpoints required by current frontend (will be deprecated/updated)-# Keeping them for now if needed, or rewriting them to use new logic if frontend calls them.-# The user wants "Refactor entire backend logic", so I can break old endpoints if I update frontend.-# But keeping some compatibility or simple redirect is good practice.--[email protected]("/system-language")-async def get_system_language():- """Get system language from main.yaml"""- config = config_manager.load_config()- system_config = config.get("system", {})- language = system_config.get("language", "en")- return {"language": language}---class SystemLanguageUpdate(BaseModel):- language: Literal["zh", "en"]--[email protected]("/system-language")-async def update_system_language(update: SystemLanguageUpdate):- """Update system language in main.yaml"""- config = config_manager.load_config()- if "system" not in config:- config["system"] = {}- config["system"]["language"] = update.language- if config_manager.save_config(config):- return {"language": update.language}- raise HTTPException(status_code=500, detail="Failed to save system language")--[email protected]("/config-info")-async def get_config_info():- """Get configuration information (paths, kb settings, etc.)"""- config = config_manager.load_config()-- paths = config.get("paths", {})- user_data_dir = paths.get("user_data_dir", "./data/user")- kb_base_dir = (- config.get("tools", {}).get("rag_tool", {}).get("kb_base_dir", "./data/knowledge_bases")- )- default_kb = config.get("tools", {}).get("rag_tool", {}).get("default_kb", "ai_textbook")- workspace = (- config.get("tools", {})- .get("run_code", {})- .get("workspace", "./data/user/run_code_workspace")- )-- return {- "kb_base_dir": kb_base_dir,- "user_data_dir": user_data_dir,- "default_kb": default_kb,- "workspace": workspace,- }---# ==================== Environment Variables API ====================---def _mask_sensitive_value(value: str, sensitive: bool) -> str:- """Mask sensitive values for display (show first 4 and last 4 chars)"""- if not sensitive or not value:- return value- if len(value) <= 8:- return "*" * len(value)- return f"{value[:4]}{'*' * (len(value) - 8)}{value[-4:]}"--[email protected]("/env", response_model=EnvConfigResponse)-async def get_env_config():- """- Get all environment variables configuration.-- Returns current values (with sensitive values masked), descriptions,- and category information for the frontend to display.-- Note: This returns the runtime values, which may differ from .env file- if they have been updated via the API.- """- variables = []-- for key, definition in ENV_VAR_DEFINITIONS.items():- current_value = os.environ.get(key, definition["default"])- is_set = bool(current_value and current_value.strip())-- variables.append(- EnvVarInfo(- key=key,- value=_mask_sensitive_value(current_value, definition["sensitive"]),- description=definition["description"],- category=definition["category"],- required=definition["required"],- default=definition["default"],- sensitive=definition["sensitive"],- is_set=is_set,- )- )-- categories = [- EnvCategoryInfo(id=cat_id, **cat_info) for cat_id, cat_info in ENV_CATEGORIES.items()- ]-- return EnvConfigResponse(variables=variables, categories=categories)--[email protected]("/env/{key}")-async def get_env_var(key: str):- """- Get a single environment variable value.-- For sensitive variables, returns masked value.- """- if key not in ENV_VAR_DEFINITIONS:- raise HTTPException(status_code=404, detail=f"Unknown environment variable: {key}")-- definition = ENV_VAR_DEFINITIONS[key]- current_value = os.environ.get(key, definition["default"])-- return {- "key": key,- "value": _mask_sensitive_value(current_value, definition["sensitive"]),- "description": definition["description"],- "category": definition["category"],- "required": definition["required"],- "is_set": bool(current_value and current_value.strip()),- }---def _update_dot_env(updates: Dict[str, str], removals: list[str]):- """Update variables in .env file preserving comments and structure."""- env_path = Path(__file__).parent.parent.parent.parent / ".env"-- if not env_path.exists():- # Create new if doesn't exist- with open(env_path, "w", encoding="utf-8") as f:- for k, v in updates.items():- if " " in v or "#" in v:- f.write(f'{k}="{v}"\n')- else:- f.write(f"{k}={v}\n")- return-- # Read existing- try:- with open(env_path, "r", encoding="utf-8") as f:- lines = f.readlines()- except Exception as e:- print(f"Error reading .env: {e}")- return-- new_lines = []- processed_keys = set()-- for line in lines:- stripped = line.strip()- if not stripped or stripped.startswith("#"):- new_lines.append(line)- continue-- # Parse key- if "=" in stripped:- key = stripped.split("=")[0].strip()-- if key in removals:- continue # Skip/Remove this line-- if key in updates:- # Update this line- val = updates[key]- # Simple quoting suggestion- if " " in val or "#" in val or '"' in val or "'" in val:- # minimal escape of double quotes- val = val.replace('"', '\\"')- new_lines.append(f'{key}="{val}"\n')- else:- new_lines.append(f"{key}={val}\n")- processed_keys.add(key)- continue-- new_lines.append(line)-- # Append new keys that weren't found- for k, v in updates.items():- if k not in processed_keys and k not in removals:- if " " in v or "#" in v or '"' in v or "'" in v:- val = v.replace('"', '\\"')- new_lines.append(f'\n{k}="{val}"\n')- else:- new_lines.append(f"\n{k}={v}\n")-- # Write back- try:- with open(env_path, "w", encoding="utf-8") as f:- f.writelines(new_lines)- except Exception as e:- print(f"Error writing .env: {e}")--[email protected]("/env")-async def update_env_config(update: EnvConfigUpdate):- """- Update environment variables at runtime and persist to .env.- """- updated_vars = []- errors = []-- env_updates = {}- env_removals = []-- for var_update in update.variables:- key = var_update.key- value = var_update.value-- # Validate the variable is known- if key not in ENV_VAR_DEFINITIONS:- errors.append(f"Unknown environment variable: {key}")- continue-- definition = ENV_VAR_DEFINITIONS[key]-- # Skip if value is masked (user didn't change it)- if definition["sensitive"] and "*" in value:- # Value is masked, skip update- continue-- # Update the environment variable- if value:- os.environ[key] = value- env_updates[key] = value- elif key in os.environ:- # If value is empty and variable exists, remove it- del os.environ[key]- env_removals.append(key)-- updated_vars.append(key)-- # Persist to .env- if env_updates or env_removals:- _update_dot_env(env_updates, env_removals)-- if errors:- raise HTTPException(status_code=400, detail={"errors": errors, "updated": updated_vars})-- # Return the updated configuration- return {- "success": True,- "updated": updated_vars,- "message": f"Updated {len(updated_vars)} environment variables.",- }--[email protected]("/env/{key}")-async def update_single_env_var(key: str, value: str):- """- Update a single environment variable at runtime.-- Note: Changes are NOT persisted to .env file.- """- if key not in ENV_VAR_DEFINITIONS:- raise HTTPException(status_code=404, detail=f"Unknown environment variable: {key}")-- definition = ENV_VAR_DEFINITIONS[key]-- # Skip if value is masked (user didn't change it)- if definition["sensitive"] and "*" in value:- return {"success": False, "message": "Cannot update with masked value"}-- # Update the environment variable- if value:- os.environ[key] = value- _update_dot_env({key: value}, [])- elif key in os.environ:- del os.environ[key]- _update_dot_env({}, [key])-[email protected]("/sidebar")+async def get_sidebar_settings():+ """Get sidebar customization settings"""+ current_ui = load_ui_settings()return {- "success": True,- "key": key,- "message": f"Environment variable {key} updated.",+ "description": current_ui.get(+ "sidebar_description", DEFAULT_UI_SETTINGS["sidebar_description"]+ ),+ "nav_order": current_ui.get("sidebar_nav_order", DEFAULT_UI_SETTINGS["sidebar_nav_order"]),}[email protected]("/env/test")-async def test_env_config():- """- Test current environment configuration by validating all services.-- Returns the status of each service (LLM, Embedding, TTS).- """- results = {- "llm": {"status": "unknown", "model": None, "error": None},- "embedding": {"status": "unknown", "model": None, "error": None},- "tts": {"status": "unknown", "model": None, "error": None},- }-- # Test LLM configuration- try:- llm_config = get_llm_config()- results["llm"]["model"] = llm_config.model- results["llm"]["status"] = "configured"- except ValueError as e:- results["llm"]["status"] = "not_configured"- results["llm"]["error"] = str(e)- except Exception as e:- results["llm"]["status"] = "error"- results["llm"]["error"] = str(e)-- # Test Embedding configuration- try:- embedding_config = get_embedding_config()- results["embedding"]["model"] = embedding_config.model- results["embedding"]["status"] = "configured"- except ValueError as e:- results["embedding"]["status"] = "not_configured"- results["embedding"]["error"] = str(e)- except Exception as e:- results["embedding"]["status"] = "error"- results["embedding"]["error"] = str(e)-- # Test TTS configuration- try:- tts_config = get_tts_config()- results["tts"]["model"] = tts_config.get("model")- results["tts"]["status"] = "configured"- except ValueError as e:- results["tts"]["status"] = "not_configured"- results["tts"]["error"] = str(e)- except Exception as e:- results["tts"]["status"] = "error"- results["tts"]["error"] = str(e)-- return results--[email protected]("/env/test/{service}")-async def test_single_service(service: Literal["llm", "embedding", "tts"]):- """- Test a single service configuration with actual API call.-- Args:- service: The service to test (llm, embedding, tts)-- Returns:- Test result with status, model info, and response time.- """- import time-- result = {- "status": "unknown",- "model": None,- "error": None,- "response_time_ms": None,- "message": None,- }[email protected]("/sidebar/description")+async def update_sidebar_description(update: SidebarDescriptionUpdate):+ """Update sidebar description"""+ current_ui = load_ui_settings()+ current_ui["sidebar_description"] = update.description+ save_ui_settings(current_ui)+ return {"description": update.description}- start_time = time.time()- if service == "llm":- try:- from src.services.llm import complete as llm_complete-- llm_config = get_llm_config()- result["model"] = llm_config.model-- # Actually test the LLM with a simple prompt- response = await llm_complete(- model=llm_config.model,- prompt="Say 'OK' if you can hear me.",- system_prompt="You are a test assistant. Reply with just 'OK'.",- api_key=llm_config.api_key,- base_url=llm_config.base_url,- binding=llm_config.binding,- max_tokens=10,- )- result["status"] = "success"- result["message"] = (- f"Response: {response[:50]}..." if len(response) > 50 else f"Response: {response}"- )- except ValueError as e:- result["status"] = "not_configured"- result["error"] = str(e)- except Exception as e:- result["status"] = "error"- result["error"] = str(e)-- elif service == "embedding":- try:- from src.services.embedding import get_embedding_client-- embedding_config = get_embedding_config()- result["model"] = embedding_config.model-- # Actually test embedding with a simple text- embedding_client = get_embedding_client()- embeddings = await embedding_client.embed(["Test embedding"])- if embeddings and len(embeddings) > 0:- result["status"] = "success"- result["message"] = f"Dimension: {len(embeddings[0])}"- else:- result["status"] = "error"- result["error"] = "Empty embedding returned"- except ValueError as e:- result["status"] = "not_configured"- result["error"] = str(e)- except Exception as e:- result["status"] = "error"- result["error"] = str(e)-- elif service == "tts":- try:- tts_config = get_tts_config()- result["model"] = tts_config.get("model")-- # For TTS, just check if config is valid (actual audio test is expensive)- if tts_config.get("model") and tts_config.get("base_url"):- result["status"] = "success"- result["message"] = f"Voice: {tts_config.get('voice', 'alloy')}"- else:- result["status"] = "not_configured"- result["error"] = "Missing model or base_url"- except ValueError as e:- result["status"] = "not_configured"- result["error"] = str(e)- except Exception as e:- result["status"] = "error"- result["error"] = str(e)-- result["response_time_ms"] = int((time.time() - start_time) * 1000)- return result---# ==================== Web Search Configuration ====================--[email protected]("/web-search/config")-async def get_web_search_config():- """- Get current web search configuration.-- Returns:- {- "enabled": bool,- "provider": str,- "consolidation": str | None,- "consolidation_template": str | None,- "available_providers": list[str],- "config_source": "env" | "yaml" | "default"- }- """- try:- from src.tools.web_search import get_current_config-- return get_current_config()- except Exception as e:- raise HTTPException(- status_code=500, detail=f"Failed to get web search config: {str(e)}"- ) from e---# ==================== RAG Provider Configuration ====================--[email protected]("/rag/providers")-async def get_rag_providers():- """- Get list of available RAG providers.-- Returns:- {- "providers": [...],- "current": "lightrag"- }- """- try:- from src.tools.rag_tool import get_available_providers, get_current_provider-- providers = get_available_providers()- current = get_current_provider()-- return {"providers": providers, "current": current}- except Exception as e:- raise HTTPException(status_code=500, detail=f"Failed to get RAG providers: {str(e)}")[email protected]("/sidebar/nav-order")+async def update_sidebar_nav_order(update: SidebarNavOrderUpdate):+ """Update sidebar navigation order"""+ current_ui = load_ui_settings()+ current_ui["sidebar_nav_order"] = update.nav_order.model_dump()+ save_ui_settings(current_ui)+ return {"nav_order": update.nav_order.model_dump()}diff --git a/src/core/errors.py b/src/core/errors.pyindex 43b5b2a91..4c72b1a31 100644--- a/src/core/errors.py+++ b/src/core/errors.py@@ -19,9 +19,6 @@ class DeepTutorError(Exception):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.messageclass ConfigurationError(DeepTutorError):diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.pyindex 91c9a3984..9e6d963a5 100644--- a/src/knowledge/add_documents.py+++ b/src/knowledge/add_documents.py@@ -207,7 +207,7 @@ class DocumentAdder:raise ImportError("RAGAnything module not found.")# Pre-import progress stage if needed to avoid overhead in loop- ProgressStage = None+ ProgressStage: Any = Noneif self.progress_tracker:from src.knowledge.progress_tracker import ProgressStage@@ -467,11 +467,11 @@ class DocumentAdder:metadata = json.load(f)metadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")-+# Update RAG provider if specifiedif self.rag_provider:metadata["rag_provider"] = self.rag_provider-+history = metadata.get("update_history", [])history.append({diff --git a/src/knowledge/extract_numbered_items.py b/src/knowledge/extract_numbered_items.pyindex 25a2fd513..aa2111942 100644--- a/src/knowledge/extract_numbered_items.py+++ b/src/knowledge/extract_numbered_items.py@@ -26,6 +26,11 @@ from src.services.llm import get_llm_configload_dotenv(dotenv_path=".env", override=False)# Use project unified logging system+import logging as std_logging++# Logger can be either custom Logger or standard logging.Logger+logger: Any # Use Any to allow both types+try:from pathlib import Path@@ -42,11 +47,9 @@ try:logger = get_logger("Knowledge", log_dir=log_dir)except ImportError:# If import fails, use basic logging- import logging-- logger = logging.getLogger("knowledge_init.extract_items")- logging.basicConfig(- level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s"+ logger = std_logging.getLogger("knowledge_init.extract_items")+ std_logging.basicConfig(+ level=std_logging.INFO, format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s")@@ -355,7 +358,7 @@ async def _process_single_batch(total_batches: int,) -> dict[str, dict[str, Any]]:"""Asynchronously process a single batch"""- numbered_items = {}+ numbered_items: dict[str, dict[str, Any]] = {}# Build batch processing textbatch_texts = []@@ -559,11 +562,11 @@ async def extract_numbered_items_with_llm_async(Returns:Dict[identifier, {text: original text, type: type, page: page number}]"""- numbered_items = {}+ numbered_items: dict[str, dict[str, Any]] = {}# Create index mapping: from text_items index to full content_items index- text_item_to_full_index = {}- text_items = []+ text_item_to_full_index: dict[int, int] = {}+ text_items: list[dict[str, Any]] = []for idx, item in enumerate(content_items):item_type = item.get("type", "")@@ -665,7 +668,7 @@ async def extract_numbered_items_with_llm_async(numbered_items.update(result)# Count results- type_stats = {}+ type_stats: dict[str, int] = {}for item_data in numbered_items.values():item_type = item_data.get("type", "Unknown")type_stats[item_type] = type_stats.get(item_type, 0) + 1@@ -833,7 +836,7 @@ def process_content_list(logger.info(f"Results saved to: {output_file}")# Print statistics- type_counts = {}+ type_counts: dict[str, int] = {}for identifier in numbered_items.keys():# Identify equations: starting with parenthesis, e.g., (1.2.1)if identifier.startswith("(") and ")" in identifier:diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex e49ad0b29..7b7a39973 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -101,13 +101,13 @@ class KnowledgeBaseInitializer:metadata = json.load(f)else:metadata = {}-+metadata["rag_provider"] = providermetadata["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")-+with open(metadata_file, "w", encoding="utf-8") as f:json.dump(metadata, indent=2, ensure_ascii=False, fp=f)-+logger.info(f" ✓ Updated metadata with RAG provider: {provider}")except Exception as e:logger.warning(f"Failed to update metadata with provider: {e}")@@ -215,10 +215,10 @@ class KnowledgeBaseInitializer:if success:logger.info("✓ Document processing completed!")-+# Update metadata with the RAG provider usedself._update_metadata_with_provider(provider)-+self.progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,"Documents processed successfully",@@ -444,7 +444,7 @@ class KnowledgeBaseInitializer:# Read provider from metadata instead of env varprovider = self.rag_provider or os.getenv("RAG_PROVIDER", "raganything")-+# Try to read from metadata.json if availablemetadata_file = self.kb_dir / "metadata.json"if metadata_file.exists():diff --git a/src/knowledge/manager.py b/src/knowledge/manager.pyindex 68fefabf5..c03f37917 100644--- a/src/knowledge/manager.py+++ b/src/knowledge/manager.py@@ -208,12 +208,14 @@ class KnowledgeBaseManager:except Exception:content_lists_count = 0+ metadata = info["metadata"]+ rag_provider = metadata.get("rag_provider") if isinstance(metadata, dict) else Noneinfo["statistics"] = {"raw_documents": raw_count,"images": images_count,"content_lists": content_lists_count,"rag_initialized": rag_storage_dir.exists() and rag_storage_dir.is_dir(),- "rag_provider": info["metadata"].get("rag_provider"), # Add RAG provider info+ "rag_provider": rag_provider, # Add RAG provider info}# Try to get RAG statistics@@ -257,7 +259,9 @@ class KnowledgeBaseManager:passif rag_stats:- info["statistics"]["rag"] = rag_stats+ statistics = info["statistics"]+ if isinstance(statistics, dict):+ statistics["rag"] = rag_statsexcept Exception:passdiff --git a/src/logging/adapters/llamaindex.py b/src/logging/adapters/llamaindex.pyindex c77dfa555..e9173c960 100644--- a/src/logging/adapters/llamaindex.py+++ b/src/logging/adapters/llamaindex.py@@ -8,7 +8,7 @@ Forwards LlamaIndex logs to DeepTutor's unified logging system.from contextlib import contextmanagerimport logging-from typing import Optional+from typing import Any, Dict, List, Optional, Tupleclass LlamaIndexLogForwarder(logging.Handler):@@ -92,8 +92,8 @@ def LlamaIndexLogContext(min_level_int = getattr(logging, min_level.upper(), logging.INFO)# Store original state- original_states = []- forwarders = []+ original_states: List[Dict[str, Any]] = []+ forwarders: List[Tuple[logging.Logger, LlamaIndexLogForwarder]] = []for llama_logger in llama_loggers:original_states.append(diff --git a/src/logging/logger.py b/src/logging/logger.pyindex 9446424f3..78640595c 100644--- a/src/logging/logger.py+++ b/src/logging/logger.py@@ -19,7 +19,7 @@ import jsonimport loggingfrom pathlib import Pathimport sys-from typing import Any, Optional+from typing import Any, List, Optional, Unionfrom src.config.constants import LOG_SYMBOLS, PROJECT_ROOT@@ -135,7 +135,7 @@ class Logger:level: str = "INFO",console_output: bool = True,file_output: bool = True,- log_dir: Optional[str] = None,+ log_dir: Optional[Union[str, Path]] = None,):"""Initialize logger.@@ -155,16 +155,17 @@ class Logger:self.logger.setLevel(logging.DEBUG) # Capture all, filter at handlersself.logger.handlers.clear()# Setup log directory+ log_dir_path: Pathif log_dir is None:- log_dir = PROJECT_ROOT / "data" / "user" / "logs"+ log_dir_path = PROJECT_ROOT / "data" / "user" / "logs"else:- log_dir = Path(log_dir)+ log_dir_path = Path(log_dir) if isinstance(log_dir, str) else log_dir# If relative path, resolve it relative to project root- if not log_dir.is_absolute():- log_dir = PROJECT_ROOT / log_dir+ if not log_dir_path.is_absolute():+ log_dir_path = PROJECT_ROOT / log_dir_path- log_dir.mkdir(parents=True, exist_ok=True)- self.log_dir = log_dir+ log_dir_path.mkdir(parents=True, exist_ok=True)+ self.log_dir = log_dir_path# Console handlerif console_output:@@ -176,7 +177,7 @@ class Logger:# File handlerif file_output:timestamp = datetime.now().strftime("%Y%m%d")- log_file = log_dir / f"ai_tutor_{timestamp}.log"+ log_file = log_dir_path / f"ai_tutor_{timestamp}.log"file_handler = logging.FileHandler(log_file, encoding="utf-8")file_handler.setLevel(logging.DEBUG) # Log everything to file@@ -186,7 +187,7 @@ class Logger:self._log_file = log_file# For backwards compatibility with task-specific logging- self._task_handlers = []+ self._task_handlers: List[logging.Handler] = []# Display manager for TUI (optional, used by solve_agents)self.display_manager = None@@ -608,8 +609,8 @@ class Logger:self.logger.removeHandler(handler)-# Global logger registry-_loggers: dict[str, Logger] = {}+# Global logger registry - key is tuple of (name, level, console_output, file_output, log_dir)+_loggers: dict[tuple[str, str, bool, bool, Optional[str]], "Logger"] = {}def get_logger(diff --git a/src/logging/stats/llm_stats.py b/src/logging/stats/llm_stats.pyindex 60c612717..8070240e1 100644--- a/src/logging/stats/llm_stats.py+++ b/src/logging/stats/llm_stats.py@@ -83,7 +83,7 @@ class LLMStats:self.total_prompt_tokens = 0self.total_completion_tokens = 0self.total_cost = 0.0- self.model_used = None+ self.model_used: Optional[str] = Nonedef add_call(self,diff --git a/src/services/__init__.py b/src/services/__init__.pyindex 697828f7a..46700494e 100644--- a/src/services/__init__.py+++ b/src/services/__init__.py@@ -8,6 +8,7 @@ Unified service layer for DeepTutor providing:- RAG pipelines and components- Prompt management- TTS configuration+- Web Search providers- System setup utilities- Configuration loading@@ -17,6 +18,7 @@ Usage:from src.services.rag import get_pipelinefrom src.services.prompt import get_prompt_managerfrom src.services.tts import get_tts_config+ from src.services.search import web_searchfrom src.services.setup import init_user_directoriesfrom src.services.config import load_config_with_main@@ -35,9 +37,12 @@ Usage:# Promptpm = get_prompt_manager()prompts = pm.load_prompts("guide", "tutor_agent")++ # Search+ result = web_search("What is AI?")"""-from . import config, embedding, llm, prompt, rag, setup, tts+from . import config, embedding, llm, prompt, rag, search, setup, tts__all__ = ["llm",@@ -45,6 +50,7 @@ __all__ = ["rag","prompt","tts",+ "search","setup","config",]diff --git a/src/services/config/__init__.py b/src/services/config/__init__.pyindex e0ff7e991..5cc6a39cf 100644--- a/src/services/config/__init__.py+++ b/src/services/config/__init__.py@@ -2,32 +2,49 @@Configuration Service=====================-Unified configuration loading for all DeepTutor modules.+Provides two types of configuration:-Usage:- from src.services.config import load_config_with_main, PROJECT_ROOT+1. **YAML Configuration (loader.py)** - For application settings from config/*.yaml+ - PROJECT_ROOT, load_config_with_main, get_path_from_config, parse_language, get_agent_params- # Load module configuration- config = load_config_with_main("solve_config.yaml")-- # Get agent parameters- params = get_agent_params("guide")+2. **Unified Config Service (unified_config.py)** - For service configurations (LLM, Embedding, TTS, Search)+ - ConfigType, UnifiedConfigManager, get_config_manager+ - get_active_llm_config, get_active_embedding_config, get_active_tts_config, get_active_search_config"""+# Re-export everything from loader.py (existing functionality)from .loader import (PROJECT_ROOT,- _deep_merge,get_agent_params,get_path_from_config,load_config_with_main,parse_language,)+# Export new unified config service+from .unified_config import (+ ConfigType,+ UnifiedConfigManager,+ get_active_embedding_config,+ get_active_llm_config,+ get_active_search_config,+ get_active_tts_config,+ get_config_manager,+)+__all__ = [+ # From loader.py"PROJECT_ROOT","load_config_with_main","get_path_from_config","parse_language","get_agent_params",- "_deep_merge",+ # From unified_config.py+ "ConfigType",+ "UnifiedConfigManager",+ "get_config_manager",+ "get_active_llm_config",+ "get_active_embedding_config",+ "get_active_tts_config",+ "get_active_search_config",]diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.pynew file mode 100644index 000000000..787b494bb--- /dev/null+++ b/src/services/config/unified_config.py@@ -0,0 +1,450 @@+"""+Unified Configuration Manager+=============================++Manages configurations for LLM, Embedding, TTS, and Search services.+Supports both .env defaults and user-defined configurations.+"""++import json+import logging+import os+import uuid+from enum import Enum+from pathlib import Path+from typing import Any, Dict, List, Optional++from dotenv import load_dotenv++logger = logging.getLogger(__name__)++# Load environment variables+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent+load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)+load_dotenv(PROJECT_ROOT / ".env", override=False)++# Storage directory+SETTINGS_DIR = PROJECT_ROOT / "data" / "user" / "settings"+++class ConfigType(str, Enum):+ """Configuration types."""+ LLM = "llm"+ EMBEDDING = "embedding"+ TTS = "tts"+ SEARCH = "search"+++# Provider options for each service type+PROVIDER_OPTIONS = {+ ConfigType.LLM: ["openai", "anthropic", "azure_openai", "deepseek", "ollama", "lm_studio", "vllm"],+ ConfigType.EMBEDDING: ["openai", "azure_openai", "ollama", "jina", "cohere", "huggingface"],+ ConfigType.TTS: ["openai", "azure_openai"],+ ConfigType.SEARCH: ["perplexity", "tavily", "exa", "jina", "serper", "baidu"],+}++# Environment variable mappings for each service type+ENV_VAR_MAPPINGS = {+ ConfigType.LLM: {+ "provider": "LLM_BINDING",+ "base_url": "LLM_HOST",+ "api_key": "LLM_API_KEY",+ "model": "LLM_MODEL",+ "api_version": "LLM_API_VERSION",+ },+ ConfigType.EMBEDDING: {+ "provider": "EMBEDDING_BINDING",+ "base_url": "EMBEDDING_HOST",+ "api_key": "EMBEDDING_API_KEY",+ "model": "EMBEDDING_MODEL",+ "dimensions": "EMBEDDING_DIMENSION",+ "api_version": "EMBEDDING_API_VERSION",+ },+ ConfigType.TTS: {+ "provider": "TTS_BINDING",+ "base_url": "TTS_URL",+ "api_key": "TTS_API_KEY",+ "model": "TTS_MODEL",+ "voice": "TTS_VOICE",+ "api_version": "TTS_BINDING_API_VERSION",+ },+ ConfigType.SEARCH: {+ "provider": "SEARCH_PROVIDER",+ "api_key": "SEARCH_API_KEY", # Unified API key for all providers+ },+}+++def _resolve_env_value(value: Any) -> Any:+ """+ Resolve a value that may reference an environment variable.++ If value is {"use_env": "VAR_NAME"}, returns os.environ.get("VAR_NAME").+ Otherwise, returns the value as-is.+ """+ if isinstance(value, dict) and "use_env" in value:+ env_var = value["use_env"]+ return os.environ.get(env_var, "")+ return value+++def _get_env_value(env_var: str) -> Optional[str]:+ """Get and strip an environment variable value."""+ value = os.environ.get(env_var)+ if value:+ return value.strip().strip("\"'")+ return None+++class UnifiedConfigManager:+ """+ Manages configurations for all service types.++ Each service type has:+ - A "default" configuration that comes from .env (cannot be deleted)+ - User-defined configurations that can be added/edited/deleted+ - An "active" configuration that is currently in use+ """++ _instance: Optional["UnifiedConfigManager"] = None++ def __new__(cls):+ if cls._instance is None:+ cls._instance = super(UnifiedConfigManager, cls).__new__(cls)+ cls._instance._initialized = False+ return cls._instance++ def __init__(self):+ if getattr(self, "_initialized", False):+ return++ SETTINGS_DIR.mkdir(parents=True, exist_ok=True)+ self._initialized = True++ def _get_storage_path(self, config_type: ConfigType) -> Path:+ """Get the storage file path for a config type."""+ return SETTINGS_DIR / f"{config_type.value}_configs.json"++ def _load_configs(self, config_type: ConfigType) -> Dict[str, Any]:+ """Load configurations from storage."""+ path = self._get_storage_path(config_type)+ if path.exists():+ try:+ with open(path, "r", encoding="utf-8") as f:+ return json.load(f)+ except (json.JSONDecodeError, IOError) as e:+ logger.warning(f"Failed to load {config_type.value} configs: {e}")+ return {"configs": [], "active_id": "default"}++ def _save_configs(self, config_type: ConfigType, data: Dict[str, Any]) -> bool:+ """Save configurations to storage."""+ path = self._get_storage_path(config_type)+ try:+ with open(path, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ return True+ except IOError as e:+ logger.error(f"Failed to save {config_type.value} configs: {e}")+ return False++ def _build_default_config(self, config_type: ConfigType) -> Dict[str, Any]:+ """Build the default configuration from environment variables."""+ env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})++ if config_type == ConfigType.LLM:+ return {+ "id": "default",+ "name": "Default (from .env)",+ "is_default": True,+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "base_url": _get_env_value(env_mapping.get("base_url")) or "",+ "api_key": "***", # Hidden for security+ "model": _get_env_value(env_mapping.get("model")) or "",+ "api_version": _get_env_value(env_mapping.get("api_version")),+ }++ elif config_type == ConfigType.EMBEDDING:+ dim_str = _get_env_value(env_mapping.get("dimensions"))+ return {+ "id": "default",+ "name": "Default (from .env)",+ "is_default": True,+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "base_url": _get_env_value(env_mapping.get("base_url")) or "",+ "api_key": "***",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "dimensions": int(dim_str) if dim_str and dim_str.isdigit() else 3072,+ "api_version": _get_env_value(env_mapping.get("api_version")),+ }++ elif config_type == ConfigType.TTS:+ return {+ "id": "default",+ "name": "Default (from .env)",+ "is_default": True,+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "base_url": _get_env_value(env_mapping.get("base_url")) or "",+ "api_key": "***",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "voice": _get_env_value(env_mapping.get("voice")) or "alloy",+ "api_version": _get_env_value(env_mapping.get("api_version")),+ }++ elif config_type == ConfigType.SEARCH:+ provider = _get_env_value(env_mapping.get("provider")) or "perplexity"+ return {+ "id": "default",+ "name": "Default (from .env)",+ "is_default": True,+ "provider": provider,+ "api_key": "***",+ }++ return {"id": "default", "name": "Default (from .env)", "is_default": True}++ def _get_default_config_resolved(self, config_type: ConfigType) -> Dict[str, Any]:+ """Get the default configuration with actual values resolved (for internal use)."""+ env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})++ if config_type == ConfigType.LLM:+ return {+ "id": "default",+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "base_url": _get_env_value(env_mapping.get("base_url")) or "",+ "api_key": _get_env_value(env_mapping.get("api_key")) or "",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "api_version": _get_env_value(env_mapping.get("api_version")),+ }++ elif config_type == ConfigType.EMBEDDING:+ dim_str = _get_env_value(env_mapping.get("dimensions"))+ return {+ "id": "default",+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "base_url": _get_env_value(env_mapping.get("base_url")) or "",+ "api_key": _get_env_value(env_mapping.get("api_key")) or "",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "dimensions": int(dim_str) if dim_str and dim_str.isdigit() else 3072,+ "api_version": _get_env_value(env_mapping.get("api_version")),+ }++ elif config_type == ConfigType.TTS:+ return {+ "id": "default",+ "provider": _get_env_value(env_mapping.get("provider")) or "openai",+ "base_url": _get_env_value(env_mapping.get("base_url")) or "",+ "api_key": _get_env_value(env_mapping.get("api_key")) or "",+ "model": _get_env_value(env_mapping.get("model")) or "",+ "voice": _get_env_value(env_mapping.get("voice")) or "alloy",+ "api_version": _get_env_value(env_mapping.get("api_version")),+ }++ elif config_type == ConfigType.SEARCH:+ provider = _get_env_value(env_mapping.get("provider")) or "perplexity"+ return {+ "id": "default",+ "provider": provider,+ "api_key": _get_env_value(env_mapping.get("api_key")) or "",+ }++ return {"id": "default"}++ def _resolve_config(self, config: Dict[str, Any], config_type: ConfigType) -> Dict[str, Any]:+ """Resolve all {"use_env": ...} references in a configuration."""+ resolved = {}+ env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})++ for key, value in config.items():+ if isinstance(value, dict) and "use_env" in value:+ env_var = value["use_env"]+ resolved[key] = _get_env_value(env_var) or ""+ else:+ resolved[key] = value++ return resolved++ def get_provider_options(self, config_type: ConfigType) -> List[str]:+ """Get available provider options for a config type."""+ return PROVIDER_OPTIONS.get(config_type, [])++ def list_configs(self, config_type: ConfigType) -> List[Dict[str, Any]]:+ """+ List all configurations for a service type.+ Includes the default config (from .env) and user-defined configs.+ """+ data = self._load_configs(config_type)++ # Build default config+ default_config = self._build_default_config(config_type)++ # Get user configs+ user_configs = data.get("configs", [])++ # Mark active config+ active_id = data.get("active_id", "default")++ all_configs = [default_config] + user_configs+ for cfg in all_configs:+ cfg["is_active"] = cfg.get("id") == active_id++ return all_configs++ def get_config(self, config_type: ConfigType, config_id: str) -> Optional[Dict[str, Any]]:+ """Get a specific configuration by ID."""+ if config_id == "default":+ return self._build_default_config(config_type)++ data = self._load_configs(config_type)+ for cfg in data.get("configs", []):+ if cfg.get("id") == config_id:+ return cfg+ return None++ def get_active_config(self, config_type: ConfigType) -> Optional[Dict[str, Any]]:+ """+ Get the currently active configuration with all values resolved.+ This is used internally when services need actual configuration values.+ """+ data = self._load_configs(config_type)+ active_id = data.get("active_id", "default")++ if active_id == "default":+ return self._get_default_config_resolved(config_type)++ for cfg in data.get("configs", []):+ if cfg.get("id") == active_id:+ return self._resolve_config(cfg, config_type)++ # Fallback to default if active config not found+ return self._get_default_config_resolved(config_type)++ def add_config(self, config_type: ConfigType, config: Dict[str, Any]) -> Dict[str, Any]:+ """Add a new configuration."""+ data = self._load_configs(config_type)++ # Generate ID if not provided+ if "id" not in config:+ config["id"] = str(uuid.uuid4())[:8]++ # Ensure required fields+ config["is_default"] = False++ # Add to list+ data["configs"].append(config)+ self._save_configs(config_type, data)++ return config++ def update_config(self, config_type: ConfigType, config_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ """Update an existing configuration."""+ if config_id == "default":+ return None # Cannot update default config++ data = self._load_configs(config_type)++ for i, cfg in enumerate(data.get("configs", [])):+ if cfg.get("id") == config_id:+ # Update fields+ cfg.update(updates)+ cfg["id"] = config_id # Preserve ID+ cfg["is_default"] = False # Ensure it's not marked as default+ data["configs"][i] = cfg+ self._save_configs(config_type, data)+ return cfg++ return None++ def delete_config(self, config_type: ConfigType, config_id: str) -> bool:+ """Delete a configuration."""+ if config_id == "default":+ return False # Cannot delete default config++ data = self._load_configs(config_type)+ original_len = len(data.get("configs", []))+ data["configs"] = [c for c in data.get("configs", []) if c.get("id") != config_id]++ if len(data["configs"]) < original_len:+ # If deleted config was active, switch to default+ if data.get("active_id") == config_id:+ data["active_id"] = "default"+ self._save_configs(config_type, data)+ return True++ return False++ def set_active_config(self, config_type: ConfigType, config_id: str) -> bool:+ """Set a configuration as active."""+ data = self._load_configs(config_type)++ # Verify config exists+ if config_id != "default":+ found = any(c.get("id") == config_id for c in data.get("configs", []))+ if not found:+ return False++ data["active_id"] = config_id+ return self._save_configs(config_type, data)++ def get_env_status(self, config_type: ConfigType) -> Dict[str, bool]:+ """Check which environment variables are configured for a service type."""+ env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})+ status = {}++ for field, env_var in env_mapping.items():+ if not env_var.endswith("_key"): # Skip individual search provider keys+ status[field] = bool(_get_env_value(env_var))++ return status++ def get_default_config(self, config_type: ConfigType) -> Dict[str, Any]:+ """+ Get the default configuration with actual values resolved.+ Used for testing the default configuration.+ """+ return self._get_default_config_resolved(config_type)++ def resolve_config_env_values(self, config: Dict[str, Any]) -> Dict[str, Any]:+ """+ Resolve all {"use_env": "VAR_NAME"} references in a user configuration.+ Returns a copy with actual values from environment variables.+ """+ resolved = dict(config)+ for key, value in config.items():+ if isinstance(value, dict) and "use_env" in value:+ env_var = value["use_env"]+ resolved[key] = _get_env_value(env_var) or ""+ return resolved+++# Global instance+_config_manager: Optional[UnifiedConfigManager] = None+++def get_config_manager() -> UnifiedConfigManager:+ """Get the global config manager instance."""+ global _config_manager+ if _config_manager is None:+ _config_manager = UnifiedConfigManager()+ return _config_manager+++# Convenience functions for services+def get_active_llm_config() -> Optional[Dict[str, Any]]:+ """Get the active LLM configuration."""+ return get_config_manager().get_active_config(ConfigType.LLM)+++def get_active_embedding_config() -> Optional[Dict[str, Any]]:+ """Get the active embedding configuration."""+ return get_config_manager().get_active_config(ConfigType.EMBEDDING)+++def get_active_tts_config() -> Optional[Dict[str, Any]]:+ """Get the active TTS configuration."""+ return get_config_manager().get_active_config(ConfigType.TTS)+++def get_active_search_config() -> Optional[Dict[str, Any]]:+ """Get the active search configuration."""+ return get_config_manager().get_active_config(ConfigType.SEARCH)+diff --git a/src/services/embedding/__init__.py b/src/services/embedding/__init__.pyindex e06e05957..8e393cb45 100644--- a/src/services/embedding/__init__.py+++ b/src/services/embedding/__init__.py@@ -27,11 +27,6 @@ from .adapters import (from .client import EmbeddingClient, get_embedding_client, reset_embedding_clientfrom .config import EmbeddingConfig, get_embedding_configfrom .provider import get_embedding_provider_manager, reset_embedding_provider_manager-from .provider_config import (- EmbeddingProvider,- EmbeddingProviderConfigManager,- embedding_provider_config_manager,-)__all__ = ["EmbeddingClient",@@ -41,9 +36,6 @@ __all__ = ["reset_embedding_client","get_embedding_provider_manager","reset_embedding_provider_manager",- "EmbeddingProvider",- "EmbeddingProviderConfigManager",- "embedding_provider_config_manager","BaseEmbeddingAdapter","EmbeddingRequest","EmbeddingResponse",diff --git a/src/services/embedding/adapters/cohere.py b/src/services/embedding/adapters/cohere.pyindex ad674af8e..8753fe7a9 100644--- a/src/services/embedding/adapters/cohere.py+++ b/src/services/embedding/adapters/cohere.py@@ -116,9 +116,12 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):def get_model_info(self) -> Dict[str, Any]:model_info = self.MODELS_INFO.get(self.model, {})+ dimensions_list = model_info.get("dimensions", [])return {"model": self.model,"dimensions": model_info.get("default", self.dimensions),- "supports_variable_dimensions": len(model_info.get("dimensions", [])) > 1,+ "supports_variable_dimensions": len(dimensions_list) > 1+ if isinstance(dimensions_list, list)+ else False,"provider": "cohere",}diff --git a/src/services/embedding/config.py b/src/services/embedding/config.pyindex e1cbc15a8..36af8827b 100644--- a/src/services/embedding/config.py+++ b/src/services/embedding/config.py@@ -3,15 +3,19 @@ Embedding Configuration=======================Configuration management for embedding services.+Simplified version - loads from unified config service or falls back to .env."""from dataclasses import dataclass+import loggingimport osfrom pathlib import Pathfrom typing import Optionalfrom dotenv import load_dotenv+logger = logging.getLogger(__name__)+# Load environment variablesPROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parentload_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)@@ -63,82 +67,50 @@ def _to_bool(value: Optional[str], default: bool) -> bool:def get_embedding_config() -> EmbeddingConfig:"""- Load embedding configuration from environment variables or provider manager.+ Load embedding configuration.Priority:- 1. Active provider from embedding_providers.json+ 1. Active configuration from unified config service2. Environment variables (.env)- Strategy for environment variables:- 1. Read EMBEDDING_BINDING to determine active provider- 2. Try provider-specific variables first (e.g., JINA_EMBEDDING_MODEL)- 3. Fall back to generic EMBEDDING_* variables-- This allows easy switching between providers without changing all vars.-Returns:EmbeddingConfig: Configuration dataclassRaises:ValueError: If required configuration is missing"""- # 1. Try to get active provider from provider config manager+ # 1. Try to get active config from unified config servicetry:- from .provider_config import embedding_provider_config_manager+ from src.services.config import get_active_embedding_config- active_provider = embedding_provider_config_manager.get_active_provider()-- if active_provider:+ config = get_active_embedding_config()+ if config and config.get("model"):return EmbeddingConfig(- binding=active_provider.binding,- model=active_provider.model,- api_key=active_provider.api_key or "", # Empty string for local providers- base_url=active_provider.base_url,- api_version=getattr(active_provider, "api_version", None),- dim=active_provider.dimensions,- input_type=active_provider.input_type,- normalized=active_provider.normalized,- truncate=active_provider.truncate,+ binding=config.get("provider", "openai"),+ model=config["model"],+ api_key=config.get("api_key", ""),+ base_url=config.get("base_url"),+ api_version=config.get("api_version"),+ dim=config.get("dimensions", 3072),)+ except ImportError:+ # Unified config service not yet available, fall back to env+ passexcept Exception as e:- print(f"⚠️ Failed to load active embedding provider: {e}")+ logger.warning(f"Failed to load from unified config: {e}")# 2. Fallback to environment variablesbinding = _strip_value(os.getenv("EMBEDDING_BINDING", "openai"))-- # Provider-specific prefix mapping- prefix_map = {- "openai": "OPENAI",- "jina": "JINA",- "google": "GOOGLE",- "cohere": "COHERE",- "azure_openai": "AZURE",- "huggingface": "HF",- "ollama": "OLLAMA",- "lm_studio": "LM_STUDIO",- }-- prefix = prefix_map.get(binding, "")-- # Try provider-specific vars first, then fall back to generic- def get_with_fallback(var_name: str, generic_name: str) -> Optional[str]:- if prefix:- specific = _strip_value(os.getenv(f"{prefix}_{var_name}"))- if specific:- return specific- return _strip_value(os.getenv(generic_name))-- model = get_with_fallback("EMBEDDING_MODEL", "EMBEDDING_MODEL")- api_key = get_with_fallback("EMBEDDING_API_KEY", "EMBEDDING_API_KEY")- base_url = get_with_fallback("EMBEDDING_HOST", "EMBEDDING_HOST")- api_version = get_with_fallback("EMBEDDING_API_VERSION", "EMBEDDING_API_VERSION")- dim_str = get_with_fallback("EMBEDDING_DIM", "EMBEDDING_DIM")+ model = _strip_value(os.getenv("EMBEDDING_MODEL"))+ api_key = _strip_value(os.getenv("EMBEDDING_API_KEY"))+ base_url = _strip_value(os.getenv("EMBEDDING_HOST"))+ api_version = _strip_value(os.getenv("EMBEDDING_API_VERSION"))+ dim_str = _strip_value(os.getenv("EMBEDDING_DIMENSION"))# Strict mode: Model is requiredif not model:raise ValueError(- f"Error: EMBEDDING_MODEL not set for binding '{binding}'. "- f"Set either {prefix}_EMBEDDING_MODEL or EMBEDDING_MODEL in .env file"+ "EMBEDDING_MODEL not set. Please configure it in .env file or add a configuration in Settings")# Check if API key is required@@ -148,13 +120,11 @@ def get_embedding_config() -> EmbeddingConfig:if requires_key and not api_key:raise ValueError(- f"Error: EMBEDDING_API_KEY not set for binding '{binding}'. "- f"Set {prefix}_EMBEDDING_API_KEY or EMBEDDING_API_KEY in .env file"+ "EMBEDDING_API_KEY not set. Please configure it in .env file or add a configuration in Settings")if not base_url:raise ValueError(- f"Error: EMBEDDING_HOST not set for binding '{binding}'. "- f"Set {prefix}_EMBEDDING_HOST or EMBEDDING_HOST in .env file"+ "EMBEDDING_HOST not set. Please configure it in .env file or add a configuration in Settings")# Get optional configuration@@ -172,7 +142,7 @@ def get_embedding_config() -> EmbeddingConfig:return EmbeddingConfig(binding=binding,model=model,- api_key=api_key,+ api_key=api_key or "",base_url=base_url,api_version=api_version,dim=dim,diff --git a/src/services/embedding/provider.py b/src/services/embedding/provider.pyindex 8bc199a1b..84e7967ee 100644--- a/src/services/embedding/provider.py+++ b/src/services/embedding/provider.py@@ -7,7 +7,7 @@ Provides centralized configuration and adapter selection."""import logging-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, Typefrom .adapters.base import BaseEmbeddingAdapterfrom .adapters.cohere import CohereEmbeddingAdapter@@ -29,7 +29,7 @@ class EmbeddingProviderManager:"""# Mapping of binding names to adapter classes- ADAPTER_MAPPING = {+ ADAPTER_MAPPING: Dict[str, Type[BaseEmbeddingAdapter]] = {"openai": OpenAICompatibleEmbeddingAdapter,"azure_openai": OpenAICompatibleEmbeddingAdapter,"jina": JinaEmbeddingAdapter,diff --git a/src/services/embedding/provider_config.py b/src/services/embedding/provider_config.pydeleted file mode 100644index eb52d50fa..000000000--- a/src/services/embedding/provider_config.py+++ /dev/null@@ -1,184 +0,0 @@-"""-Embedding Provider Configuration Management-============================================--Manages embedding provider configurations, persisting them to a JSON file.-Similar to LLM provider management but for embedding services.-"""--import json-from pathlib import Path-from typing import Any, Dict, List, Optional--from pydantic import BaseModel, ConfigDict, Field--USER_DATA_DIR = Path("./data/user")-PROVIDERS_FILE = USER_DATA_DIR / "embedding_providers.json"---class EmbeddingProvider(BaseModel):- """- Configuration model for a single embedding provider.- """-- name: str = Field(..., description="Unique name for the provider configuration")- binding: str = Field(..., description="Provider type (openai, jina, cohere, ollama, etc.)")- base_url: str = Field(..., description="API endpoint URL")- api_key: str = Field(default="", description="API Key (optional for local providers)")- api_version: Optional[str] = Field(- default=None, description="API Version (required for Azure OpenAI)"- )- model: str = Field(..., description="Model name to use")- dimensions: int = Field(..., description="Embedding vector dimensions")- is_active: bool = Field(default=False, description="Whether this provider is currently active")-- # Optional advanced settings for some specific providers, view each api references for details- input_type: Optional[str] = Field(- default=None, description="Input type for task-aware embeddings"- )- normalized: bool = Field(default=True, description="L2 normalization")- truncate: bool = Field(default=True, description="Truncate long texts")-- model_config = ConfigDict(populate_by_name=True)---class EmbeddingProviderConfigManager:- """- Manages embedding provider configurations, persisting them to a JSON file.- """-- def __init__(self, storage_path: Path = PROVIDERS_FILE):- self.storage_path = storage_path- self._ensure_storage_exists()-- def _ensure_storage_exists(self):- """Ensure the storage directory and file exist."""- if not self.storage_path.parent.exists():- self.storage_path.parent.mkdir(parents=True, exist_ok=True)-- if not self.storage_path.exists():- self._save_providers([])-- def _load_providers(self) -> List[Dict[str, Any]]:- """Load raw provider data from JSON."""- try:- with open(self.storage_path, "r", encoding="utf-8") as f:- return json.load(f)- except (json.JSONDecodeError, FileNotFoundError):- return []-- 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:- json.dump(providers, f, indent=2, ensure_ascii=False)-- def list_providers(self) -> List[EmbeddingProvider]:- """List all configured providers."""- raw_list = self._load_providers()- return [EmbeddingProvider(**p) for p in raw_list]-- def get_provider(self, name: str) -> Optional[EmbeddingProvider]:- """Get a specific provider by name."""- providers = self.list_providers()- for p in providers:- if p.name == name:- return p- return None-- def get_active_provider(self) -> Optional[EmbeddingProvider]:- """Get the currently active provider."""- providers = self.list_providers()- for p in providers:- if p.is_active:- return p- return None-- def add_provider(self, provider: EmbeddingProvider) -> EmbeddingProvider:- """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")-- # 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-- providers.append(provider)- self._save_providers([p.model_dump() for p in providers])- return provider-- def update_provider(self, name: str, updates: Dict[str, Any]) -> Optional[EmbeddingProvider]:- """Update an existing provider."""- providers = self.list_providers()- target_idx = -1-- for i, p in enumerate(providers):- if p.name == name:- target_idx = i- break-- if target_idx == -1:- return None-- # Update fields- current_data = providers[target_idx].model_dump()- current_data.update(updates)- updated_provider = EmbeddingProvider(**current_data)-- # Handle activation logic if changing is_active- if updated_provider.is_active:- for i, p in enumerate(providers):- if i != target_idx:- p.is_active = False-- providers[target_idx] = updated_provider- self._save_providers([p.model_dump() for p in providers])- return updated_provider-- def delete_provider(self, name: str) -> bool:- """Delete a provider."""- providers = self.list_providers()- initial_len = len(providers)- providers = [p for p in providers if p.name != name]-- if len(providers) < initial_len:- self._save_providers([p.model_dump() for p in providers])- return True- return False-- def set_active_provider(self, name: str) -> Optional[EmbeddingProvider]:- """Set a provider as active and deactivate others."""- providers = self.list_providers()- activated = None-- found = False- for p in providers:- if p.name == name:- p.is_active = True- activated = p- found = True- else:- p.is_active = False-- if found:- self._save_providers([p.model_dump() for p in providers])- return activated- return None---# Global instance-embedding_provider_config_manager = EmbeddingProviderConfigManager()---__all__ = [- "EmbeddingProvider",- "EmbeddingProviderConfigManager",- "embedding_provider_config_manager",-]diff --git a/src/services/llm/__init__.py b/src/services/llm/__init__.pyindex 0b82a6937..0beb248ca 100644--- a/src/services/llm/__init__.py+++ b/src/services/llm/__init__.py@@ -19,7 +19,7 @@ CloudProvider LocalProviderFeatures:- Unified interface for all LLM providers (cloud + local)- Automatic retry with exponential backoff-- Smart routing based on URL/configuration+- Smart routing based on URL detection- Provider capability detectionUsage:@@ -43,15 +43,8 @@ Usage:from src.services.llm import get_llm_config, LLMConfigconfig = get_llm_config()- # Provider management- from src.services.llm import provider_manager, LLMProvider- providers = provider_manager.list_providers()-# URL utilities for local LLM serversfrom src.services.llm import sanitize_url, is_local_llm_server-- # Mode information- from src.services.llm import LLMMode, get_llm_mode, get_mode_info"""# Also expose the providers for direct access if needed@@ -91,20 +84,11 @@ from .factory import (DEFAULT_MAX_RETRIES,DEFAULT_RETRY_DELAY,LOCAL_PROVIDER_PRESETS,- LLMMode,complete,fetch_models,- get_llm_mode,- get_mode_info,get_provider_presets,stream,)-from .provider import (- LLMProvider,- LLMProviderManager,- ProviderType,- provider_manager,-)from .utils import (build_auth_headers,build_chat_url,@@ -145,9 +129,6 @@ __all__ = ["LLMAuthenticationError","LLMModelNotFoundError",# Factory (main API)- "LLMMode",- "get_llm_mode",- "get_mode_info","complete","stream","fetch_models",@@ -161,11 +142,6 @@ __all__ = [# Providers"cloud_provider","local_provider",- # Provider Management- "ProviderType",- "LLMProvider",- "LLMProviderManager",- "provider_manager",# Utils"sanitize_url","is_local_llm_server",diff --git a/src/services/llm/config.py b/src/services/llm/config.pyindex 3b6440dfc..e071cc6a7 100644--- a/src/services/llm/config.py+++ b/src/services/llm/config.py@@ -4,11 +4,7 @@ LLM Configuration=================Configuration management for LLM services.--Supports multiple deployment modes:-- api: Cloud API providers only (OpenAI, Anthropic, etc.)-- local: Local/self-hosted LLM servers only (Ollama, LM Studio, etc.)-- hybrid: Both API and local, uses active provider (default)+Simplified version - loads from unified config service or falls back to .env."""from dataclasses import dataclass@@ -16,7 +12,7 @@ import loggingimport osfrom pathlib import Pathimport re-from typing import Literal, Optional+from typing import Optionalfrom dotenv import load_dotenv@@ -29,11 +25,6 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parentload_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)load_dotenv(PROJECT_ROOT / ".env", override=False)-# LLM deployment modes-LLM_MODE_API = "api"-LLM_MODE_LOCAL = "local"-LLM_MODE_HYBRID = "hybrid"-@dataclassclass LLMConfig:@@ -46,7 +37,6 @@ class LLMConfig:api_version: Optional[str] = Nonemax_tokens: int = 4096temperature: float = 0.7- provider_type: Literal["api", "local"] = "api" # Track if this is API or local configdef _strip_value(value: Optional[str]) -> Optional[str]:@@ -56,18 +46,6 @@ def _strip_value(value: Optional[str]) -> Optional[str]:return value.strip().strip("\"'")-def _get_llm_mode_str() -> str:- """- Get the current LLM deployment mode from environment (internal use).-- For external use, import get_llm_mode from factory.py which returns LLMMode enum.-- Returns:- str: 'api', 'local', or 'hybrid' (default)- """- 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"))@@ -79,26 +57,11 @@ def _get_llm_config_from_env() -> LLMConfig:# Validate required configurationif 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"+ "LLM_MODEL not set, please configure it in .env file or add a configuration in Settings")if not base_url:raise LLMConfigError(- "LLM_HOST not set, please configure it in .env file or activate a provider"+ "LLM_HOST not set, please configure it in .env file or add a configuration in Settings")return LLMConfig(@@ -107,60 +70,41 @@ def _get_llm_config_from_env() -> LLMConfig: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.-- 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)+ Load LLM configuration.Priority:- 1. Active provider from llm_providers.json (if mode compatible)+ 1. Active configuration from unified config service2. Environment variables (.env)Returns:LLMConfig: Configuration dataclassRaises:- ValueError: If required configuration is missing+ LLMConfigError: If required configuration is missing"""- mode = _get_llm_mode_str()-- # 1. Try to get active provider from provider manager+ # 1. Try to get active config from unified config servicetry:- from .provider import provider_manager-- active_provider = provider_manager.get_active_provider()-- 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"),- )+ from src.services.config import get_active_llm_config++ config = get_active_llm_config()+ if config:+ return LLMConfig(+ binding=config.get("provider", "openai"),+ model=config["model"],+ api_key=config.get("api_key", ""),+ base_url=config.get("base_url"),+ api_version=config.get("api_version"),+ )+ except ImportError:+ # Unified config service not yet available, fall back to env+ passexcept Exception as e:- logger.warning(f"Failed to load active provider: {e}")+ logger.warning(f"Failed to load from unified config: {e}")# 2. Fallback to environment variablesreturn _get_llm_config_from_env()@@ -170,56 +114,31 @@ async def get_llm_config_async() -> LLMConfig:"""Async version of get_llm_config for non-blocking configuration loading.- Load LLM configuration from environment variables or provider manager.-- 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)-- Priority:- 1. Active provider from llm_providers.json (if mode compatible)- 2. Environment variables (.env)-Returns:LLMConfig: Configuration dataclassRaises:- ValueError: If required configuration is missing+ LLMConfigError: If required configuration is missing"""- mode = _get_llm_mode_str()-- # 1. Try to get active provider from provider manager+ # 1. Try to get active config from unified config servicetry:- 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"),- )+ from src.services.config import get_active_llm_config++ config = get_active_llm_config()+ if config:+ return LLMConfig(+ binding=config.get("provider", "openai"),+ model=config["model"],+ api_key=config.get("api_key", ""),+ base_url=config.get("base_url"),+ api_version=config.get("api_version"),+ )+ except ImportError:+ passexcept Exception as e:- logger.warning(f"Failed to load active provider: {e}")+ logger.warning(f"Failed to load from unified config: {e}")- # 2. Fallback to environment variables (no async needed since these are env vars)+ # 2. Fallback to environment variablesreturn _get_llm_config_from_env()@@ -260,21 +179,12 @@ def get_token_limit_kwargs(model: str, max_tokens: int) -> dict:"""Get the appropriate token limit parameter for the model.- Newer OpenAI models (gpt-5.x, o1, o3, gpt-4o) require max_completion_tokens- instead of max_tokens. This function automatically selects the correct parameter.-Args:model: The model namemax_tokens: The desired token limitReturns:Dictionary with either {"max_tokens": value} or {"max_completion_tokens": value}-- Example:- >>> get_token_limit_kwargs("gpt-4", 4096)- {"max_tokens": 4096}- >>> get_token_limit_kwargs("gpt-5.2", 4096)- {"max_completion_tokens": 4096}"""if uses_max_completion_tokens(model):return {"max_completion_tokens": max_tokens}@@ -287,7 +197,4 @@ __all__ = ["get_llm_config_async","uses_max_completion_tokens","get_token_limit_kwargs",- "LLM_MODE_API",- "LLM_MODE_LOCAL",- "LLM_MODE_HYBRID",]diff --git a/src/services/llm/error_mapping.py b/src/services/llm/error_mapping.pyindex 4ef511dc2..05dbc7e66 100644--- a/src/services/llm/error_mapping.py+++ b/src/services/llm/error_mapping.py@@ -8,6 +8,15 @@ from dataclasses import dataclassimport loggingfrom typing import Callable, List, Optional, Type+# Import unified exceptions from exceptions.py+from .exceptions import (+ LLMAPIError,+ LLMAuthenticationError,+ LLMError,+ LLMRateLimitError,+ ProviderContextWindowError,+)+try:import openai # type: ignore@@ -20,37 +29,6 @@ except ImportError: # pragma: no coverlogger = 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]diff --git a/src/services/llm/factory.py b/src/services/llm/factory.pyindex c1282674f..875fa0656 100644--- a/src/services/llm/factory.py+++ b/src/services/llm/factory.py@@ -4,7 +4,7 @@ LLM Factory - Central Hub for LLM CallsThis module serves as the central hub for all LLM calls in DeepTutor.It provides a unified interface for agents to call LLMs, routing requests-to the appropriate provider (cloud or local) based on configuration.+to the appropriate provider (cloud or local) based on URL detection.Architecture:Agents (ChatAgent, GuideAgent, etc.)@@ -20,10 +20,9 @@ CloudProvider LocalProvider↓ ↓OpenAI/DeepSeek/etc LM Studio/Ollama/etc-Deployment Modes (LLM_MODE env var):-- api: Only use cloud API providers-- local: Only use local/self-hosted LLM servers-- hybrid: Use whatever is active (default)+Routing:+- Automatically routes to local_provider for local URLs (localhost, 127.0.0.1, etc.)+- Routes to cloud_provider for all other URLsRetry Mechanism:- Automatic retry with exponential backoff for transient errors@@ -32,8 +31,6 @@ Retry Mechanism:"""import asyncio-from enum import Enum-import osfrom typing import Any, AsyncGenerator, Dict, List, Optionalimport tenacity@@ -48,7 +45,6 @@ from .exceptions import (LLMRateLimitError,LLMTimeoutError,)-from .provider import provider_managerfrom .utils import is_local_llm_server# Initialize logger@@ -103,96 +99,17 @@ def _is_retriable_error(error: Exception) -> bool:return True-class LLMMode(str, Enum):- """LLM deployment mode."""-- API = "api" # Cloud API only- LOCAL = "local" # Local/self-hosted only- HYBRID = "hybrid" # Both, use active provider---def get_llm_mode() -> LLMMode:- """- Get the current LLM deployment mode from environment.-- Returns:- LLMMode: Current deployment mode (defaults to hybrid)- """- mode = os.getenv("LLM_MODE", "hybrid").lower()- if mode == "api":- return LLMMode.API- elif mode == "local":- return LLMMode.LOCAL- return LLMMode.HYBRID--def _should_use_local(base_url: Optional[str]) -> bool:"""- Determine if we should use the local provider based on URL and mode.+ Determine if we should use the local provider based on URL.Args:base_url: The base URL to checkReturns:- True if local provider should be used- """- mode = get_llm_mode()-- if mode == LLMMode.API:- return False- elif mode == LLMMode.LOCAL:- return True- else: # HYBRID- return is_local_llm_server(base_url) if base_url else False---def get_mode_info() -> Dict[str, Any]:- """- Get information about the current LLM configuration mode.-- Returns:- Dict containing:- - mode: Current deployment mode- - active_provider: Active provider info (if any)- - env_configured: Whether env vars are properly configured- - effective_source: Which config source is being used+ True if local provider should be used (localhost, 127.0.0.1, etc.)"""- 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))- except ValueError:- env_config = None- env_configured = False-- # Determine effective source- effective_source = "env"- if active_provider:- provider_is_local = active_provider.provider_type == "local"- if mode == LLMMode.HYBRID:- effective_source = "provider"- elif mode == LLMMode.API and not provider_is_local:- effective_source = "provider"- elif mode == LLMMode.LOCAL and provider_is_local:- effective_source = "provider"-- return {- "mode": mode.value,- "active_provider": (- {- "name": active_provider.name,- "model": active_provider.model,- "provider_type": active_provider.provider_type,- "binding": active_provider.binding,- }- if active_provider- else None- ),- "env_configured": env_configured,- "effective_source": effective_source,- }+ return is_local_llm_server(base_url) if base_url else Falseasync def complete(@@ -520,9 +437,6 @@ def get_provider_presets() -> Dict[str, Any]:__all__ = [- "LLMMode",- "get_llm_mode",- "get_mode_info","complete","stream","fetch_models",diff --git a/src/services/llm/provider.py b/src/services/llm/provider.pydeleted file mode 100644index 9561e8ac2..000000000--- a/src/services/llm/provider.py+++ /dev/null@@ -1,206 +0,0 @@-"""-LLM Provider Management-=======================--Manages LLM provider configurations, persisting them to a JSON file.-Supports both API (cloud) and Local (self-hosted) providers.-"""--import asyncio-from enum import Enum-import json-from pathlib import Path-from typing import Any, Dict, List, Literal, Optional--from pydantic import BaseModel, ConfigDict, Field--# Define storage path-USER_DATA_DIR = Path("./data/user")-PROVIDERS_FILE = USER_DATA_DIR / "llm_providers.json"---class ProviderType(str, Enum):- """Type of LLM provider."""-- API = "api" # Cloud API providers (OpenAI, Anthropic, DeepSeek, etc.)- LOCAL = "local" # Local/self-hosted (Ollama, LM Studio, vLLM, etc.)---class LLMProvider(BaseModel):- """- Configuration model for a single LLM provider.-- Supports both API (cloud) and Local (self-hosted) providers.- """-- name: str = Field(..., description="Unique name for the provider configuration")- binding: str = Field(..., description="Provider type (e.g., openai, azure_openai, ollama)")- base_url: str = Field(..., description="API endpoint URL")- api_key: str = Field(default="", description="API Key (optional for local providers)")- api_version: Optional[str] = Field(- default=None, description="API Version (required for Azure OpenAI)"- )- model: str = Field(..., description="Model name to use")- is_active: bool = Field(default=False, description="Whether this provider is currently active")- provider_type: Literal["api", "local"] = Field(- default="local",- description="Provider type: 'api' for cloud services, 'local' for self-hosted",- )- requires_key: bool = Field(- default=False,- description="Whether this provider requires an API key",- )-- model_config = ConfigDict(populate_by_name=True)---class LLMProviderManager:- """- Manages LLM provider configurations, persisting them to a JSON file.- """-- def __init__(self, storage_path: Path = PROVIDERS_FILE):- self.storage_path = storage_path- self._ensure_storage_exists()-- def _ensure_storage_exists(self):- """Ensure the storage directory and file exist."""- if not self.storage_path.parent.exists():- self.storage_path.parent.mkdir(parents=True, exist_ok=True)-- if not self.storage_path.exists():- self._save_providers([])-- def _load_providers(self) -> List[Dict[str, Any]]:- """Load raw provider data from JSON."""- try:- with open(self.storage_path, "r", encoding="utf-8") as f:- return json.load(f)- 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:- json.dump(providers, f, indent=2, ensure_ascii=False)-- def list_providers(self) -> List[LLMProvider]:- """List all configured providers."""- raw_list = self._load_providers()- return [LLMProvider(**p) for p in raw_list]-- def get_provider(self, name: str) -> Optional[LLMProvider]:- """Get a specific provider by name."""- providers = self.list_providers()- for p in providers:- if p.name == name:- return p- return None-- def get_active_provider(self) -> Optional[LLMProvider]:- """Get the currently active provider."""- providers = self.list_providers()- for p in providers:- if p.is_active:- return p- return 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 unique- if any(p.name == provider.name for p in providers):- raise ValueError(f"Provider with name '{provider.name}' already exists")-- # If the new provider is active, deactivate all others- if provider.is_active:- for p in providers:- p.is_active = False-- providers.append(provider)- self._save_providers([p.model_dump() for p in providers])- return provider-- def update_provider(self, name: str, updates: Dict[str, Any]) -> Optional[LLMProvider]:- """Update an existing provider."""- providers = self.list_providers()- target_idx = -1-- for i, p in enumerate(providers):- if p.name == name:- target_idx = i- break-- if target_idx == -1:- return None-- # Update fields- current_data = providers[target_idx].model_dump()- current_data.update(updates)- updated_provider = LLMProvider(**current_data)-- # Handle activation logic if changing is_active- if updated_provider.is_active:- for i, p in enumerate(providers):- if i != target_idx:- p.is_active = False-- providers[target_idx] = updated_provider- self._save_providers([p.model_dump() for p in providers])- return updated_provider-- def delete_provider(self, name: str) -> bool:- """Delete a provider."""- providers = self.list_providers()- initial_len = len(providers)- providers = [p for p in providers if p.name != name]-- if len(providers) < initial_len:- self._save_providers([p.model_dump() for p in providers])- return True- return False-- def set_active_provider(self, name: str) -> Optional[LLMProvider]:- """Set a provider as active and deactivate others."""- providers = self.list_providers()- activated = None-- found = False- for p in providers:- if p.name == name:- p.is_active = True- activated = p- found = True- else:- p.is_active = False-- if found:- self._save_providers([p.model_dump() for p in providers])- return activated- return None---# Global instance-provider_manager = LLMProviderManager()---__all__ = [- "ProviderType",- "LLMProvider",- "LLMProviderManager",- "provider_manager",-]diff --git a/src/services/llm/providers/open_ai.py b/src/services/llm/providers/open_ai.pyindex d9ca71278..6dcfa7aaa 100644--- a/src/services/llm/providers/open_ai.py+++ b/src/services/llm/providers/open_ai.py@@ -54,7 +54,7 @@ class OpenAIProvider(BaseLLMProvider):return await self.execute_with_retry(_call_api)- async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator:+ async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator: # type: ignore[override]model = kwargs.pop("model", None) or self.config.model_name or "gpt-4o"async def _create_stream():diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.pyindex 4028bee64..fc8467eaa 100644--- a/src/services/rag/components/indexers/graph.py+++ b/src/services/rag/components/indexers/graph.py@@ -51,15 +51,15 @@ class GraphIndexer(BaseComponent):sys.path.insert(0, str(raganything_path))try:- from raganything import RAGAnything, RAGAnythingConfigfrom openai import AsyncOpenAI+ from raganything import RAGAnything, RAGAnythingConfigfrom src.services.embedding import get_embedding_clientfrom src.services.llm import get_llm_clientllm_client = get_llm_client()embed_client = get_embedding_client()-+# Create AsyncOpenAI client directlyopenai_client = AsyncOpenAI(api_key=llm_client.config.api_key,@@ -71,28 +71,37 @@ class GraphIndexer(BaseComponent):"""Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""if history_messages is None:history_messages = []-+# Build messagesmessages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})messages.extend(history_messages)messages.append({"role": "user", "content": prompt})-+# Whitelist only valid OpenAI parametersvalid_params = {- 'temperature', 'top_p', 'n', 'stream', 'stop', 'max_tokens',- 'presence_penalty', 'frequency_penalty', 'logit_bias', 'user', 'seed'+ "temperature",+ "top_p",+ "n",+ "stream",+ "stop",+ "max_tokens",+ "presence_penalty",+ "frequency_penalty",+ "logit_bias",+ "user",+ "seed",}clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}-+# Call OpenAI API directly (async)response = await openai_client.chat.completions.create(model=llm_client.config.model,messages=messages,**clean_kwargs,)-+return response.choices[0].message.contentconfig = RAGAnythingConfig(diff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.pyindex df5da8804..63da12298 100644--- a/src/services/rag/components/indexers/lightrag.py+++ b/src/services/rag/components/indexers/lightrag.py@@ -60,7 +60,7 @@ class LightRAGIndexer(BaseComponent):llm_client = get_llm_client()embed_client = get_embedding_client()-+# Create AsyncOpenAI client directlyopenai_client = AsyncOpenAI(api_key=llm_client.config.api_key,@@ -72,28 +72,37 @@ class LightRAGIndexer(BaseComponent):"""Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""if history_messages is None:history_messages = []-+# Build messagesmessages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})messages.extend(history_messages)messages.append({"role": "user", "content": prompt})-+# Whitelist only valid OpenAI parametersvalid_params = {- 'temperature', 'top_p', 'n', 'stream', 'stop', 'max_tokens',- 'presence_penalty', 'frequency_penalty', 'logit_bias', 'user', 'seed'+ "temperature",+ "top_p",+ "n",+ "stream",+ "stop",+ "max_tokens",+ "presence_penalty",+ "frequency_penalty",+ "logit_bias",+ "user",+ "seed",}clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}-+# Call OpenAI API directly (async)response = await openai_client.chat.completions.create(model=llm_client.config.model,messages=messages,**clean_kwargs,)-+return response.choices[0].message.content# Create pure LightRAG instance (no multimodal)diff --git a/src/services/rag/components/retrievers/hybrid.py b/src/services/rag/components/retrievers/hybrid.pyindex d4f3aacf9..a594cb32b 100644--- a/src/services/rag/components/retrievers/hybrid.py+++ b/src/services/rag/components/retrievers/hybrid.py@@ -50,15 +50,15 @@ class HybridRetriever(BaseComponent):sys.path.insert(0, str(raganything_path))try:- from raganything import RAGAnything, RAGAnythingConfigfrom openai import AsyncOpenAI+ from raganything import RAGAnything, RAGAnythingConfigfrom src.services.embedding import get_embedding_clientfrom src.services.llm import get_llm_clientllm_client = get_llm_client()embed_client = get_embedding_client()-+# Create AsyncOpenAI client directlyopenai_client = AsyncOpenAI(api_key=llm_client.config.api_key,@@ -70,28 +70,37 @@ class HybridRetriever(BaseComponent):"""Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""if history_messages is None:history_messages = []-+# Build messagesmessages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})messages.extend(history_messages)messages.append({"role": "user", "content": prompt})-+# Whitelist only valid OpenAI parametersvalid_params = {- 'temperature', 'top_p', 'n', 'stream', 'stop', 'max_tokens',- 'presence_penalty', 'frequency_penalty', 'logit_bias', 'user', 'seed'+ "temperature",+ "top_p",+ "n",+ "stream",+ "stop",+ "max_tokens",+ "presence_penalty",+ "frequency_penalty",+ "logit_bias",+ "user",+ "seed",}clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}-+# Call OpenAI API directly (async)response = await openai_client.chat.completions.create(model=llm_client.config.model,messages=messages,**clean_kwargs,)-+return response.choices[0].message.contentconfig = RAGAnythingConfig(diff --git a/src/services/rag/components/retrievers/lightrag.py b/src/services/rag/components/retrievers/lightrag.pyindex 6437653db..c945a3617 100644--- a/src/services/rag/components/retrievers/lightrag.py+++ b/src/services/rag/components/retrievers/lightrag.py@@ -59,7 +59,7 @@ class LightRAGRetriever(BaseComponent):llm_client = get_llm_client()embed_client = get_embedding_client()-+# Create AsyncOpenAI client directlyopenai_client = AsyncOpenAI(api_key=llm_client.config.api_key,@@ -71,28 +71,37 @@ class LightRAGRetriever(BaseComponent):"""Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""if history_messages is None:history_messages = []-+# Build messagesmessages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})messages.extend(history_messages)messages.append({"role": "user", "content": prompt})-+# Whitelist only valid OpenAI parametersvalid_params = {- 'temperature', 'top_p', 'n', 'stream', 'stop', 'max_tokens',- 'presence_penalty', 'frequency_penalty', 'logit_bias', 'user', 'seed'+ "temperature",+ "top_p",+ "n",+ "stream",+ "stop",+ "max_tokens",+ "presence_penalty",+ "frequency_penalty",+ "logit_bias",+ "user",+ "seed",}clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}-+# Call OpenAI API directly (async)response = await openai_client.chat.completions.create(model=llm_client.config.model,messages=messages,**clean_kwargs,)-+return response.choices[0].message.content# Create pure LightRAG instance (no multimodal)diff --git a/src/services/rag/factory.py b/src/services/rag/factory.pyindex 28e085c12..715888126 100644--- a/src/services/rag/factory.py+++ b/src/services/rag/factory.py@@ -5,10 +5,9 @@ Pipeline FactoryFactory for creating and managing RAG pipelines."""-from typing import Callable, Dict, List, Optional, Union+from typing import Callable, Dict, List, Optional-from .pipeline import RAGPipeline-from .pipelines import academic, lightrag, llamaindex+from .pipelines import lightrag, llamaindexfrom .pipelines.raganything import RAGAnythingPipeline# Pipeline registry@@ -16,13 +15,10 @@ _PIPELINES: Dict[str, Callable] = {"raganything": RAGAnythingPipeline, # Full multimodal: MinerU parser, deep analysis (slow, thorough)"lightrag": lightrag.LightRAGPipeline, # Knowledge graph: PDFParser, fast text-only (medium speed)"llamaindex": llamaindex.LlamaIndexPipeline, # Vector-only: Simple chunking, fast (fastest)- "academic": academic.AcademicPipeline,}-def get_pipeline(- name: str = "raganything", kb_base_dir: Optional[str] = None, **kwargs-):+def get_pipeline(name: str = "raganything", kb_base_dir: Optional[str] = None, **kwargs):"""Get a pre-configured pipeline by name.@@ -68,24 +64,19 @@ def list_pipelines() -> List[Dict[str, str]]:"""return [{- "id": "raganything",- "name": "RAG-Anything",- "description": "End-to-end academic document processing (MinerU + LightRAG)",+ "id": "llamaindex",+ "name": "LlamaIndex",+ "description": "纯向量检索,处理速度最快,适合快速搭建和简单场景。",},{"id": "lightrag","name": "LightRAG",- "description": "Component-based pipeline with knowledge graph",- },- {- "id": "llamaindex",- "name": "LlamaIndex",- "description": "Fast vector-based retrieval",+ "description": "轻量级知识图谱检索,快速处理纯文本文档,适合通用文档。",},{- "id": "academic",- "name": "Academic",- "description": "Academic documents with numbered item extraction",+ "id": "raganything",+ "name": "RAG-Anything",+ "description": "多模态文档处理,支持图表和公式提取,构建知识图谱。适合学术论文和教材。",},]diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.pyindex 7a5ea192f..cc9de9492 100644--- a/src/services/rag/pipelines/raganything.py+++ b/src/services/rag/pipelines/raganything.py@@ -9,6 +9,8 @@ from pathlib import Pathimport sysfrom typing import Any, Dict, List, Optional+from lightrag.llm.openai import openai_complete_if_cache+from src.logging import get_loggerfrom src.logging.adapters import LightRAGLogContext@@ -69,15 +71,15 @@ class RAGAnythingPipeline:self._setup_raganything_path()- from raganything import RAGAnything, RAGAnythingConfigfrom openai import AsyncOpenAI+ from raganything import RAGAnything, RAGAnythingConfigfrom src.services.embedding import get_embedding_clientfrom src.services.llm import get_llm_clientllm_client = get_llm_client()embed_client = get_embedding_client()-+# Create AsyncOpenAI client directly - bypasses LightRAG's response_format handlingopenai_client = AsyncOpenAI(api_key=llm_client.config.api_key,@@ -88,32 +90,41 @@ class RAGAnythingPipeline:"""Custom async LLM function that bypasses LightRAG's openai_complete_if_cache."""if history_messages is None:history_messages = []-+# Build messages arraymessages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})-+# Add historymessages.extend(history_messages)-+# Add current promptmessages.append({"role": "user", "content": prompt})-+# Whitelist only valid OpenAI parameters, filter out LightRAG-specific onesvalid_params = {- 'temperature', 'top_p', 'n', 'stream', 'stop', 'max_tokens',- 'presence_penalty', 'frequency_penalty', 'logit_bias', 'user', 'seed'+ "temperature",+ "top_p",+ "n",+ "stream",+ "stop",+ "max_tokens",+ "presence_penalty",+ "frequency_penalty",+ "logit_bias",+ "user",+ "seed",}clean_kwargs = {k: v for k, v in kwargs.items() if k in valid_params}-+# Call OpenAI API directly (async)response = await openai_client.chat.completions.create(model=llm_client.config.model,messages=messages,**clean_kwargs,)-+return response.choices[0].message.contentdef vision_model_func(diff --git a/src/services/rag/service.py b/src/services/rag/service.pyindex 2bcf60b6d..9b66540d0 100644--- a/src/services/rag/service.py+++ b/src/services/rag/service.py@@ -111,11 +111,14 @@ class RAGService:"""# Get the provider from KB metadata, fallback to instance providerprovider = self._get_provider_for_kb(kb_name)-- self.logger.info(f"Searching KB '{kb_name}' with provider '{provider}' and query: {query[:50]}...")-++ self.logger.info(+ f"Searching KB '{kb_name}' with provider '{provider}' and query: {query[:50]}..."+ )+# Get pipeline for the specific providerfrom .factory import get_pipeline+pipeline = get_pipeline(provider, kb_base_dir=self.kb_base_dir)result = await pipeline.search(query=query, kb_name=kb_name, mode=mode, **kwargs)@@ -138,17 +141,18 @@ class RAGService:"""Get the RAG provider for a specific knowledge base from its metadata.Falls back to instance provider or env var if not found in metadata.-+Args:kb_name: Knowledge base name-+Returns:Provider name (e.g., 'llamaindex', 'lightrag', 'raganything')"""try:import json+metadata_file = Path(self.kb_base_dir) / kb_name / "metadata.json"-+if metadata_file.exists():with open(metadata_file, encoding="utf-8") as f:metadata = json.load(f)@@ -156,13 +160,15 @@ class RAGService:if provider:self.logger.info(f"Using provider '{provider}' from KB metadata")return provider-+# Fallback to instance providerself.logger.info(f"No provider in metadata, using instance provider: {self.provider}")return self.provider-+except Exception as e:- self.logger.warning(f"Error reading provider from metadata: {e}, using instance provider")+ self.logger.warning(+ f"Error reading provider from metadata: {e}, using instance provider"+ )return self.providerasync def delete(self, kb_name: str) -> bool:diff --git a/src/tools/web_search/__init__.py b/src/services/search/__init__.pysimilarity index 86%rename from src/tools/web_search/__init__.pyrename to src/services/search/__init__.pyindex 454c5e6c1..c77bac0d2 100644--- a/src/tools/web_search/__init__.py+++ b/src/services/search/__init__.py@@ -1,10 +1,10 @@"""-Web Search Tool - Pluggable search provider architecture+Web Search Service - Pluggable search provider architectureThis module provides a unified interface for web search across multiple providers.Usage:- from src.tools.web_search import web_search+ from src.services.search import web_search# Simple usage (uses config/main.yaml or SEARCH_PROVIDER env var)result = web_search("What is AI?")@@ -28,31 +28,34 @@ Available Providers:- exa: Neural/embeddings search with summaries- serper: Google SERP results- jina: SERP with full content extraction++Environment Variables:+ - SEARCH_PROVIDER: Default search provider (default: perplexity)+ - SEARCH_API_KEY: Unified API key for all providers"""-from datetime import datetime+import jsonimport os+from datetime import datetime+from pathlib import Pathfrom typing import Anyfrom src.logging import get_loggerfrom src.services.config import PROJECT_ROOT, load_config_with_main-from .base import BaseSearchProvider-from .consolidation import AnswerConsolidator--# Backwards compatibility alias-SearchProvider = BaseSearchProvider+from .base import SEARCH_API_KEY_ENV, BaseSearchProvider+from .consolidation import CONSOLIDATION_TYPES, PROVIDER_TEMPLATES, AnswerConsolidatorfrom .providers import (get_available_providers,get_default_provider,get_provider,+ get_providers_info,list_providers,)from .types import Citation, SearchResult, WebSearchResponse-from .utils import save_results# Module logger-_logger = get_logger("WebSearch", level="INFO")+_logger = get_logger("Search", level="INFO")def _get_web_search_config() -> dict[str, Any]:@@ -70,6 +73,21 @@ def _get_web_search_config() -> dict[str, Any]:return {}+def _save_results(result: dict[str, Any], output_dir: str, provider: str) -> str:+ """Save search results to a JSON file."""+ output_path = Path(output_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")+ filename = f"search_{provider}_{timestamp}.json"+ file_path = output_path / filename++ with open(file_path, "w", encoding="utf-8") as f:+ json.dump(result, f, indent=2, ensure_ascii=False)++ return str(file_path)++def web_search(query: str,output_dir: str | None = None,@@ -166,6 +184,7 @@ def web_search(except Exception as e:_logger.error(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 = {}@@ -184,7 +203,7 @@ def web_search(# Save if output_dir providedif output_dir:- output_path = save_results(result, output_dir, provider_name)+ output_path = _save_results(result, output_dir, provider_name)result["result_file"] = output_path_logger.debug(f"Search results saved to: {output_path}")@@ -213,9 +232,6 @@ def get_current_config() -> dict[str, Any]:- template_providers: list[str] (providers that support template consolidation)- config_source: "env" | "yaml" | "default""""- from .consolidation import CONSOLIDATION_TYPES, PROVIDER_TEMPLATES- from .providers import get_providers_info-config = _get_web_search_config()# Determine effective provider@@ -239,17 +255,31 @@ def get_current_config() -> dict[str, Any]:}+# Backwards compatibility alias+SearchProvider = BaseSearchProvider+# Export public API__all__ = [+ # Main function"web_search","get_current_config",+ # Provider management"get_provider","list_providers","get_available_providers","get_default_provider",+ "get_providers_info",+ # Types"WebSearchResponse","Citation","SearchResult",+ # Consolidation"AnswerConsolidator",+ "CONSOLIDATION_TYPES",+ "PROVIDER_TEMPLATES",+ # Base class+ "BaseSearchProvider","SearchProvider",+ "SEARCH_API_KEY_ENV",]+diff --git a/src/tools/web_search/base.py b/src/services/search/base.pysimilarity index 68%rename from src/tools/web_search/base.pyrename to src/services/search/base.pyindex 4f963be2b..f2ce40596 100644--- a/src/tools/web_search/base.py+++ b/src/services/search/base.py@@ -2,10 +2,11 @@Web Search Base Provider - Abstract base class for all search providersThis module defines the BaseSearchProvider class that all search providers must inherit from.+All providers use a unified SEARCH_API_KEY environment variable."""-from abc import ABC, abstractmethodimport os+from abc import ABC, abstractmethodfrom typing import Anyfrom src.logging import get_logger@@ -13,36 +14,42 @@ from src.logging import get_loggerfrom .types import WebSearchResponse+# Unified API key environment variable+SEARCH_API_KEY_ENV = "SEARCH_API_KEY"++class BaseSearchProvider(ABC):- """Abstract base class for search providers"""+ """Abstract base class for search providers.++ All providers use a unified SEARCH_API_KEY environment variable.+ Each provider has its own BASE_URL defined as a class constant.+ """name: str = "base"display_name: str = "Base Provider"description: str = ""requires_api_key: bool = True- api_key_env_var: str = ""supports_answer: bool = False # Whether provider generates LLM answers+ BASE_URL: str = "" # Each provider defines its own endpointdef __init__(self, api_key: str | None = None, **kwargs: Any) -> None:"""Initialize the provider.Args:- api_key: API key for the provider. If not provided, will be read from environment.+ api_key: API key for the provider. If not provided, will be read from SEARCH_API_KEY.**kwargs: Additional configuration options."""- self.logger = get_logger(f"WebSearch.{self.__class__.__name__}", level="INFO")+ self.logger = get_logger(f"Search.{self.__class__.__name__}", level="INFO")self.api_key = api_key or self._get_api_key()self.config = kwargsdef _get_api_key(self) -> str:- """Get API key from environment variable"""- if not self.api_key_env_var:- return ""- key = os.environ.get(self.api_key_env_var, "")+ """Get API key from unified SEARCH_API_KEY environment variable."""+ key = os.environ.get(SEARCH_API_KEY_ENV, "")if self.requires_api_key and not key:raise ValueError(- f"{self.name} requires {self.api_key_env_var} environment variable. "+ f"{self.name} requires {SEARCH_API_KEY_ENV} environment variable. "f"Please set it before using this provider.")return key@@ -70,9 +77,13 @@ class BaseSearchProvider(ABC):"""try:if self.requires_api_key:- key = self.api_key or os.environ.get(self.api_key_env_var, "")+ key = self.api_key or os.environ.get(SEARCH_API_KEY_ENV, "")if not key:return Falsereturn Trueexcept (ValueError, ImportError):return False+++__all__ = ["BaseSearchProvider", "SEARCH_API_KEY_ENV"]+diff --git a/src/tools/web_search/consolidation.py b/src/services/search/consolidation.pysimilarity index 99%rename from src/tools/web_search/consolidation.pyrename to src/services/search/consolidation.pyindex c888bb499..0df2b7d63 100644--- a/src/tools/web_search/consolidation.py+++ b/src/services/search/consolidation.py@@ -16,7 +16,7 @@ from src.services.llm import get_llm_clientfrom .types import WebSearchResponse# Module logger-_logger = get_logger("WebSearch.Consolidation", level="INFO")+_logger = get_logger("Search.Consolidation", level="INFO")# Available consolidation types@@ -391,3 +391,7 @@ Search Results:Consolidate these results into structured grounding context."""return system_prompt, user_prompt+++__all__ = ["AnswerConsolidator", "CONSOLIDATION_TYPES", "PROVIDER_TEMPLATES"]+diff --git a/src/tools/web_search/providers/__init__.py b/src/services/search/providers/__init__.pysimilarity index 97%rename from src/tools/web_search/providers/__init__.pyrename to src/services/search/providers/__init__.pyindex 9d1234539..9aa72c4a7 100644--- a/src/tools/web_search/providers/__init__.py+++ b/src/services/search/providers/__init__.py@@ -85,7 +85,7 @@ def get_providers_info() -> list[dict]:Get full provider info from class attributes for frontend display.Returns:- list[dict]: List of provider info dicts with id, name, description, keyEnv, supports_answer+ list[dict]: List of provider info dicts with id, name, description, supports_answer"""providers_info = []for provider_id, cls in sorted(_PROVIDERS.items()):@@ -94,7 +94,6 @@ def get_providers_info() -> list[dict]:"id": provider_id,"name": cls.display_name,"description": cls.description,- "keyEnv": cls.api_key_env_var,"supports_answer": cls.supports_answer,"requires_api_key": cls.requires_api_key,}@@ -127,3 +126,4 @@ __all__ = ["get_providers_info","get_default_provider",]+diff --git a/src/tools/web_search/providers/baidu.py b/src/services/search/providers/baidu.pysimilarity index 99%rename from src/tools/web_search/providers/baidu.pyrename to src/services/search/providers/baidu.pyindex 476fd5d21..c4fdf2a8a 100644--- a/src/tools/web_search/providers/baidu.py+++ b/src/services/search/providers/baidu.py@@ -27,9 +27,7 @@ class BaiduProvider(BaseSearchProvider):display_name = "Baidu AI"description = "百度AI搜索 with ERNIE models"- api_key_env_var = "BAIDU_API_KEY"supports_answer = True-BASE_URL = "https://qianfan.baidubce.com/v2/ai_search/chat/completions"def search(@@ -188,3 +186,4 @@ class BaiduProvider(BaseSearchProvider):)return response_obj+diff --git a/src/tools/web_search/providers/exa.py b/src/services/search/providers/exa.pysimilarity index 99%rename from src/tools/web_search/providers/exa.pyrename to src/services/search/providers/exa.pyindex 269be40d5..fb964a072 100644--- a/src/tools/web_search/providers/exa.py+++ b/src/services/search/providers/exa.py@@ -35,9 +35,7 @@ class ExaProvider(BaseSearchProvider):display_name = "Exa"description = "Neural/embeddings search"- api_key_env_var = "EXA_API_KEY"supports_answer = True # Provides summaries and context-BASE_URL = "https://api.exa.ai/search"def search(@@ -194,3 +192,4 @@ class ExaProvider(BaseSearchProvider):)return response_obj+diff --git a/src/tools/web_search/providers/jina.py b/src/services/search/providers/jina.pysimilarity index 97%rename from src/tools/web_search/providers/jina.pyrename to src/services/search/providers/jina.pyindex ab28fd324..486b9ca64 100644--- a/src/tools/web_search/providers/jina.py+++ b/src/services/search/providers/jina.py@@ -15,9 +15,9 @@ Features:- Free tier: 10M tokens"""+import urllib.parsefrom datetime import datetimefrom typing import Any-import urllib.parseimport requests@@ -32,11 +32,9 @@ class JinaProvider(BaseSearchProvider):display_name = "Jina"description = "SERP with content extraction (free tier)"- api_key_env_var = "JINA_API_KEY"supports_answer = False # Returns raw content, not LLM answersrequires_api_key = False # Has free tier without API key-- SEARCH_URL = "https://s.jina.ai"+ BASE_URL = "https://s.jina.ai"def search(self,@@ -75,7 +73,7 @@ class JinaProvider(BaseSearchProvider):# URL encode the queryencoded_query = urllib.parse.quote(query)- url = f"{self.SEARCH_URL}/{encoded_query}"+ url = f"{self.BASE_URL}/{encoded_query}"response = requests.get(url, headers=headers, timeout=timeout)@@ -161,3 +159,4 @@ class JinaProvider(BaseSearchProvider):)return response_obj+diff --git a/src/tools/web_search/providers/perplexity.py b/src/services/search/providers/perplexity.pysimilarity index 98%rename from src/tools/web_search/providers/perplexity.pyrename to src/services/search/providers/perplexity.pyindex f27e6614e..80997ea0b 100644--- a/src/tools/web_search/providers/perplexity.py+++ b/src/services/search/providers/perplexity.py@@ -24,8 +24,8 @@ class PerplexityProvider(BaseSearchProvider):display_name = "Perplexity"description = "AI-powered search with answers"- api_key_env_var = "PERPLEXITY_API_KEY"supports_answer = True+ BASE_URL = "https://api.perplexity.ai" # Used by the perplexity package internallydef __init__(self, api_key: str | None = None, **kwargs: Any) -> None:super().__init__(api_key, **kwargs)@@ -151,3 +151,4 @@ class PerplexityProvider(BaseSearchProvider):)return response+diff --git a/src/tools/web_search/providers/serper.py b/src/services/search/providers/serper.pysimilarity index 99%rename from src/tools/web_search/providers/serper.pyrename to src/services/search/providers/serper.pyindex 78c152fe9..aa5b308b8 100644--- a/src/tools/web_search/providers/serper.py+++ b/src/services/search/providers/serper.py@@ -13,8 +13,8 @@ Features:- Very cheap: $1/1000 queries at scale"""-from datetime import datetimeimport json+from datetime import datetimefrom typing import Anyimport requests@@ -36,9 +36,7 @@ class SerperProvider(BaseSearchProvider):display_name = "Serper"description = "Google SERP results"- api_key_env_var = "SERPER_API_KEY"supports_answer = False # Raw SERP results, no LLM answer-BASE_URL = "https://google.serper.dev"def search(@@ -209,3 +207,4 @@ class SerperProvider(BaseSearchProvider):usage={},metadata=metadata,)+diff --git a/src/tools/web_search/providers/tavily.py b/src/services/search/providers/tavily.pysimilarity index 99%rename from src/tools/web_search/providers/tavily.pyrename to src/services/search/providers/tavily.pyindex 446898f90..9cd3d7fd1 100644--- a/src/tools/web_search/providers/tavily.py+++ b/src/services/search/providers/tavily.py@@ -12,8 +12,8 @@ Features:- Domain include/exclude lists"""-from datetime import datetimeimport json+from datetime import datetimefrom typing import Anyimport requests@@ -30,9 +30,7 @@ class TavilyProvider(BaseSearchProvider):name = "tavily"display_name = "Tavily"description = "Research-focused search"- api_key_env_var = "TAVILY_API_KEY"supports_answer = True-BASE_URL = "https://api.tavily.com/search"def search(@@ -161,3 +159,4 @@ class TavilyProvider(BaseSearchProvider):)return response_obj+diff --git a/src/tools/web_search/types.py b/src/services/search/types.pysimilarity index 98%rename from src/tools/web_search/types.pyrename to src/services/search/types.pyindex 6694a8f20..cea3963ad 100644--- a/src/tools/web_search/types.py+++ b/src/services/search/types.py@@ -109,3 +109,7 @@ class WebSearchResponse:if key not in result and key != "finish_reason":result[key] = valuereturn result+++__all__ = ["Citation", "SearchResult", "WebSearchResponse"]+diff --git a/src/services/setup/init.py b/src/services/setup/init.pyindex 83d7075b9..dcc1102cb 100644--- a/src/services/setup/init.py+++ b/src/services/setup/init.py@@ -155,16 +155,18 @@ def init_user_directories(project_root: Path | None = None) -> None:except Exception as e:logger.warning(f"Failed to create user_history.json: {e}")- # Create settings.json if it doesn't exist (default to English)- settings_file = user_data_dir / "settings.json"- if not settings_file.exists():+ # Create interface.json in settings folder if it doesn't exist+ settings_dir = user_data_dir / "settings"+ settings_dir.mkdir(parents=True, exist_ok=True)+ interface_file = settings_dir / "interface.json"+ if not interface_file.exists():initial_settings = {"theme": "light", "language": "en", "output_language": "en"}try:- with open(settings_file, "w", encoding="utf-8") as f:+ with open(interface_file, "w", encoding="utf-8") as f:json.dump(initial_settings, f, indent=2, ensure_ascii=False)- logger.success("Created: settings.json")+ logger.success("Created: settings/interface.json")except Exception as e:- logger.warning(f"Failed to create settings.json: {e}")+ logger.warning(f"Failed to create settings/interface.json: {e}")logger.info("=" * 80)logger.success("User data directory initialization complete!")@@ -197,12 +199,14 @@ def init_user_directories(project_root: Path | None = None) -> None:except Exception:pass # Silent fail if file creation fails but directory exists- # Ensure settings.json exists (default to English)- settings_file = user_data_dir / "settings.json"- if not settings_file.exists():+ # Ensure interface.json exists in settings folder+ settings_dir = user_data_dir / "settings"+ settings_dir.mkdir(parents=True, exist_ok=True)+ interface_file = settings_dir / "interface.json"+ if not interface_file.exists():initial_settings = {"theme": "light", "language": "en", "output_language": "en"}try:- with open(settings_file, "w", encoding="utf-8") as f:+ with open(interface_file, "w", encoding="utf-8") as f:json.dump(initial_settings, f, indent=2, ensure_ascii=False)except Exception:pass # Silent fail if file creation fails but directory existsdiff --git a/src/services/tts/config.py b/src/services/tts/config.pyindex 584035f42..ba49ef80b 100644--- a/src/services/tts/config.py+++ b/src/services/tts/config.py@@ -3,14 +3,18 @@ TTS Configuration=================Configuration management for Text-to-Speech services.+Simplified version - loads from unified config service or falls back to .env."""+import loggingimport osfrom pathlib import Pathfrom typing import Optionalfrom dotenv import load_dotenv+logger = logging.getLogger(__name__)+# Load environment variablesPROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parentload_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)@@ -26,7 +30,11 @@ def _strip_value(value: Optional[str]) -> Optional[str]:def get_tts_config() -> dict:"""- Return complete environment configuration for TTS (Text-to-Speech).+ Return complete configuration for TTS (Text-to-Speech).++ Priority:+ 1. Active configuration from unified config service+ 2. Environment variables (.env)Returns:dict: Dictionary containing the following keys:@@ -39,6 +47,26 @@ def get_tts_config() -> dict:Raises:ValueError: If required configuration is missing"""+ # 1. Try to get active config from unified config service+ try:+ from src.services.config import get_active_tts_config++ config = get_active_tts_config()+ if config and config.get("model"):+ return {+ "model": config["model"],+ "api_key": config.get("api_key", ""),+ "base_url": config.get("base_url", ""),+ "api_version": config.get("api_version"),+ "voice": config.get("voice", "alloy"),+ }+ except ImportError:+ # Unified config service not yet available, fall back to env+ pass+ except Exception as e:+ logger.warning(f"Failed to load from unified config: {e}")++ # 2. Fallback to environment variablesmodel = _strip_value(os.getenv("TTS_MODEL"))api_key = _strip_value(os.getenv("TTS_API_KEY"))base_url = _strip_value(os.getenv("TTS_URL"))@@ -48,13 +76,15 @@ def get_tts_config() -> dict:# Validate required configurationif not model:raise ValueError(- "Error: TTS_MODEL not set, please configure it in .env file (e.g., tts-1 or tts-1-hd)"+ "TTS_MODEL not set. Please configure it in .env file or add a configuration in Settings")if not api_key:- raise ValueError("Error: TTS_API_KEY not set, please configure it in .env file")+ raise ValueError(+ "TTS_API_KEY not set. Please configure it in .env file or add a configuration in Settings"+ )if not base_url:raise ValueError(- "Error: TTS_URL not set, please configure it in .env file (e.g., https://api.openai.com/v1)"+ "TTS_URL not set. Please configure it in .env file or add a configuration in Settings")return {diff --git a/src/tools/__init__.py b/src/tools/__init__.pyindex 96cfd3836..808f37a23 100644--- a/src/tools/__init__.py+++ b/src/tools/__init__.py@@ -10,6 +10,7 @@ Includes:- paper_search_tool: Paper search tool- tex_downloader: LaTeX source download tool- tex_chunker: LaTeX text chunking tool+- question: Question generation tools (pdf_parser, question_extractor, exam_mimic)"""# Patch lightrag.utils BEFORE any imports that use lightrag@@ -85,3 +86,6 @@ except ImportError as e:"run_code_sync","web_search",]++# Question generation tools (lazy import to avoid circular dependencies)+# Access via: from src.tools.question import parse_pdf_with_mineru, etc.diff --git a/src/agents/question/tools/__init__.py b/src/tools/question/__init__.pysimilarity index 82%rename from src/agents/question/tools/__init__.pyrename to src/tools/question/__init__.pyindex b99092590..57c9ebcd7 100644--- a/src/agents/question/tools/__init__.py+++ b/src/tools/question/__init__.py@@ -1,5 +1,7 @@"""Question Tools - Question generation system toolset++Tools for PDF parsing, question extraction, and exam mimicking."""from .exam_mimic import mimic_exam_questions@@ -11,3 +13,4 @@ __all__ = ["extract_questions_from_paper","mimic_exam_questions",]+diff --git a/src/agents/question/tools/exam_mimic.py b/src/tools/question/exam_mimic.pysimilarity index 96%rename from src/agents/question/tools/exam_mimic.pyrename to src/tools/question/exam_mimic.pyindex 62e13a779..8fea6530d 100644--- a/src/agents/question/tools/exam_mimic.py+++ b/src/tools/question/exam_mimic.py@@ -22,13 +22,13 @@ from typing import TYPE_CHECKING, Any, Callableif TYPE_CHECKING:from src.agents.question import AgentCoordinator-# Add project root to sys.path-project_root = Path(__file__).parent.parent.parent.parent.parent+# Project root is 3 levels up from src/tools/question/+project_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))# Note: AgentCoordinator is imported inside functions to avoid circular import-from src.agents.question.tools.pdf_parser import parse_pdf_with_mineru-from src.agents.question.tools.question_extractor import extract_questions_from_paper+from src.tools.question.pdf_parser import parse_pdf_with_mineru+from src.tools.question.question_extractor import extract_questions_from_paperfrom src.services.llm.config import get_llm_config# Type alias for WebSocket callback@@ -145,7 +145,6 @@ async def mimic_exam_questions(paper_path = Path(paper_dir)# Candidate locations to search (including new location)- project_root = Path(__file__).parent.parent.parent.parent.parentpossible_paths = [project_root/ "data"@@ -177,12 +176,7 @@ async def mimic_exam_questions("success": False,"error": f"{error_msg}\nSearched paths: {[str(p) for p in possible_paths]}",}- else:- latest_dir = paper_path.resolve()- if not latest_dir.exists():- error_msg = f"Exam directory not found: {latest_dir}"- await send_progress("error", {"content": error_msg})- return {"success": False, "error": error_msg}+ # Note: latest_dir was already resolved in the loop above, no need to override# Ensure auto subdirectory existsauto_dir = latest_dir / "auto"@@ -219,7 +213,6 @@ async def mimic_exam_questions(print("-" * 80)# Use provided output_dir or default to mimic_papers- project_root = Path(__file__).parent.parent.parent.parent.parentif output_dir:output_base = Path(output_dir)else:@@ -621,3 +614,4 @@ Examples:if __name__ == "__main__":asyncio.run(main())+diff --git a/src/agents/question/tools/pdf_parser.py b/src/tools/question/pdf_parser.pysimilarity index 97%rename from src/agents/question/tools/pdf_parser.pyrename to src/tools/question/pdf_parser.pyindex f6e8be011..4f5596a4b 100644--- a/src/agents/question/tools/pdf_parser.py+++ b/src/tools/question/pdf_parser.py@@ -67,9 +67,10 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):print(f"✗ Error: File is not PDF format: {pdf_path}")return False- script_dir = Path(__file__).parent.parent.parent.parent.parent+ # Project root is 3 levels up from src/tools/question/+ project_root = Path(__file__).parent.parent.parent.parentif output_base_dir is None:- output_base_dir = script_dir / "reference_papers"+ output_base_dir = project_root / "reference_papers"else:output_base_dir = Path(output_base_dir)@@ -197,3 +198,4 @@ Examples:if __name__ == "__main__":main()+diff --git a/src/agents/question/tools/question_extractor.py b/src/tools/question/question_extractor.pysimilarity index 99%rename from src/agents/question/tools/question_extractor.pyrename to src/tools/question/question_extractor.pyindex 03b654351..d9b01eff2 100644--- a/src/agents/question/tools/question_extractor.py+++ b/src/tools/question/question_extractor.py@@ -20,7 +20,8 @@ from pathlib import Pathimport sysfrom typing import Any-project_root = Path(__file__).parent.parent.parent.parent.parent+# Project root is 3 levels up from src/tools/question/+project_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))from src.services.config import get_agent_params@@ -391,3 +392,4 @@ Examples:if __name__ == "__main__":main()+diff --git a/src/tools/web_search.py b/src/tools/web_search.pynew file mode 100644index 000000000..822dec9e3--- /dev/null+++ b/src/tools/web_search.py@@ -0,0 +1,72 @@+"""+Web Search Tool - Simple entry point for agents++This module provides a simple interface to the web search service.+All search logic is implemented in src/services/search/.++Usage:+ from src.tools.web_search import web_search++ # Simple usage+ result = web_search("What is AI?")++ # With provider+ result = web_search("What is AI?", provider="tavily")++Environment Variables:+ - SEARCH_PROVIDER: Default search provider (default: perplexity)+ - SEARCH_API_KEY: Unified API key for all providers++Available Providers:+ - perplexity: AI-powered search (default)+ - baidu: Baidu AI Search+ - tavily: Research-focused with optional answers+ - exa: Neural/embeddings search with summaries+ - serper: Google SERP results+ - jina: SERP with full content extraction+"""++# Re-export from services layer+from src.services.search import (+ CONSOLIDATION_TYPES,+ PROVIDER_TEMPLATES,+ SEARCH_API_KEY_ENV,+ AnswerConsolidator,+ BaseSearchProvider,+ Citation,+ SearchProvider,+ SearchResult,+ WebSearchResponse,+ get_available_providers,+ get_current_config,+ get_default_provider,+ get_provider,+ get_providers_info,+ list_providers,+ web_search,+)++__all__ = [+ # Main function+ "web_search",+ "get_current_config",+ # Provider management+ "get_provider",+ "list_providers",+ "get_available_providers",+ "get_default_provider",+ "get_providers_info",+ # Types+ "WebSearchResponse",+ "Citation",+ "SearchResult",+ # Consolidation+ "AnswerConsolidator",+ "CONSOLIDATION_TYPES",+ "PROVIDER_TEMPLATES",+ # Base class+ "BaseSearchProvider",+ "SearchProvider",+ "SEARCH_API_KEY_ENV",+]+diff --git a/src/tools/web_search/README.md b/src/tools/web_search/README.mddeleted file mode 100644index e8ccc0519..000000000--- a/src/tools/web_search/README.md+++ /dev/null@@ -1,753 +0,0 @@-# Web Search Tool--A unified, pluggable web search interface supporting multiple search providers with standardized responses.--## Quick Start--```python-from src.tools.web_search import web_search--# Basic search (uses default provider from config)-result = web_search("What is machine learning?")-print(result["answer"])-print(result["citations"])--# Specify a provider-result = web_search("Latest AI news", provider="tavily")--# With provider-specific options-result = web_search(- query="Python best practices",- provider="serper",- output_dir="./search_cache",- verbose=True,- num=20, # Serper-specific option-)-```--## Available Providers--| Provider | Type | API Key Env Var | Generates Answer | Description |-|----------|------|-----------------|------------------|-------------|-| **perplexity** | AI Search | `PERPLEXITY_API_KEY` | ✅ Yes | AI-powered search with LLM answers |-| **baidu** | AI Search | `BAIDU_API_KEY` | ✅ Yes | Baidu AI Search with ERNIE models |-| **tavily** | AI Search | `TAVILY_API_KEY` | ✅ Yes | Research-focused with relevance scoring |-| **exa** | AI Search | `EXA_API_KEY` | ✅ Yes | Neural/embeddings search with summaries |-| **serper** | SERP | `SERPER_API_KEY` | ⚡ Partial | Google SERP (extracts from Knowledge Graph) |-| **jina** | SERP | `JINA_API_KEY` | ❌ No | SERP with content extraction (free tier available) |--### Provider-Specific Options--#### Perplexity-```python-result = web_search(- query="Explain quantum computing",- provider="perplexity",- model="sonar",- system_prompt="Be concise and technical",-)-```--#### Tavily-```python-result = web_search(- query="Latest developments in renewable energy",- provider="tavily",- search_depth="advanced", # "basic" or "advanced"- topic="news", # "general", "news", "finance"- max_results=15, # 1-20- include_answer=True,- include_raw_content=False,- include_images=False,- days=30, # Filter to last N days (1-365)- include_domains=["arxiv.org"],- exclude_domains=["example.com"],-)-```--#### Exa-```python-result = web_search(- query="Machine learning optimization",- provider="exa",- search_type="neural", # "auto", "neural", "keyword"- num_results=10,- include_text=True,- include_highlights=True,- include_summary=True,- category="research paper", # "news", "company", "github", etc.- start_published_date="2024-01-01",- end_published_date="2024-12-31",-)-```--#### Baidu-```python-result = web_search(- query="人工智能最新进展",- provider="baidu",- model="ernie-4.5-turbo-32k",- enable_deep_search=True,- search_recency_filter="month", # "week", "month", "semiyear", "year"-)-```--#### Serper-```python-result = web_search(- query="Best Python frameworks 2024",- provider="serper",- mode="search", # "search" or "scholar"- num=20, # max: 100- gl="us", # Country code- hl="en", # Language code-)--# Scholar mode for academic papers-result = web_search(- query="transformer architecture attention mechanism",- provider="serper",- mode="scholar", # Google Scholar results- num=10,- consolidation="template", # Uses serper_scholar template automatically-)-# Scholar results include in attributes: publicationInfo, citedBy, pdfUrl, year, paperId-```--#### Jina-```python-result = web_search(- query="Python async programming guide",- provider="jina",- enrich=True, # Full content + images (default: True)- timeout=60, # Request timeout in seconds-)--# Basic mode (SERP only, no content extraction)-result = web_search(- query="Python async programming guide",- provider="jina",- enrich=False, # Basic SERP only, faster-)-```--## Configuration--### Environment Variables--```bash-# Provider selection (optional)-export SEARCH_PROVIDER=tavily--# API Keys-export PERPLEXITY_API_KEY=your_key-export TAVILY_API_KEY=your_key-export EXA_API_KEY=your_key-export BAIDU_API_KEY=your_key-export SERPER_API_KEY=your_key-export JINA_API_KEY=your_key-```--### YAML Configuration (`config/main.yaml`)--```yaml-tools:- web_search:- enabled: true- provider: perplexity- consolidation: template # "none", "template", "llm"-```--### Priority Order--1. Function argument (`provider="tavily"`)-2. Environment variable (`SEARCH_PROVIDER`)-3. YAML config (`config/main.yaml`)-4. Default (`perplexity`)--## Response Format--All providers return a standardized dictionary:--```python-{- "timestamp": "2024-01-15T10:30:00.000000",- "query": "What is machine learning?",- "provider": "tavily",- "model": "tavily-basic",- "answer": "Machine learning is a subset of AI...",- "citations": [- {- "id": 1,- "reference": "[1]",- "url": "https://example.com/ml-guide",- "title": "Machine Learning Guide",- "snippet": "A comprehensive introduction...",- "date": "2024-01-10",- "source": "example.com",- "content": "",- "type": "web",- "icon": "",- "website": "",- "web_anchor": ""- }- ],- "search_results": [- {- "title": "Machine Learning Guide",- "url": "https://example.com/ml-guide",- "snippet": "A comprehensive introduction...",- "date": "2024-01-10",- "source": "example.com",- "content": "",- "score": 0.95- }- ],- "usage": {},- "response": {- "content": "Machine learning is...",- "role": "assistant",- "finish_reason": "stop"- }- # Provider-specific metadata may be merged at top level-}-```--## Answer Consolidation--SERP providers (Serper, Jina) don't generate LLM answers. Use consolidation to generate answers from raw results:--### Template Consolidation--Uses provider-specific Jinja2 templates. **Available for: `serper`, `serper_scholar`, `jina`**.--When using Serper with `mode="scholar"`, the provider automatically returns `provider="serper_scholar"` which triggers the academic-focused template with publication info, authors, and citation counts.--```python-result = web_search(- query="Python best practices",- provider="serper",- consolidation="template",-)--# Scholar mode with automatic template selection-result = web_search(- query="deep learning optimization",- provider="serper",- mode="scholar", # Automatically uses serper_scholar template- consolidation="template",-)-```--### LLM Consolidation--Uses the project's LLM client to synthesize answers. Works with any provider.--```python-result = web_search(- query="Python best practices",- provider="serper",- consolidation="llm",-)-```--### Custom Template--```python-result = web_search(- query="Python best practices",- provider="serper",- consolidation="template",- consolidation_custom_template="""-# Results for: {{ query }}--{% for result in results[:5] %}-## {{ result.title }}-{{ result.snippet }}-[Source]({{ result.url }})-{% endfor %}-""",-)-```-------# Creating New Providers--This section documents how to add new search providers to the web_search module.--## Architecture Overview--```-src/tools/web_search/-├── __init__.py # Main entry point, web_search() function-├── base.py # BaseSearchProvider abstract class-├── types.py # WebSearchResponse, Citation, SearchResult dataclasses-├── consolidation.py # Answer consolidation (template/LLM)-├── utils.py # Helper utilities-└── providers/- ├── __init__.py # Provider registry (@register_provider decorator)- ├── perplexity.py- ├── tavily.py- ├── exa.py- ├── baidu.py- ├── serper.py- └── jina.py-```--## Step 1: Create Provider File--Create `src/tools/web_search/providers/my_provider.py`:--```python-"""-MyProvider Search Provider--API Docs: https://api.myprovider.com/docs-"""-from datetime import datetime-from typing import Any--import requests--from ..base import BaseSearchProvider-from ..types import Citation, SearchResult, WebSearchResponse-from . import register_provider---@register_provider("myprovider")-class MyProvider(BaseSearchProvider):- """My custom search provider"""-- # =========================================================================- # REQUIRED CLASS ATTRIBUTES- # =========================================================================-- # Human-readable name for UI display- display_name = "MyProvider"-- # Short description for UI- description = "My custom search engine"-- # Environment variable name for API key- api_key_env_var = "MYPROVIDER_API_KEY"-- # Does this provider generate LLM answers?- # - True: AI providers (Perplexity, Tavily, Exa, Baidu)- # - False: SERP providers (Serper, Jina) - need consolidation for answers- supports_answer = True-- # =========================================================================- # OPTIONAL CLASS ATTRIBUTES- # =========================================================================-- # Set to False if provider has a free tier (like Jina)- # Default: True- requires_api_key = True-- # Provider name (auto-set by @register_provider decorator)- # Only override if you need a different internal name- # name = "myprovider"-- # =========================================================================- # PROVIDER IMPLEMENTATION- # =========================================================================-- BASE_URL = "https://api.myprovider.com/search"-- def search(- self,- query: str,- # Add your provider-specific parameters here- max_results: int = 10,- language: str = "en",- timeout: int = 30,- **kwargs: Any,- ) -> WebSearchResponse:- """- Execute search and return standardized response.-- Args:- query: Search query string.- max_results: Maximum results to return.- language: Language code.- timeout: Request timeout in seconds.- **kwargs: Additional options (passed from web_search()).-- Returns:- WebSearchResponse: Standardized search response.- """- # Use self.logger for logging (auto-configured in base class)- self.logger.debug(f"Calling MyProvider API max_results={max_results}")-- # Use self.api_key (auto-loaded from env var or constructor)- headers = {- "Authorization": f"Bearer {self.api_key}",- "Content-Type": "application/json",- }-- payload = {- "query": query,- "limit": max_results,- "lang": language,- }-- response = requests.post(- self.BASE_URL,- headers=headers,- json=payload,- timeout=timeout,- )-- if response.status_code != 200:- self.logger.error(f"MyProvider API error: {response.status_code}")- raise Exception(- f"MyProvider API error: {response.status_code} - {response.text}"- )-- data = response.json()- self.logger.debug(f"MyProvider returned {len(data.get('results', []))} results")-- # =====================================================================- # CONVERT API RESPONSE TO STANDARDIZED FORMAT- # =====================================================================-- citations: list[Citation] = []- search_results: list[SearchResult] = []-- for i, item in enumerate(data.get("results", []), 1):- # Build SearchResult- sr = SearchResult(- title=item.get("title", ""),- url=item.get("url", ""),- snippet=item.get("snippet", ""),- date=item.get("published_date", ""),- source=item.get("domain", ""),- content=item.get("full_content", ""), # Full text if available- score=item.get("relevance_score", 0.0),- # Optional: sitelinks and attributes- sitelinks=[], # list[dict] with "title" and "link" keys- attributes={}, # dict with any extra data- )- search_results.append(sr)-- # Build Citation (parallel to SearchResult)- citations.append(- Citation(- id=i,- reference=f"[{i}]",- url=item.get("url", ""),- title=item.get("title", ""),- snippet=item.get("snippet", ""),- date=item.get("published_date", ""),- source=item.get("domain", ""),- content=item.get("full_content", ""),- )- )-- # Build the response- return WebSearchResponse(- query=query,- answer=data.get("generated_answer", ""), # Empty string for SERP providers- provider="myprovider",- timestamp=datetime.now().isoformat(),- model=data.get("model_used", "myprovider-default"),- citations=citations,- search_results=search_results,- usage={- # Token usage if available- "prompt_tokens": data.get("usage", {}).get("prompt_tokens", 0),- "completion_tokens": data.get("usage", {}).get("completion_tokens", 0),- "total_tokens": data.get("usage", {}).get("total_tokens", 0),- },- metadata={- "finish_reason": "stop",- # Add any provider-specific metadata here- # This data is available for template consolidation- },- )-```--## Step 2: Register the Provider--Add the import to `src/tools/web_search/providers/__init__.py`:--```python-# At the bottom of the file, add your provider to the imports:-from . import perplexity, baidu, tavily, exa, serper, jina, my_provider-```--That's it! The `@register_provider("myprovider")` decorator automatically registers your provider in the global registry.--## Step 3: (Optional) Add Consolidation Template--If your provider is a SERP provider (`supports_answer = False`), you can add a Jinja2 template for template consolidation.--Edit `src/tools/web_search/consolidation.py`:--```python-# 1. Add to PROVIDER_TEMPLATES dict (module-level):-PROVIDER_TEMPLATES = {- # ... existing templates ...-- "myprovider": """### Search Results for "{{ query }}"--{% for result in results[:max_results] %}-**[{{ loop.index }}] {{ result.title }}**-{{ result.snippet }}-🔗 {{ result.url }}-{% if result.date %}📅 {{ result.date }}{% endif %}--{% endfor %}-----*{{ results|length }} results from MyProvider*""",-}--# 2. Add to AnswerConsolidator.PROVIDER_TEMPLATE_MAP (class attribute):-class AnswerConsolidator:- PROVIDER_TEMPLATE_MAP = {- "serper": "serper",- "jina": "jina",- "serper_scholar": "serper_scholar",- "myprovider": "myprovider", # Add this line- }-```--### Template Context Variables--These variables are available in all templates:--| Variable | Type | Description |-|----------|------|-------------|-| `query` | `str` | Original search query |-| `provider` | `str` | Provider name |-| `model` | `str` | Model used |-| `max_results` | `int` | Max results to display (default: 5) |-| `results` | `list[dict]` | Search results with `title`, `url`, `snippet`, `date`, `source`, `content`, `sitelinks`, `attributes` |-| `citations` | `list[dict]` | Citations with `id`, `reference`, `url`, `title`, `snippet` |-| `timestamp` | `str` | ISO timestamp |--Provider-specific metadata from `WebSearchResponse.metadata` is also available. For example, Serper templates have access to:-- `knowledge_graph`-- `answer_box`-- `people_also_ask`-- `related_searches`--## Step 4: Test Your Provider--```python-from src.tools.web_search import web_search, list_providers, get_available_providers--# Verify registration-print(list_providers())-# ['baidu', 'exa', 'jina', 'myprovider', 'perplexity', 'serper', 'tavily']--# Check if available (API key set)-print(get_available_providers())--# Test search-result = web_search("test query", provider="myprovider")-print(result["answer"])-print(result["citations"])--# Test with consolidation (for SERP providers)-result = web_search(- "test query",- provider="myprovider",- consolidation="template",-)-```--## BaseSearchProvider Reference--```python-class BaseSearchProvider(ABC):- """Abstract base class for search providers"""-- # Class attributes (override in subclass)- name: str = "base" # Auto-set by @register_provider- display_name: str = "Base Provider" # Human-readable name- description: str = "" # Short description- requires_api_key: bool = True # False for free-tier providers- api_key_env_var: str = "" # Env var name for API key- supports_answer: bool = False # True for AI providers-- def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:- """- Initialize the provider.-- Args:- api_key: API key. If not provided, reads from api_key_env_var.- **kwargs: Additional config stored in self.config.- """- self.logger = get_logger(f"WebSearch.{self.__class__.__name__}")- self.api_key = api_key or self._get_api_key()- self.config = kwargs-- @abstractmethod- def search(self, query: str, **kwargs: Any) -> WebSearchResponse:- """Execute search - MUST be implemented by subclass."""- pass-- def is_available(self) -> bool:- """Check if provider is available (API key set if required)."""- if self.requires_api_key:- return bool(self.api_key)- return True-```--## Types Reference--### WebSearchResponse--```python-@dataclass-class WebSearchResponse:- query: str # Original search query- answer: str # LLM answer (empty for SERP)- provider: str # Provider name- timestamp: str # ISO timestamp- model: str # Model used- citations: list[Citation] # Citation list- search_results: list[SearchResult] # Raw search results- usage: dict[str, Any] # Token/cost usage- metadata: dict[str, Any] # Provider-specific data-- def to_dict(self) -> dict[str, Any]:- """Convert to backward-compatible dict format."""-```--### Citation--```python-@dataclass-class Citation:- id: int # Citation number (1, 2, 3...)- reference: str # Display reference ("[1]", "[2]"...)- url: str # Source URL- title: str = "" # Page title- snippet: str = "" # Text snippet- date: str = "" # Publication date- source: str = "" # Source domain- content: str = "" # Full content if available- # Additional fields for backward compatibility- type: str = "web" # Citation type (web, pdf, etc.)- icon: str = "" # Source icon URL- website: str = "" # Website name- web_anchor: str = "" # Web anchor text-```--### SearchResult--```python-@dataclass-class SearchResult:- title: str # Result title- url: str # Result URL- snippet: str # Text snippet- date: str = "" # Publication date- source: str = "" # Source domain- content: str = "" # Full content if available- score: float = 0.0 # Relevance score- sitelinks: list[dict[str, str]] = [] # Related links- attributes: dict[str, Any] = {} # Additional attributes-```--## Helper Functions--```python-from src.tools.web_search import (- web_search, # Main search function- get_current_config, # Get active configuration- list_providers, # List all registered providers- get_available_providers, # List providers with API keys set- get_provider, # Get a provider instance directly- get_default_provider, # Get default provider instance- WebSearchResponse, # Response dataclass- Citation, # Citation dataclass- SearchResult, # SearchResult dataclass- AnswerConsolidator, # Consolidation class-)--# From providers submodule (for advanced use)-from src.tools.web_search.providers import (- get_providers_info, # Get full provider info for frontend display- register_provider, # Decorator to register custom providers-)-```--## Example: Real Provider Implementation--Here's a simplified version of the Tavily provider as reference:--```python-@register_provider("tavily")-class TavilyProvider(BaseSearchProvider):- """Tavily research-focused search provider"""-- display_name = "Tavily"- description = "Research-focused search"- api_key_env_var = "TAVILY_API_KEY"- supports_answer = True # Tavily generates LLM answers-- BASE_URL = "https://api.tavily.com/search"-- def search(- self,- query: str,- search_depth: str = "basic",- topic: str = "general",- max_results: int = 10,- include_answer: bool = True,- timeout: int = 60,- **kwargs: Any,- ) -> WebSearchResponse:- self.logger.debug(f"Calling Tavily API depth={search_depth}")-- payload = {- "api_key": self.api_key,- "query": query,- "search_depth": search_depth,- "topic": topic,- "max_results": max_results,- "include_answer": include_answer,- }-- response = requests.post(self.BASE_URL, json=payload, timeout=timeout)-- if response.status_code != 200:- raise Exception(f"Tavily API error: {response.status_code}")-- data = response.json()-- citations = []- search_results = []-- for i, result in enumerate(data.get("results", []), 1):- sr = SearchResult(- title=result.get("title", ""),- url=result.get("url", ""),- snippet=result.get("content", ""),- score=result.get("score", 0.0),- )- search_results.append(sr)- citations.append(Citation(- id=i,- reference=f"[{i}]",- url=result.get("url", ""),- title=result.get("title", ""),- snippet=result.get("content", ""),- ))-- return WebSearchResponse(- query=query,- answer=data.get("answer", ""),- provider="tavily",- timestamp=datetime.now().isoformat(),- model=f"tavily-{search_depth}",- citations=citations,- search_results=search_results,- usage={},- metadata={"search_depth": search_depth},- )-```diff --git a/src/tools/web_search/utils.py b/src/tools/web_search/utils.pydeleted file mode 100644index 3da3dccca..000000000--- a/src/tools/web_search/utils.py+++ /dev/null@@ -1,18 +0,0 @@-"""Web Search Utilities"""--from datetime import datetime-import json-import os-from typing import Any---def save_results(result: dict[str, Any], output_dir: str, provider: str) -> str:- """Save search results to a JSON file."""- os.makedirs(output_dir, exist_ok=True)- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- output_path = os.path.join(output_dir, f"search_{provider}_{timestamp}.json")-- with open(output_path, "w", encoding="utf-8") as f:- json.dump(result, f, ensure_ascii=False, indent=2)-- return output_pathdiff --git a/src/utils/config_manager.py b/src/utils/config_manager.pyindex a1f937f55..29181b0ad 100644--- a/src/utils/config_manager.py+++ b/src/utils/config_manager.py@@ -85,7 +85,7 @@ class ConfigManager:try:return AppConfig(**migrated).dict()except ValidationError as e:- raise ConfigError("Config validation failed", context={"errors": e.errors()})+ raise ConfigError("Config validation failed", details={"errors": e.errors()})def load_config(self, force_reload: bool = False) -> Dict[str, Any]:"""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/knowledge/page.tsx b/web/app/knowledge/page.tsxindex 459dedf45..198a2e651 100644--- a/web/app/knowledge/page.tsx+++ b/web/app/knowledge/page.tsx@@ -56,7 +56,7 @@ export default function KnowledgePage() {const [files, setFiles] = useState<FileList | null>(null);const [newKbName, setNewKbName] = useState("");const [dragActive, setDragActive] = useState(false);- const [ragProvider, setRagProvider] = useState<string>("raganything");+ const [ragProvider, setRagProvider] = useState<string>("llamaindex");const [ragProviders, setRagProviders] = useState<Array<{ id: string; name: string; description: string }>>([]);@@ -471,7 +471,7 @@ export default function KnowledgePage() {Array.from(files).forEach((file) => {formData.append("files", file);});-+// Add rag_provider to form data if user selected one different from KB's existing providerif (ragProvider) {formData.append("rag_provider", ragProvider);@@ -560,7 +560,7 @@ export default function KnowledgePage() {setCreateModalOpen(false);setFiles(null);setNewKbName("");- setRagProvider("raganything"); // Reset to default+ setRagProvider("llamaindex"); // Reset to default// Delay refresh to get full info (but user can already see the new KB)setTimeout(async () => {@@ -626,7 +626,7 @@ export default function KnowledgePage() {onClick={() => {setFiles(null);setNewKbName("");- setRagProvider("raganything");+ setRagProvider("llamaindex");setCreateModalOpen(true);}}className="bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 px-4 py-2 rounded-lg text-sm font-medium hover:bg-slate-800 dark:hover:bg-slate-200 transition-colors flex items-center gap-2 shadow-lg shadow-slate-900/20"@@ -688,7 +688,9 @@ export default function KnowledgePage() {setTargetKb(kb.name);setFiles(null);// Set RAG provider to KB's existing provider or default- setRagProvider(kb.statistics.rag_provider || "raganything");+ setRagProvider(+ kb.statistics.rag_provider || "llamaindex",+ );setUploadModalOpen(true);}}className="p-2 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-lg text-slate-500 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"@@ -859,7 +861,10 @@ export default function KnowledgePage() {</div>{kb.statistics.rag_provider && (<div className="text-[10px] text-slate-500 dark:text-slate-400">- Provider: <span className="font-semibold text-slate-600 dark:text-slate-300">{kb.statistics.rag_provider}</span>+ Provider:{" "}+ <span className="font-semibold text-slate-600 dark:text-slate-300">+ {kb.statistics.rag_provider}+ </span></div>)}</div>@@ -868,7 +873,10 @@ export default function KnowledgePage() {if (kb.statistics.rag_provider) {return (<div className="mt-2 text-[10px] text-slate-500 dark:text-slate-400">- Provider: <span className="font-semibold text-slate-600 dark:text-slate-300">{kb.statistics.rag_provider}</span>+ Provider:{" "}+ <span className="font-semibold text-slate-600 dark:text-slate-300">+ {kb.statistics.rag_provider}+ </span></div>);}@@ -939,13 +947,36 @@ export default function KnowledgePage() {<><option value="llamaindex">LlamaIndex</option><option value="lightrag">LightRAG</option>- <option value="raganything">RAGAnything</option>+ <option value="raganything">RAG-Anything</option></>)}</select>- <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">- Choose the RAG pipeline for indexing and searching- </p>+ {/* Provider description */}+ <div className="mt-2 p-2.5 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600">+ <p className="text-xs text-slate-600 dark:text-slate-300">+ {(() => {+ const selectedProvider = ragProviders.find(+ (p) => p.id === ragProvider,+ );+ if (selectedProvider?.description) {+ return selectedProvider.description;+ }+ // Fallback descriptions+ const fallbackDescriptions: Record<string, string> = {+ llamaindex:+ "纯向量检索,处理速度最快,适合快速搭建和简单场景。",+ lightrag:+ "轻量级知识图谱检索,快速处理纯文本文档,适合通用文档。",+ raganything:+ "多模态文档处理,支持图表和公式提取,构建知识图谱。适合学术论文和教材。",+ };+ return (+ fallbackDescriptions[ragProvider] ||+ "选择适合您文档类型的 RAG 管道"+ );+ })()}+ </p>+ </div></div><div>@@ -1060,10 +1091,35 @@ export default function KnowledgePage() {<><option value="llamaindex">LlamaIndex</option><option value="lightrag">LightRAG</option>- <option value="raganything">RAGAnything</option>+ <option value="raganything">RAG-Anything</option></>)}</select>+ {/* Provider description */}+ <div className="mt-2 p-2.5 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600">+ <p className="text-xs text-slate-600 dark:text-slate-300">+ {(() => {+ const selectedProvider = ragProviders.find(+ (p) => p.id === ragProvider,+ );+ if (selectedProvider?.description) {+ return selectedProvider.description;+ }+ const fallbackDescriptions: Record<string, string> = {+ llamaindex:+ "纯向量检索,处理速度最快,适合快速搭建和简单场景。",+ lightrag:+ "轻量级知识图谱检索,快速处理纯文本文档,适合通用文档。",+ raganything:+ "多模态文档处理,支持图表和公式提取,构建知识图谱。适合学术论文和教材。",+ };+ return (+ fallbackDescriptions[ragProvider] ||+ "选择适合您文档类型的 RAG 管道"+ );+ })()}+ </p>+ </div><p className="text-xs text-slate-500 dark:text-slate-400 mt-1">Leave as-is to use the KB's existing provider</p>diff --git a/web/app/layout.tsx b/web/app/layout.tsxindex 9e41b2494..95aa3cfd5 100644--- a/web/app/layout.tsx+++ b/web/app/layout.tsx@@ -4,6 +4,7 @@ import "./globals.css";import Sidebar from "@/components/Sidebar";import { GlobalProvider } from "@/context/GlobalContext";import ThemeScript from "@/components/ThemeScript";+import LayoutWrapper from "@/components/LayoutWrapper";// Use Inter font with swap display for better loadingconst font = Inter({@@ -29,12 +30,14 @@ export default function RootLayout({</head><body className={font.className}><GlobalProvider>- <div className="flex h-screen bg-slate-50 dark:bg-slate-900 overflow-hidden transition-colors duration-200">- <Sidebar />- <main className="flex-1 overflow-y-auto bg-slate-50 dark:bg-slate-900">- {children}- </main>- </div>+ <LayoutWrapper>+ <div className="flex h-screen bg-slate-50 dark:bg-slate-900 overflow-hidden transition-colors duration-200">+ <Sidebar />+ <main className="flex-1 overflow-y-auto bg-slate-50 dark:bg-slate-900">+ {children}+ </main>+ </div>+ </LayoutWrapper></GlobalProvider></body></html>diff --git a/web/app/notebook/page.tsx b/web/app/notebook/page.tsxindex 209b36dbc..9ebe2199d 100644--- a/web/app/notebook/page.tsx+++ b/web/app/notebook/page.tsx@@ -27,6 +27,7 @@ import {History,Import,Upload,+ MessageSquare,} from "lucide-react";import ReactMarkdown from "react-markdown";import remarkMath from "remark-math";@@ -37,7 +38,7 @@ import { processLatexContent } from "@/lib/latex";interface NotebookRecord {id: string;- type: "solve" | "question" | "research" | "co_writer";+ type: "solve" | "question" | "research" | "co_writer" | "chat";title: string;user_query: string;output: string;@@ -91,6 +92,8 @@ const getRecordIcon = (type: string) => {return <Microscope className="w-4 h-4" />;case "co_writer":return <PenTool className="w-4 h-4" />;+ case "chat":+ return <MessageSquare className="w-4 h-4" />;default:return <FileText className="w-4 h-4" />;}@@ -106,6 +109,8 @@ const getRecordLabel = (type: string) => {return "Research";case "co_writer":return "Co-Writer";+ case "chat":+ return "Chat";default:return "Record";}@@ -121,6 +126,8 @@ const getRecordColor = (type: string) => {return "text-emerald-500 bg-emerald-50 border-emerald-200";case "co_writer":return "text-amber-500 bg-amber-50 border-amber-200";+ case "chat":+ return "text-cyan-500 bg-cyan-50 border-cyan-200";default:return "text-slate-500 bg-slate-50 border-slate-200";}diff --git a/web/app/page.tsx b/web/app/page.tsxindex 211254631..aa85bcc51 100644--- a/web/app/page.tsx+++ b/web/app/page.tsx@@ -19,6 +19,7 @@ import {Edit3,GraduationCap,PenTool,+ Save,} from "lucide-react";import Link from "next/link";import ReactMarkdown from "react-markdown";@@ -29,6 +30,7 @@ import { useGlobal } from "@/context/GlobalContext";import { apiUrl } from "@/lib/api";import { processLatexContent } from "@/lib/latex";import { getTranslation } from "@/lib/i18n";+import AddToNotebookModal from "@/components/AddToNotebookModal";interface KnowledgeBase {name: string;@@ -50,6 +52,41 @@ export default function HomePage() {const [kbs, setKbs] = useState<KnowledgeBase[]>([]);const chatEndRef = useRef<HTMLDivElement>(null);const inputRef = useRef<HTMLInputElement>(null);+ const [showNotebookModal, setShowNotebookModal] = useState(false);++ // Format chat history for notebook+ const formatChatForNotebook = () => {+ if (chatState.messages.length === 0)+ return { title: "", userQuery: "", output: "" };++ // Use the first user message as title+ const firstUserMsg = chatState.messages.find((m) => m.role === "user");+ const title =+ firstUserMsg?.content.slice(0, 50) ++ (firstUserMsg && firstUserMsg.content.length > 50 ? "..." : "") ||+ "Chat Session";++ // Format all messages as markdown+ const formattedMessages = chatState.messages+ .map((msg, idx) => {+ const roleLabel =+ msg.role === "user" ? "👤 **User**" : "🤖 **Assistant**";+ return `### ${roleLabel}\n\n${msg.content}`;+ })+ .join("\n\n---\n\n");++ // User query is the concatenation of all user messages+ const userQueries = chatState.messages+ .filter((m) => m.role === "user")+ .map((m) => m.content)+ .join("\n\n");++ return {+ title: `Chat: ${title}`,+ userQuery: userQueries,+ output: formattedMessages,+ };+ };// Fetch knowledge basesuseEffect(() => {@@ -333,13 +370,23 @@ export default function HomePage() {)}</div>- <button- onClick={newChatSession}- className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"- >- <Trash2 className="w-3.5 h-3.5" />- {t("New Chat")}- </button>+ <div className="flex items-center gap-2">+ <button+ onClick={() => setShowNotebookModal(true)}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-slate-500 dark:text-slate-400 hover:text-indigo-600 dark:hover:text-indigo-400 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded-lg transition-colors"+ title={t("Save to Notebook")}+ >+ <Save className="w-3.5 h-3.5" />+ {t("Save to Notebook")}+ </button>+ <button+ onClick={newChatSession}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-slate-500 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"+ >+ <Trash2 className="w-3.5 h-3.5" />+ {t("New Chat")}+ </button>+ </div></div>{/* Messages Area */}@@ -478,6 +525,23 @@ export default function HomePage() {</div></>)}++ {/* Add to Notebook Modal */}+ <AddToNotebookModal+ isOpen={showNotebookModal}+ onClose={() => setShowNotebookModal(false)}+ recordType="chat"+ title={formatChatForNotebook().title}+ userQuery={formatChatForNotebook().userQuery}+ output={formatChatForNotebook().output}+ metadata={{+ session_id: chatState.sessionId,+ message_count: chatState.messages.length,+ enable_rag: chatState.enableRag,+ enable_web_search: chatState.enableWebSearch,+ }}+ kbName={chatState.enableRag ? chatState.selectedKb : undefined}+ /></div>);}diff --git a/web/app/question/page.tsx b/web/app/question/page.tsxindex d6854e6c4..eb2c68fd2 100644--- a/web/app/question/page.tsx+++ b/web/app/question/page.tsx@@ -3,22 +3,21 @@import { useState, useEffect } from "react";import {PenTool,- CheckCircle2,- AlertCircle,Loader2,- BookOpen,- BrainCircuit,- Sparkles,RefreshCw,- FileText,- Book,- Upload,Database,- FileQuestion,Activity,+ CheckCircle2,+ BrainCircuit,+ FileText,+ Upload,+ Sparkles,+ Book,Zap,ChevronDown,- ChevronRight,+ ChevronUp,+ AlertCircle,+ Lightbulb,} from "lucide-react";import { useGlobal } from "@/context/GlobalContext";import ReactMarkdown from "react-markdown";@@ -28,7 +27,7 @@ import "katex/dist/katex.min.css";import { apiUrl } from "@/lib/api";import { processLatexContent } from "@/lib/latex";import AddToNotebookModal from "@/components/AddToNotebookModal";-import { QuestionDashboard } from "@/components/question";+import { LogDrawer } from "@/components/question";import { useQuestionReducer } from "@/hooks/useQuestionReducer";export default function QuestionPage() {@@ -42,45 +41,71 @@ export default function QuestionPage() {// Dashboard state for parallel generationconst [dashboardState, dispatchDashboard] = useQuestionReducer();- const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);- // Tab state: "questions" shows the quiz, "process" shows the dashboard- const [activeTab, setActiveTab] = useState<"questions" | "process">(- "questions",- );-- // Local interaction state- const [kbs, setKbs] = useState<string[]>([]);-- // Answering state+ // UI stateconst [activeIdx, setActiveIdx] = useState(0);const [userAnswers, setUserAnswers] = useState<Record<number, string>>({});const [submittedMap, setSubmittedMap] = useState<Record<number, boolean>>({});- const [showValidation, setShowValidation] = useState(false);-- // Notebook modal state+ const [kbs, setKbs] = useState<string[]>([]);+ const [showLogDrawer, setShowLogDrawer] = useState(false);const [showNotebookModal, setShowNotebookModal] = useState(false);+ const [showAnalysis, setShowAnalysis] = useState(false);- // Check if generation is in progress- const isGenerating =- questionState.step === "generating" || questionState.step === "result";+ // Derived state+ const isGenerating = questionState.step === "generating";+ const isComplete = questionState.step === "result";const isConfigMode = questionState.step === "config";+ const totalQuestions = questionState.results.length;+ const currentQuestion = questionState.results[activeIdx];+ const extendedCount = questionState.results.filter(+ (r: any) => r.extended,+ ).length;- // Fetch KBs on mount only+ // Progress info from questionState+ const progress = questionState.progress || {};+ const stage =+ progress.stage ||+ (isGenerating ? "generating" : isComplete ? "complete" : null);+ const subFocuses = progress.subFocuses || [];++ // Fetch KBs on mountuseEffect(() => {- fetch(apiUrl("/api/v1/knowledge/list"))+ let isMounted = true;+ const controller = new AbortController();++ fetch(apiUrl("/api/v1/knowledge/list"), { signal: controller.signal }).then((res) => res.json()).then((data) => {+ if (!isMounted) return;const names = data.map((kb: any) => kb.name);setKbs(names);if (!questionState.selectedKb && names.length > 0) {setQuestionState((prev) => ({ ...prev, selectedKb: names[0] }));}})- .catch((err) => console.error("Failed to fetch KBs:", err));+ .catch((err) => {+ if (err.name !== "AbortError") {+ console.error("Failed to fetch KBs:", err);+ }+ });++ return () => {+ isMounted = false;+ controller.abort();+ };// eslint-disable-next-line react-hooks/exhaustive-deps}, []);+ // Auto-select first question when results come in+ useEffect(() => {+ if (+ questionState.results.length > 0 &&+ activeIdx >= questionState.results.length+ ) {+ setActiveIdx(0);+ }+ }, [questionState.results.length, activeIdx]);+const handleStart = () => {if (questionState.mode === "knowledge") {startQuestionGen(@@ -91,21 +116,18 @@ export default function QuestionPage() {questionState.selectedKb,);} else {- // Mimic mode - use PDF file or pre-parsed directory+ // Mimic mode: don't limit questions by default (process all reference questions)+ // Only limit if user explicitly sets a value via maxQuestions statestartMimicQuestionGen(questionState.uploadedFile,questionState.paperPath,questionState.selectedKb,- questionState.count > 0 ? questionState.count : undefined,+ undefined, // Let backend process all reference questions);}- // Reset interaction statesetUserAnswers({});setSubmittedMap({});setActiveIdx(0);- setShowValidation(false);- // Switch to process tab when generating- setActiveTab("process");};const handleAnswer = (val: string) => {@@ -130,24 +152,24 @@ export default function QuestionPage() {}));};- const currentQuestion = questionState.results[activeIdx];- const totalQuestions = questionState.results.length;- const extendedCount = questionState.results.filter(- (r: any) => r.extended,- ).length;+ const handleReset = () => {+ resetQuestionGen();+ setUserAnswers({});+ setSubmittedMap({});+ setActiveIdx(0);+ };- // Auto-switch to questions tab when generation completes- useEffect(() => {- if (questionState.step === "result" && totalQuestions > 0) {- setActiveTab("questions");- }- }, [questionState.step, totalQuestions]);+ const canStart =+ questionState.mode === "knowledge"+ ? questionState.topic.trim().length > 0+ : questionState.uploadedFile !== null ||+ questionState.paperPath.trim().length > 0;return (- <div className="h-screen flex flex-col animate-fade-in overflow-hidden p-4">+ <div className="h-screen flex gap-0 p-4 animate-fade-in overflow-hidden">{/* Main Panel */}- <div className="flex-1 flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden min-h-0">- {/* Header Row */}+ <div className="flex-1 flex flex-col bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">+ {/* Header */}<div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center backdrop-blur-sm shrink-0"><div className="flex items-center gap-4"><div className="flex items-center gap-2 text-slate-700 dark:text-slate-200 font-semibold">@@ -155,95 +177,65 @@ export default function QuestionPage() {Question Generator</div>- {/* Mode Switching - disabled when generating */}- <div- className={`flex bg-slate-100 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600 ${isGenerating ? "opacity-50" : ""}`}- >- <button- onClick={() =>- !isGenerating &&- setQuestionState((prev) => ({- ...prev,- mode: "knowledge",- }))- }- disabled={isGenerating}- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${- questionState.mode === "knowledge"- ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"- : isGenerating- ? "text-slate-400 dark:text-slate-500 cursor-not-allowed"+ {/* Mode Switching */}+ {isConfigMode && (+ <div className="flex bg-slate-100 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600">+ <button+ onClick={() =>+ setQuestionState((prev) => ({ ...prev, mode: "knowledge" }))+ }+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${+ questionState.mode === "knowledge"+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm": "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- <BrainCircuit className="w-4 h-4" />- Custom- </button>- <button- onClick={() =>- !isGenerating &&- setQuestionState((prev) => ({ ...prev, mode: "mimic" }))- }- disabled={isGenerating}- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${- questionState.mode === "mimic"- ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"- : isGenerating- ? "text-slate-400 dark:text-slate-500 cursor-not-allowed"+ }`}+ >+ <BrainCircuit className="w-4 h-4" />+ Custom+ </button>+ <button+ onClick={() =>+ setQuestionState((prev) => ({ ...prev, mode: "mimic" }))+ }+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${+ questionState.mode === "mimic"+ ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm": "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- <FileText className="w-4 h-4" />- Mimic Exam- </button>- </div>-- {/* Separator */}- <div className="h-6 w-px bg-slate-200 dark:bg-slate-600" />+ }`}+ >+ <FileText className="w-4 h-4" />+ Mimic Exam+ </button>+ </div>+ )}- {/* Questions/Process Tabs */}- <div className="flex bg-slate-100 dark:bg-slate-700 p-1 rounded-lg border border-slate-200 dark:border-slate-600">- <button- onClick={() => !isConfigMode && setActiveTab("questions")}- disabled={isConfigMode}- className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${- !isConfigMode && activeTab === "questions"- ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"- : isConfigMode- ? "text-slate-300 dark:text-slate-500 cursor-not-allowed"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- <FileQuestion className="w-4 h-4" />- Questions- {totalQuestions > 0 && (- <span className="px-1.5 py-0.5 bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300 text-xs rounded-full">- {totalQuestions}- </span>- )}- </button>- <button- onClick={() => !isConfigMode && setActiveTab("process")}- disabled={isConfigMode}- className={`flex items-center gap-2 px-3 py-1.5 rounded-md text-sm font-medium transition-all ${- !isConfigMode && activeTab === "process"- ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"- : isConfigMode- ? "text-slate-300 dark:text-slate-500 cursor-not-allowed"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- <Activity className="w-4 h-4" />- Process- {questionState.step === "generating" && (- <Loader2 className="w-3 h-3 animate-spin text-purple-500 dark:text-purple-400" />- )}- </button>- </div>+ {/* Status indicator when generating/complete */}+ {!isConfigMode && (+ <div className="flex items-center gap-2 text-sm">+ {isGenerating ? (+ <div className="flex items-center gap-2 px-3 py-1 bg-purple-50 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400 rounded-full">+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ <span>+ Generating {totalQuestions}/{questionState.count}...+ </span>+ </div>+ ) : isComplete ? (+ <div className="flex items-center gap-2 px-3 py-1 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 rounded-full">+ <CheckCircle2 className="w-3.5 h-3.5" />+ <span>{totalQuestions} questions</span>+ {extendedCount > 0 && (+ <span className="text-amber-600 dark:text-amber-400">+ ({extendedCount} extended)+ </span>+ )}+ </div>+ ) : null}+ </div>+ )}</div>- <div className="flex items-center gap-4">- {/* Knowledge Base Selection */}+ <div className="flex items-center gap-3">+ {/* Knowledge Base selector */}<div className="flex items-center gap-2"><Database className="w-4 h-4 text-slate-400 dark:text-slate-500" /><select@@ -255,7 +247,7 @@ export default function QuestionPage() {}))}disabled={isGenerating}- className={`text-sm bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-500/20 dark:text-slate-200 ${isGenerating ? "opacity-50 cursor-not-allowed" : ""}`}+ className="text-sm bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:border-purple-400 dark:text-slate-200 disabled:opacity-50">{kbs.map((kb) => (<option key={kb} value={kb}>@@ -265,10 +257,22 @@ export default function QuestionPage() {</select></div>+ {/* Log Drawer Toggle */}+ {!isConfigMode && (+ <button+ onClick={() => setShowLogDrawer(true)}+ className="flex items-center gap-1.5 text-sm text-slate-500 dark:text-slate-400 hover:text-purple-600 dark:hover:text-purple-400 px-3 py-1.5 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded-lg transition-colors"+ >+ <Activity className="w-4 h-4" />+ Logs+ </button>+ )}++ {/* New/Reset button */}{!isConfigMode && (<button- onClick={resetQuestionGen}- className="text-sm flex items-center gap-1.5 text-slate-500 dark:text-slate-400 hover:text-purple-600 dark:hover:text-purple-400 transition-colors px-3 py-1.5 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded-lg border border-slate-200 dark:border-slate-600"+ onClick={handleReset}+ className="flex items-center gap-1.5 text-sm text-slate-500 dark:text-slate-400 hover:text-purple-600 dark:hover:text-purple-400 px-3 py-1.5 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded-lg border border-slate-200 dark:border-slate-600 transition-colors"><RefreshCw className="w-4 h-4" />New@@ -278,11 +282,11 @@ export default function QuestionPage() {</div>{/* Content Area */}- <div className="flex-1 overflow-y-auto bg-slate-50/30 dark:bg-slate-900/30 min-h-0">- {/* MODE: CONFIG - Show config form */}+ <div className="flex-1 overflow-y-auto bg-slate-50/30 dark:bg-slate-900/30">+ {/* Config Mode */}{isConfigMode && (<div className="p-6">- <div className="max-w-2xl mx-auto space-y-8 animate-in fade-in slide-in-from-bottom-4">+ <div className="max-w-2xl mx-auto space-y-6">{/* Mode Info Banner */}<divclassName={`p-4 rounded-xl border ${@@ -321,47 +325,6 @@ export default function QuestionPage() {{/* Knowledge Base Mode Config */}{questionState.mode === "knowledge" && (<>- <div className="grid grid-cols-2 gap-6">- <div className="space-y-2">- <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">- Question Count- </label>- <div className="flex items-center gap-4">- <input- type="range"- min="1"- max="10"- step="1"- value={Math.min(questionState.count, 10)}- onChange={(e) =>- setQuestionState((prev) => ({- ...prev,- count: parseInt(e.target.value),- }))- }- className="flex-1 accent-purple-600 h-2 bg-slate-200 dark:bg-slate-600 rounded-lg appearance-none cursor-pointer"- />- <input- type="number"- min="1"- max="50"- value={questionState.count}- onChange={(e) => {- const val = parseInt(e.target.value) || 1;- setQuestionState((prev) => ({- ...prev,- count: Math.max(1, Math.min(50, val)),- }));- }}- className="w-16 text-center font-bold text-purple-700 dark:text-purple-300 bg-purple-50 dark:bg-purple-900/30 py-1 rounded-md border border-purple-100 dark:border-purple-800 outline-none focus:border-purple-400 focus:ring-2 focus:ring-purple-500/20"- />- </div>- <p className="text-[10px] text-slate-400 dark:text-slate-500">- Use slider (1-10) or type directly (1-50)- </p>- </div>- </div>-<div className="space-y-2"><label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Knowledge Point / Topic@@ -376,64 +339,87 @@ export default function QuestionPage() {}))}placeholder="e.g. Gradient Descent Optimization"- className="w-full p-4 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 transition-all text-lg dark:text-slate-200 dark:placeholder:text-slate-500"+ className="w-full p-4 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 transition-all text-lg dark:text-slate-200 placeholder:text-slate-400"/></div>- <div className="grid grid-cols-2 gap-6">+ <div className="grid grid-cols-3 gap-4">+ <div className="space-y-2">+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">+ Count+ </label>+ <input+ type="number"+ min="1"+ max="50"+ value={questionState.count || ""}+ onChange={(e) => {+ const rawVal = e.target.value;+ // Allow empty input while typing+ if (rawVal === "") {+ setQuestionState((prev) => ({+ ...prev,+ count: 0,+ }));+ return;+ }+ const val = parseInt(rawVal);+ if (!isNaN(val)) {+ setQuestionState((prev) => ({+ ...prev,+ count: Math.min(50, Math.max(0, val)),+ }));+ }+ }}+ onBlur={(e) => {+ // Ensure valid value on blur+ const val = parseInt(e.target.value) || 1;+ setQuestionState((prev) => ({+ ...prev,+ count: Math.max(1, Math.min(50, val)),+ }));+ }}+ className="w-full p-3 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-center outline-none focus:border-purple-500 dark:text-slate-200"+ />+ </div>+<div className="space-y-2"><label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Difficulty</label>- <div className="flex bg-slate-50 dark:bg-slate-700 p-1 rounded-xl border border-slate-200 dark:border-slate-600">- {["easy", "medium", "hard"].map((lvl) => (- <button- key={lvl}- onClick={() =>- setQuestionState((prev) => ({- ...prev,- difficulty: lvl,- }))- }- className={`flex-1 py-2 rounded-lg text-sm font-medium capitalize transition-all ${- questionState.difficulty === lvl- ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- {lvl}- </button>- ))}- </div>+ <select+ value={questionState.difficulty}+ onChange={(e) =>+ setQuestionState((prev) => ({+ ...prev,+ difficulty: e.target.value,+ }))+ }+ className="w-full p-3 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 dark:text-slate-200"+ >+ <option value="easy">Easy</option>+ <option value="medium">Medium</option>+ <option value="hard">Hard</option>+ </select></div><div className="space-y-2"><label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Type</label>- <div className="flex bg-slate-50 dark:bg-slate-700 p-1 rounded-xl border border-slate-200 dark:border-slate-600">- {[- { id: "choice", label: "Multiple Choice" },- { id: "written", label: "Written" },- ].map((t) => (- <button- key={t.id}- onClick={() =>- setQuestionState((prev) => ({- ...prev,- type: t.id,- }))- }- className={`flex-1 py-2 rounded-lg text-sm font-medium transition-all ${- questionState.type === t.id- ? "bg-white dark:bg-slate-600 text-purple-700 dark:text-purple-400 shadow-sm"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- {t.label}- </button>- ))}- </div>+ <select+ value={questionState.type}+ onChange={(e) =>+ setQuestionState((prev) => ({+ ...prev,+ type: e.target.value,+ }))+ }+ className="w-full p-3 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 dark:text-slate-200"+ >+ <option value="choice">Multiple Choice</option>+ <option value="written">Written</option>+ </select></div></div></>@@ -441,8 +427,7 @@ export default function QuestionPage() {{/* Mimic Mode Config */}{questionState.mode === "mimic" && (- <div className="space-y-6">- {/* PDF Upload Section */}+ <div className="space-y-5"><div className="space-y-2"><label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Upload Exam Paper (PDF)@@ -457,7 +442,7 @@ export default function QuestionPage() {/><labelhtmlFor="pdf-upload"- className="flex items-center justify-center gap-3 w-full p-6 border-2 border-dashed border-slate-300 dark:border-slate-600 rounded-xl cursor-pointer hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50/50 dark:hover:bg-purple-900/20 transition-all"+ className="flex items-center justify-center gap-3 w-full py-8 border-2 border-dashed border-slate-300 dark:border-slate-600 rounded-xl cursor-pointer hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50/50 dark:hover:bg-purple-900/20 transition-all">{questionState.uploadedFile ? (<div className="flex items-center gap-3 text-purple-700 dark:text-purple-400">@@ -472,19 +457,16 @@ export default function QuestionPage() {1024 /1024).toFixed(2)}{" "}- MB - Click to change+ MB</p></div></div>) : (<div className="text-center text-slate-500 dark:text-slate-400">- <Upload className="w-8 h-8 mx-auto mb-2 text-slate-400 dark:text-slate-500" />- <p className="font-medium">- Click to upload PDF exam paper- </p>+ <Upload className="w-8 h-8 mx-auto mb-2 text-slate-400" />+ <p className="font-medium">Click to upload PDF</p><p className="text-xs">- The system will automatically parse and generate- questions+ The system will parse and generate questions</p></div>)}@@ -492,19 +474,17 @@ export default function QuestionPage() {</div></div>- {/* Divider */}<div className="flex items-center gap-3"><div className="flex-1 h-px bg-slate-200 dark:bg-slate-600"></div>- <span className="text-xs text-slate-400 dark:text-slate-500 font-medium">+ <span className="text-xs text-slate-400 dark:text-slate-500">OR</span><div className="flex-1 h-px bg-slate-200 dark:bg-slate-600"></div></div>- {/* Pre-parsed Directory (Optional) */}<div className="space-y-2"><label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">- Pre-parsed Directory (Optional)+ Pre-parsed Directory</label><inputtype="text"@@ -517,67 +497,17 @@ export default function QuestionPage() {}))}placeholder="e.g. 2211asm1"- className="w-full p-3 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 transition-all dark:text-slate-200 dark:placeholder:text-slate-500"+ className="w-full p-3 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 dark:text-slate-200 placeholder:text-slate-400"/>- <p className="text-xs text-slate-500 dark:text-slate-400">- Or enter a pre-parsed paper directory name- </p>- </div>-- <div className="space-y-2">- <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">- Max Questions (Optional)- </label>- <div className="flex items-center gap-4">- <input- type="number"- min="1"- max="20"- placeholder="All"- value={questionState.count || ""}- onChange={(e) => {- const val = e.target.value- ? parseInt(e.target.value)- : 0;- setQuestionState((prev) => ({- ...prev,- count: val > 0 ? Math.min(20, val) : 0,- }));- }}- className="w-24 p-2 text-center bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 dark:text-slate-200"- />- <span className="text-sm text-slate-500 dark:text-slate-400">- Leave empty to generate all questions from the paper- </span>- </div>- </div>-- <div className="p-4 bg-gradient-to-r from-purple-50 to-blue-50 dark:from-purple-900/30 dark:to-blue-900/30 border border-purple-200 dark:border-purple-800 rounded-xl text-sm text-slate-700 dark:text-slate-300">- <p className="font-medium mb-2 text-purple-800 dark:text-purple-300">- ✨ How Mimic Mode Works- </p>- <ol className="text-xs space-y-1 list-decimal list-inside text-slate-600 dark:text-slate-400">- <li>Upload your exam paper PDF</li>- <li>Select the relevant knowledge base</li>- <li>- The system will automatically: parse PDF → extract- questions → generate similar new questions- </li>- <li>Progress will be displayed in real-time</li>- </ol></div></div>)}+ {/* Generate Button */}<buttononClick={handleStart}- disabled={- questionState.mode === "knowledge"- ? !questionState.topic.trim()- : !questionState.uploadedFile &&- !questionState.paperPath.trim()- }- className="w-full py-4 bg-purple-600 text-white rounded-xl font-bold text-lg shadow-lg shadow-purple-500/30 hover:bg-purple-700 hover:shadow-purple-500/50 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"+ disabled={!canStart || isGenerating}+ className="w-full py-4 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-xl font-bold text-lg shadow-lg shadow-purple-500/30 hover:from-purple-700 hover:to-indigo-700 hover:shadow-purple-500/50 active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"><Sparkles className="w-5 h-5" />Generate Questions@@ -586,102 +516,126 @@ export default function QuestionPage() {</div>)}- {/* QUESTIONS TAB */}- {!isConfigMode && activeTab === "questions" && (- <div className="p-6 h-full">- {/* Question Number Selector */}- {totalQuestions > 0 && (- <div className="mb-6 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-4">- <div className="flex items-center justify-between mb-3">- <span className="text-sm font-semibold text-slate-700 dark:text-slate-200">+ {/* Question Display Mode */}+ {!isConfigMode && (+ <div className="flex h-full">+ {/* Left: Question List */}+ <div className="w-72 flex-shrink-0 border-r border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800 flex flex-col">+ <div className="p-3 border-b border-slate-100 dark:border-slate-700">+ <div className="flex items-center justify-between">+ <span className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Questions</span>- <span className="text-sm text-slate-500 dark:text-slate-400">- {totalQuestions} / {questionState.count} completed- {extendedCount > 0 && (- <span className="ml-2 text-amber-600 dark:text-amber-400">- ({extendedCount} extended)- </span>- )}+ <span className="text-xs text-slate-400">+ {totalQuestions}/{questionState.count}</span></div>- <div className="flex flex-wrap gap-2">- {questionState.results.map((result: any, idx: number) => (- <button- key={idx}- onClick={() => setActiveIdx(idx)}- className={`w-10 h-10 rounded-full flex items-center justify-center font-semibold text-sm border-2 transition-all ${- activeIdx === idx- ? "bg-purple-600 text-white border-purple-600 shadow-lg shadow-purple-500/30 scale-110"- : result.extended- ? "bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 border-amber-300 dark:border-amber-600 hover:border-amber-400 dark:hover:border-amber-500 hover:bg-amber-100 dark:hover:bg-amber-900/50"- : submittedMap[idx]- ? "bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-300 dark:border-emerald-600 hover:border-emerald-400 dark:hover:border-emerald-500"- : "bg-white dark:bg-slate-700 text-slate-600 dark:text-slate-300 border-slate-200 dark:border-slate-600 hover:border-purple-300 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-900/30"- }`}- >- {submittedMap[idx] && activeIdx !== idx ? (- <CheckCircle2 className="w-5 h-5" />- ) : result.extended && activeIdx !== idx ? (- <Zap className="w-4 h-4" />- ) : (- idx + 1- )}- </button>- ))}- </div>+ {isGenerating && questionState.count > 0 && (+ <div className="mt-2 h-1 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden">+ <div+ className="h-full bg-purple-500 transition-all duration-300"+ style={{+ width: `${(totalQuestions / questionState.count) * 100}%`,+ }}+ />+ </div>+ )}</div>- )}-- {/* No Questions Yet */}- {totalQuestions === 0 && questionState.step === "generating" && (- <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 gap-4">- <div className="relative">- <div className="w-16 h-16 border-4 border-purple-100 dark:border-purple-900 border-t-purple-500 rounded-full animate-spin"></div>- <div className="absolute inset-0 flex items-center justify-center">- <BrainCircuit className="w-6 h-6 text-purple-500 dark:text-purple-400" />+ <div className="flex-1 overflow-y-auto p-2">+ {totalQuestions === 0 && isGenerating && (+ <div className="flex flex-col items-center justify-center h-full text-slate-400">+ <Loader2 className="w-8 h-8 animate-spin mb-2" />+ <p className="text-sm">Generating...</p></div>- </div>- <p className="font-medium text-slate-600 dark:text-slate-300">- Generating questions...- </p>- <p className="text-sm text-center max-w-xs">- Switch to the Process tab to see detailed progress- </p>+ )}+ {questionState.results.map((result: any, idx: number) => (+ <button+ key={idx}+ onClick={() => setActiveIdx(idx)}+ className={`w-full text-left px-3 py-2.5 rounded-lg transition-all mb-1 ${+ activeIdx === idx+ ? "bg-purple-50 dark:bg-purple-900/30 border-l-2 border-purple-500"+ : "hover:bg-slate-50 dark:hover:bg-slate-700"+ }`}+ >+ <div className="flex items-start gap-3">+ <div+ className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${+ result.extended+ ? "bg-amber-100 dark:bg-amber-900/40 text-amber-600"+ : submittedMap[idx]+ ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600"+ : activeIdx === idx+ ? "bg-purple-100 dark:bg-purple-900/40 text-purple-600"+ : "bg-slate-100 dark:bg-slate-700 text-slate-500"+ }`}+ >+ {result.extended ? (+ <Zap className="w-3.5 h-3.5" />+ ) : submittedMap[idx] ? (+ <CheckCircle2 className="w-3.5 h-3.5" />+ ) : (+ idx + 1+ )}+ </div>+ <div className="flex-1 min-w-0">+ <p+ className={`text-sm line-clamp-2 ${activeIdx === idx ? "text-slate-800 dark:text-slate-100 font-medium" : "text-slate-600 dark:text-slate-300"}`}+ >+ {result.question.question.slice(0, 80)}...+ </p>+ <div className="flex items-center gap-2 mt-1">+ <span className="text-xs text-slate-400 uppercase">+ {result.question.type ||+ result.question.question_type}+ </span>+ {result.extended && (+ <span className="text-xs text-amber-500">+ Extended+ </span>+ )}+ </div>+ </div>+ </div>+ </button>+ ))}</div>- )}+ </div>- {/* Question Display - Left-Right Layout */}- {totalQuestions > 0 && currentQuestion && (- <div className="flex-1 flex gap-6 animate-in fade-in slide-in-from-right-4">- {/* Left Side: Question Area */}- <div className="flex-1 bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden flex flex-col">+ {/* Right: Question Detail */}+ <div className="flex-1 flex flex-col overflow-hidden">+ {currentQuestion ? (+ <>{/* Question Header */}- <div className="px-6 py-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/30 dark:bg-slate-800/30">- <div className="flex items-center gap-2">- <span className="px-3 py-1 bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-xs font-bold uppercase rounded-full border border-purple-100 dark:border-purple-800">+ <div className="px-6 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between bg-white dark:bg-slate-800">+ <div className="flex items-center gap-3">+ <span className="text-sm font-medium text-slate-500">+ Question {activeIdx + 1}+ </span>+ <span className="px-2 py-0.5 text-xs font-bold uppercase tracking-wider bg-slate-100 dark:bg-slate-700 text-slate-500 rounded">{currentQuestion.question.type ||currentQuestion.question.question_type}</span>{currentQuestion.extended && (- <span className="px-3 py-1 bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-xs font-bold uppercase rounded-full border border-amber-200 dark:border-amber-800 flex items-center gap-1">+ <span className="px-2 py-0.5 text-xs font-bold uppercase tracking-wider bg-amber-100 dark:bg-amber-900/40 text-amber-600 rounded flex items-center gap-1"><Zap className="w-3 h-3" />Extended</span>)}- <button- onClick={() => setShowNotebookModal(true)}- className="ml-auto text-xs font-medium text-indigo-500 dark:text-indigo-400 hover:text-indigo-600 dark:hover:text-indigo-300 flex items-center gap-1 px-2 py-1 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded-lg transition-colors"- >- <Book className="w-3 h-3" />- Add to Notebook- </button></div>+ <button+ onClick={() => setShowNotebookModal(true)}+ className="text-xs text-indigo-500 hover:text-indigo-600 flex items-center gap-1 px-2 py-1 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 rounded-lg transition-colors"+ >+ <Book className="w-3 h-3" />+ Add to Notebook+ </button></div>{/* Question Content */}- <div className="p-6 flex-1 overflow-y-auto">- <h3 className="text-lg font-medium text-slate-800 dark:text-slate-200 leading-relaxed mb-6 prose dark:prose-invert max-w-none">+ <div className="flex-1 overflow-y-auto p-6 space-y-6">+ {/* Question Text */}+ <div className="prose prose-slate dark:prose-invert max-w-none"><ReactMarkdownremarkPlugins={[remarkMath]}rehypePlugins={[rehypeKatex]}@@ -690,51 +644,71 @@ export default function QuestionPage() {currentQuestion.question.question,)}</ReactMarkdown>- </h3>+ </div>- {/* Options / Input Area */}+ {/* Options or Input */}{(currentQuestion.question.question_type === "choice" ||currentQuestion.question.type === "choice") &&- currentQuestion.question.options ? (+ currentQuestion.question.options &&+ Object.keys(currentQuestion.question.options).length >+ 0 ? (<div className="space-y-3">{Object.entries(currentQuestion.question.options).map(- ([key, val]) => (- <button- key={key}- onClick={() => handleAnswer(key)}- disabled={submittedMap[activeIdx]}- className={`w-full text-left p-4 rounded-xl border transition-all flex items-start gap-4 prose dark:prose-invert max-w-none ${- userAnswers[activeIdx] === key- ? submittedMap[activeIdx]- ? key ===- currentQuestion.question.correct_answer- ? "bg-green-50 dark:bg-green-900/30 border-green-500 text-green-800 dark:text-green-200"- : "bg-red-50 dark:bg-red-900/30 border-red-500 text-red-800 dark:text-red-200"- : "bg-purple-50 dark:bg-purple-900/30 border-purple-500 text-purple-900 dark:text-purple-200 shadow-sm"- : submittedMap[activeIdx] &&- key ===- currentQuestion.question- .correct_answer- ? "bg-green-50 dark:bg-green-900/30 border-green-300 dark:border-green-600 text-green-800 dark:text-green-200"- : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600 hover:bg-slate-50 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200"- }`}- >- <span className="font-bold shrink-0 w-6">- {key}.- </span>- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}+ ([key, val]) => {+ const isSelected = userAnswers[activeIdx] === key;+ const isCorrect =+ key === currentQuestion.question.correct_answer;+ const showCorrectness = submittedMap[activeIdx];++ return (+ <button+ key={key}+ onClick={() =>+ !submittedMap[activeIdx] &&+ handleAnswer(key)+ }+ disabled={submittedMap[activeIdx]}+ className={`w-full text-left p-4 rounded-xl border transition-all flex items-start gap-4 prose dark:prose-invert max-w-none ${+ showCorrectness+ ? isCorrect+ ? "bg-emerald-50 dark:bg-emerald-900/30 border-emerald-300"+ : isSelected+ ? "bg-red-50 dark:bg-red-900/30 border-red-300"+ : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600"+ : isSelected+ ? "bg-purple-50 dark:bg-purple-900/30 border-purple-300"+ : "bg-white dark:bg-slate-700 border-slate-200 dark:border-slate-600 hover:border-purple-300"+ }`}>- {processLatexContent(String(val))}- </ReactMarkdown>- {submittedMap[activeIdx] &&- key ===- currentQuestion.question.correct_answer && (- <CheckCircle2 className="w-5 h-5 text-green-600 dark:text-green-400 ml-auto shrink-0" />+ <span+ className={`flex-shrink-0 w-7 h-7 rounded-full flex items-center justify-center text-sm font-bold ${+ showCorrectness && isCorrect+ ? "bg-emerald-500 text-white"+ : showCorrectness &&+ isSelected &&+ !isCorrect+ ? "bg-red-500 text-white"+ : isSelected+ ? "bg-purple-500 text-white"+ : "bg-slate-100 dark:bg-slate-600 text-slate-600 dark:text-slate-300"+ }`}+ >+ {key}+ </span>+ <div className="flex-1">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(String(val))}+ </ReactMarkdown>+ </div>+ {showCorrectness && isCorrect && (+ <CheckCircle2 className="w-5 h-5 text-emerald-500 flex-shrink-0" />)}- </button>- ),+ </button>+ );+ },)}</div>) : (@@ -743,327 +717,250 @@ export default function QuestionPage() {onChange={(e) => handleAnswer(e.target.value)}disabled={submittedMap[activeIdx]}placeholder="Type your answer here..."- className="w-full h-48 p-4 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 outline-none resize-none text-slate-800 dark:text-slate-200 placeholder:text-slate-400 dark:placeholder:text-slate-500"+ className="w-full h-40 p-4 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl outline-none focus:border-purple-500 focus:ring-2 focus:ring-purple-500/10 resize-none text-slate-800 dark:text-slate-200 placeholder:text-slate-400"/>)}- </div>- {/* Submit Button Area */}- <div className="p-4 border-t border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800 flex gap-3">- {!submittedMap[activeIdx] ? (- <button- onClick={handleSubmit}- disabled={!userAnswers[activeIdx]}- className="flex-1 py-3 bg-purple-600 text-white rounded-xl font-bold shadow-lg shadow-purple-500/20 hover:bg-purple-700 disabled:opacity-50 disabled:shadow-none transition-all"- >- Submit Answer- </button>- ) : (- <>- <div className="flex-1 py-3 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 rounded-xl font-medium text-center border border-emerald-200 dark:border-emerald-800 flex items-center justify-center gap-2">- <CheckCircle2 className="w-4 h-4" />- Submitted+ {/* Answer & Explanation (shown after submit) */}+ {submittedMap[activeIdx] && (+ <div className="space-y-4 pt-4 border-t border-slate-100 dark:border-slate-700">+ {/* Correct Answer */}+ <div className="p-4 bg-emerald-50 dark:bg-emerald-900/20 rounded-xl border border-emerald-100 dark:border-emerald-800">+ <p className="text-xs font-bold text-emerald-600 uppercase tracking-wider mb-2">+ Correct Answer+ </p>+ <div className="text-emerald-800 dark:text-emerald-200 prose prose-sm dark:prose-invert max-w-none">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(+ String(+ currentQuestion.question.correct_answer,+ ),+ )}+ </ReactMarkdown>+ </div></div>- {activeIdx < questionState.results.length - 1 && (- <button- onClick={() => setActiveIdx(activeIdx + 1)}- className="flex-1 py-3 bg-purple-600 text-white rounded-xl font-bold shadow-lg shadow-purple-500/20 hover:bg-purple-700 transition-all flex items-center justify-center gap-2"- >- Next Question- <ChevronRight className="w-4 h-4" />- </button>- )}- </>- )}- </div>- </div>- {/* Right Side: Answer & Validation Area (shown after submit) */}- <div className="w-[400px] flex flex-col gap-4">- {/* Answer & Explanation (shown after submit) */}- {submittedMap[activeIdx] ? (- <>- {/* Collapsible Validation Report - only shown after submit */}- <div- className={`rounded-xl border overflow-hidden ${- currentQuestion.extended- ? "bg-amber-50 dark:bg-amber-900/30 border-amber-200 dark:border-amber-800"- : "bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700"- }`}- >- <button- onClick={() => setShowValidation(!showValidation)}- className={`w-full px-4 py-3 flex items-center justify-between text-sm font-medium transition-colors ${- currentQuestion.extended- ? "text-amber-800 dark:text-amber-300 hover:bg-amber-100 dark:hover:bg-amber-900/50"- : "text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700"- }`}- >- <div className="flex items-center gap-2">- <AlertCircle className="w-4 h-4" />- Validation Report- <span- className={`px-2 py-0.5 text-xs rounded-full ${- currentQuestion.extended- ? "bg-amber-200 dark:bg-amber-800 text-amber-800 dark:text-amber-200"- : "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"- }`}- >- {currentQuestion.rounds || 1} round- {(currentQuestion.rounds || 1) > 1 ? "s" : ""}- </span>+ {/* Explanation */}+ {currentQuestion.question.explanation && (+ <div>+ <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">+ Explanation+ </p>+ <div className="text-slate-700 dark:text-slate-300 prose prose-sm dark:prose-invert max-w-none">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(+ currentQuestion.question.explanation,+ )}+ </ReactMarkdown>+ </div></div>- {showValidation ? (- <ChevronDown className="w-4 h-4" />- ) : (- <ChevronRight className="w-4 h-4" />- )}- </button>+ )}- {showValidation && (- <div className="px-4 pb-4 animate-in fade-in slide-in-from-top-2">- <div- className={`p-3 rounded-lg text-sm ${- currentQuestion.extended- ? "bg-amber-100/50 dark:bg-amber-900/30"- : "bg-white dark:bg-slate-700 border border-slate-100 dark:border-slate-600"- }`}+ {/* Relevance Analysis (collapsible) */}+ {currentQuestion.validation && (+ <div className="border border-slate-200 dark:border-slate-600 rounded-xl overflow-hidden">+ <button+ onClick={() => setShowAnalysis(!showAnalysis)}+ className="w-full px-4 py-3 flex items-center justify-between bg-slate-50 dark:bg-slate-700 hover:bg-slate-100 dark:hover:bg-slate-600 transition-colors">- {/* Header with status */}- <div className="flex items-center gap-2 mb-3 font-semibold flex-wrap">- {currentQuestion.extended ? (- <>- <Zap className="w-4 h-4 text-amber-600 dark:text-amber-400" />- <span className="text-amber-800 dark:text-amber-300">- Extended Question- </span>- </>- ) : currentQuestion.validation?.relevance ? (- <>- <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />- <span className="text-emerald-700 dark:text-emerald-300">- Relevance:{" "}- {currentQuestion.validation- .relevance === "high"- ? "High"- : "Partial"}- </span>- <span- className={`px-2 py-0.5 text-xs rounded-full ${- currentQuestion.validation- .relevance === "high"- ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"- : "bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300"- }`}- >- {currentQuestion.validation- .relevance === "high"- ? "Fully Covered by KB"- : "Extends Beyond KB"}- </span>- </>- ) : (- <>- <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />- <span className="text-emerald-700 dark:text-emerald-300">- Validation Passed- </span>- </>- )}+ <div className="flex items-center gap-2 text-sm">+ <AlertCircle className="w-4 h-4 text-slate-400" />+ <span className="font-medium text-slate-600 dark:text-slate-300">+ Relevance Analysis+ </span>+ <span className="text-xs px-1.5 py-0.5 bg-slate-200 dark:bg-slate-600 text-slate-500 rounded">+ {currentQuestion.rounds || 1} round+ {(currentQuestion.rounds || 1) > 1+ ? "s"+ : ""}+ </span></div>-- {/* KB Coverage - for custom mode */}- {currentQuestion.validation?.kb_coverage && (- <div className="mb-3">- <p className="text-xs font-semibold text-emerald-700 dark:text-emerald-400 uppercase tracking-wider mb-1.5 flex items-center gap-1">- <Database className="w-3 h-3" />- Knowledge Base Coverage- </p>- <div className="text-slate-700 dark:text-slate-300 text-xs leading-relaxed bg-emerald-50/50 dark:bg-emerald-900/20 p-2 rounded border border-emerald-100 dark:border-emerald-800 prose prose-xs dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(- currentQuestion.validation- .kb_coverage,- )}- </ReactMarkdown>- </div>- </div>- )}-- {/* Extension Points - for custom mode when relevance is partial */}- {currentQuestion.validation- ?.extension_points && (- <div className="mb-3">- <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wider mb-1.5 flex items-center gap-1">- <Zap className="w-3 h-3" />- Extension Points- </p>- <div className="text-amber-900 dark:text-amber-200 text-xs leading-relaxed bg-amber-50/50 dark:bg-amber-900/20 p-2 rounded border border-amber-100 dark:border-amber-800 prose prose-xs dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(- currentQuestion.validation- .extension_points,- )}- </ReactMarkdown>- </div>- </div>+ {showAnalysis ? (+ <ChevronUp className="w-4 h-4 text-slate-400" />+ ) : (+ <ChevronDown className="w-4 h-4 text-slate-400" />)}+ </button>- {/* KB Connection - for extended questions */}- {currentQuestion.extended &&- currentQuestion.validation?.kb_connection && (- <div className="mb-3">- <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wider mb-1.5">- KB Connection- </p>- <div className="text-amber-900 dark:text-amber-200 text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none">+ {showAnalysis && (+ <div className="px-4 py-3 space-y-3 text-sm bg-white dark:bg-slate-800">+ {currentQuestion.validation.kb_coverage && (+ <div>+ <div className="flex items-center gap-1.5 text-xs font-bold text-emerald-600 uppercase tracking-wider mb-1">+ <Database className="w-3 h-3" />+ KB Coverage+ </div>+ <div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdownremarkPlugins={[remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(currentQuestion.validation- .kb_connection,+ .kb_coverage,)}</ReactMarkdown></div></div>)}-- {/* Extended Aspects - for extended questions */}- {currentQuestion.extended &&- currentQuestion.validation- ?.extended_aspect && (- <div className="mb-3">- <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wider mb-1.5">- Extended Aspects- </p>- <div className="text-amber-900 dark:text-amber-200 text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none">+ {currentQuestion.validation+ .extension_points && (+ <div>+ <div className="flex items-center gap-1.5 text-xs font-bold text-amber-600 uppercase tracking-wider mb-1">+ <Zap className="w-3 h-3" />+ Extension Points+ </div>+ <div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none"><ReactMarkdownremarkPlugins={[remarkMath]}rehypePlugins={[rehypeKatex]}>{processLatexContent(currentQuestion.validation- .extended_aspect,+ .extension_points,)}</ReactMarkdown></div></div>)}-- {/* Reasoning - legacy field */}- {currentQuestion.validation?.reasoning && (- <div>- <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1.5">- Reasoning- </p>- <div className="text-slate-700 dark:text-slate-300 text-xs leading-relaxed prose prose-xs dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(- currentQuestion.validation.reasoning,- )}- </ReactMarkdown>+ {currentQuestion.extended &&+ currentQuestion.validation+ .kb_connection && (+ <div>+ <div className="flex items-center gap-1.5 text-xs font-bold text-amber-600 uppercase tracking-wider mb-1">+ <Database className="w-3 h-3" />+ KB Connection+ </div>+ <div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(+ currentQuestion.validation+ .kb_connection,+ )}+ </ReactMarkdown>+ </div>+ </div>+ )}+ {currentQuestion.extended &&+ currentQuestion.validation+ .extended_aspect && (+ <div>+ <div className="flex items-center gap-1.5 text-xs font-bold text-orange-600 uppercase tracking-wider mb-1">+ <Lightbulb className="w-3 h-3" />+ Extended Aspects+ </div>+ <div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(+ currentQuestion.validation+ .extended_aspect,+ )}+ </ReactMarkdown>+ </div>+ </div>+ )}+ {currentQuestion.validation.reasoning && (+ <div>+ <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">+ Reasoning+ </div>+ <div className="text-slate-600 dark:text-slate-300 prose prose-xs dark:prose-invert max-w-none">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(+ currentQuestion.validation+ .reasoning,+ )}+ </ReactMarkdown>+ </div></div>- </div>- )}- </div>+ )}+ </div>+ )}</div>)}</div>+ )}+ </div>- {/* Answer & Explanation */}- <div className="flex-1 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden flex flex-col animate-in fade-in slide-in-from-bottom-4">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-emerald-50 dark:bg-emerald-900/30">- <h4 className="text-emerald-800 dark:text-emerald-300 font-semibold flex items-center gap-2">- <BookOpen className="w-4 h-4" />- Answer & Explanation- </h4>- </div>- <div className="p-4 flex-1 overflow-y-auto">- <div className="mb-4 p-3 bg-emerald-50 dark:bg-emerald-900/30 rounded-lg border border-emerald-100 dark:border-emerald-800">- <p className="text-xs font-semibold text-emerald-600 dark:text-emerald-400 uppercase tracking-wider mb-1">- Correct Answer- </p>- <div className="text-emerald-800 dark:text-emerald-200 text-base leading-relaxed [&_.katex]:text-emerald-800 dark:[&_.katex]:text-emerald-200 [&_.katex-display]:my-3 [&_.katex-display]:overflow-x-auto prose prose-emerald dark:prose-invert max-w-none prose-p:my-2 prose-p:leading-relaxed">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(- String(- currentQuestion.question.correct_answer ||- "",- ),- )}- </ReactMarkdown>- </div>- </div>-- <div className="prose prose-sm prose-slate dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(- currentQuestion.question.explanation,- )}- </ReactMarkdown>- </div>- </div>+ {/* Footer Actions */}+ <div className="px-6 py-4 border-t border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800">+ {!submittedMap[activeIdx] ? (+ <button+ onClick={handleSubmit}+ disabled={!userAnswers[activeIdx]}+ className="w-full py-3 bg-purple-600 text-white rounded-xl font-bold shadow-lg shadow-purple-500/20 hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all"+ >+ Submit Answer+ </button>+ ) : (+ <div className="flex items-center justify-center gap-2 py-3 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 rounded-xl">+ <CheckCircle2 className="w-4 h-4" />+ <span className="font-medium">Submitted</span></div>- </>- ) : (- <div className="flex-1 bg-slate-50 dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 flex items-center justify-center">- <div className="text-center text-slate-400 dark:text-slate-500 p-6">- <BookOpen className="w-10 h-10 mx-auto mb-3 opacity-30" />- <p className="text-sm font-medium">Answer Hidden</p>- <p className="text-xs mt-1">- Submit your answer to reveal+ )}+ </div>+ </>+ ) : (+ <div className="flex-1 flex items-center justify-center text-slate-400">+ <div className="text-center">+ {isGenerating ? (+ <>+ <Loader2 className="w-12 h-12 animate-spin mx-auto mb-3 text-purple-500" />+ <p className="text-lg font-medium text-slate-600 dark:text-slate-300">+ Generating questions...</p>- </div>- </div>- )}+ <p className="text-sm">+ View progress in the Logs panel+ </p>+ </>+ ) : (+ <>+ <Book className="w-12 h-12 mx-auto mb-3 opacity-30" />+ <p className="text-sm">+ Select a question to view details+ </p>+ </>+ )}+ </div></div>- </div>- )}- </div>- )}-- {/* PROCESS TAB */}- {!isConfigMode && activeTab === "process" && (- <div className="h-full">- <QuestionDashboard- state={dashboardState}- globalProgress={questionState.progress}- globalLogs={questionState.logs}- globalResults={questionState.results}- globalTopic={questionState.topic}- globalDifficulty={questionState.difficulty}- globalType={questionState.type}- globalCount={questionState.count}- globalStep={questionState.step}- globalMode={- questionState.mode === "knowledge" ? "custom" : "mimic"- }- selectedTaskId={selectedTaskId}- onTaskSelect={setSelectedTaskId}- tokenStats={questionState.tokenStats}- />+ )}+ </div></div>)}</div></div>+ {/* Log Drawer */}+ <LogDrawer+ isOpen={showLogDrawer}+ onClose={() => setShowLogDrawer(false)}+ logs={questionState.logs || []}+ stage={stage}+ progress={progress.progress}+ subFocuses={subFocuses}+ mode={questionState.mode === "knowledge" ? "custom" : "mimic"}+ topic={questionState.topic}+ difficulty={questionState.difficulty}+ questionType={questionState.type}+ count={questionState.count}+ onClearLogs={() => setQuestionState((prev) => ({ ...prev, logs: [] }))}+ />+{/* Add to Notebook Modal */}{currentQuestion && (<AddToNotebookModaldiff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsxindex c33fdedfe..34c78ff61 100644--- a/web/app/settings/page.tsx+++ b/web/app/settings/page.tsx@@ -1,2584 +1,1275 @@"use client";-import { useState, useEffect, useRef } from "react";+import { useState, useEffect } from "react";import {Settings as SettingsIcon,- Sun,- Moon,- Globe,- Save,- RotateCcw,- Loader2,- Check,- Server,- AlertCircle,+ Brain,Database,- Search,- MessageSquare,Volume2,- Cpu,- Key,- Brain,+ Search,+ Plus,+ Trash2,+ Check,+ Loader2,+ AlertCircle,+ Server,Eye,EyeOff,RefreshCw,- CheckCircle,- XCircle,- Info,- Sliders,+ ChevronDown,+ Sun,+ Moon,+ Globe,+ Pencil,+ TestTube,} from "lucide-react";import { apiUrl } from "@/lib/api";-import { getTranslation } from "@/lib/i18n";-import { setTheme } from "@/lib/theme";-import { debounce } from "@/lib/debounce";-import { useGlobal } from "@/context/GlobalContext";+import { getTranslation } from "@/lib/i18n";-// --- Types matching backend -----interface UISettings {- theme: "light" | "dark";- language: "zh" | "en";- output_language: "zh" | "en";-}--interface EnvInfo {- model: string;- [key: string]: string;-}--// Config is dynamic, but we know some structure-interface ConfigData {- system?: {- language?: string;- [key: string]: any;- };- tools?: {- rag_tool?: {- kb_base_dir?: string;- default_kb?: string;- [key: string]: any;- };- run_code?: {- workspace?: string;- allowed_roots?: string[];- language?: string;- timeout?: number;- sandbox?: boolean;- [key: string]: any;- };- web_search?: {- enabled?: boolean;- provider?: string;- max_results?: number;- consolidation?: "none" | "template" | "llm";- consolidation_template?: string;- [key: string]: any;- };- [key: string]: any;- };- logging?: {- level?: string;- [key: string]: any;- };- tts?: {- default_voice?: string;- default_language?: string;- [key: string]: any;- };- [key: string]: any;-}--interface FullSettingsResponse {- ui: UISettings;- config: ConfigData;- env: EnvInfo;-}+// Language options+const LANGUAGE_OPTIONS = [+ { value: "en" as const, label: "English" },+ { value: "zh" as const, label: "中文" },+];-// Web search config types (fetched from backend)-interface WebSearchProvider {+// Types+interface ConfigItem {id: string;name: string;- description: string;- keyEnv: string;- supports_answer: boolean;- requires_api_key: boolean;-}--interface WebSearchConfigResponse {- enabled: boolean;provider: string;- consolidation: string | null;- providers: WebSearchProvider[];- consolidation_types: string[]; // ["none", "template", "llm"]- template_providers: string[]; // Providers that support template consolidation (serper, jina, etc.)- config_source: "env" | "yaml" | "default";-}--// Environment variable types-interface EnvVarInfo {- key: string;- value: string;- description: string;- category: string;- required: boolean;- default: string;- sensitive: boolean;- is_set: boolean;-}--interface EnvCategoryInfo {- id: string;- name: string;- description: string;- icon: string;+ base_url?: string;+ api_key?: string;+ model?: string;+ dimensions?: number;+ voice?: string;+ api_version?: string;+ is_default?: boolean;+ is_active?: boolean;}-interface EnvConfigResponse {- variables: EnvVarInfo[];- categories: EnvCategoryInfo[];+interface ConfigStatus {+ configured: boolean;+ active_config_id: string;+ active_config_name: string;+ model: string | null;+ provider: string | null;+ env_configured: Record<string, boolean>;+ total_configs: number;}-interface TestResults {- llm: { status: string; model: string | null; error: string | null };- embedding: { status: string; model: string | null; error: string | null };- tts: { status: string; model: string | null; error: string | null };+interface FullStatus {+ llm: ConfigStatus;+ embedding: ConfigStatus;+ tts: ConfigStatus;+ search: ConfigStatus;}-interface LLMProvider {- name: string;- binding: string;- base_url: string;- api_key: string;- model: string;- is_active: boolean;- provider_type: "api" | "local";- requires_key: boolean;-}--interface LLMModeInfo {- mode: "api" | "local" | "hybrid";- active_provider: {- name: string;- model: string;- provider_type: "api" | "local";- binding: string;- } | null;- env_configured: boolean;- effective_source: "env" | "provider";+interface PortsInfo {+ backend_port: number;+ frontend_port: number;}-// Tab types-type SettingsTab = "general" | "environment" | "local_models";+type ConfigType = "llm" | "embedding" | "tts" | "search";+type TabType = "overview" | ConfigType;++// Provider options+// Provider options - Cloud services first, then local deployments+const PROVIDER_OPTIONS: Record<ConfigType, string[]> = {+ llm: [+ // Cloud providers+ "openai",+ "anthropic",+ "azure_openai",+ "deepseek",+ "openrouter",+ // Local providers+ "ollama",+ "lm_studio",+ "vllm",+ "llama_cpp",+ ],+ embedding: [+ // Cloud providers+ "openai",+ "azure_openai",+ "jina",+ "cohere",+ "huggingface",+ "google",+ // Local providers+ "ollama",+ "lm_studio",+ ],+ tts: ["openai", "azure_openai"],+ search: ["perplexity", "tavily", "exa", "jina", "serper", "baidu"],+};++// Local providers that don't require API keys+const LOCAL_PROVIDERS = ["ollama", "lm_studio", "vllm", "llama_cpp"];++// Default base URLs for local providers+const LOCAL_PROVIDER_URLS: Record<string, string> = {+ ollama: "http://localhost:11434/v1",+ lm_studio: "http://localhost:1234/v1",+ vllm: "http://localhost:8000/v1",+ llama_cpp: "http://localhost:8080/v1",+};++// Voice options for TTS+const VOICE_OPTIONS = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];export default function SettingsPage() {- const { uiSettings, refreshSettings } = useGlobal();+ const { uiSettings, updateTheme, updateLanguage } = useGlobal();const t = (key: string) => getTranslation(uiSettings.language, key);- const [activeTab, setActiveTab] = useState<SettingsTab>("general");- const [data, setData] = useState<FullSettingsResponse | null>(null);- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);- const [saveSuccess, setSaveSuccess] = useState(false);- const [error, setError] = useState("");-- // Edit states- const [editedConfig, setEditedConfig] = useState<ConfigData | null>(null);- const [editedUI, setEditedUI] = useState<UISettings | null>(null);-- // --- Helper Data ----- interface ProviderPreset {- id: string;- name: string;- binding:- | "openai"- | "azure_openai"- | "ollama"- | "anthropic"- | "gemini"- | "groq"- | "openrouter";- base_url?: string;- default_model: string;- models: string[];- requires_key: boolean;- help_text?: string;- }-- // Local deployment presets only - cloud providers should use Environment Variables tab- const PROVIDER_PRESETS: ProviderPreset[] = [- {- id: "ollama",- name: "Ollama",- binding: "openai",- base_url: "http://localhost:11434/v1",- default_model: "llama3.2",- models: [- "llama3.2",- "llama3.3",- "qwen2.5",- "qwen3",- "mistral-nemo",- "deepseek-r1",- "gemma2",- "phi3",- ],- requires_key: false,- help_text:- "Ollama runs models locally. Default: http://localhost:11434/v1. Run 'ollama serve' first.",- },- {- id: "lmstudio",- name: "LM Studio",- binding: "openai",- base_url: "http://127.0.0.1:1234",- default_model: "local-model",- models: [],- requires_key: false,- help_text:- "LM Studio provides a local OpenAI-compatible API. Default port: 1234. Use 'Refresh Models' to auto-detect loaded models.",- },- {- id: "llamacpp",- name: "llama.cpp Server",- binding: "openai",- base_url: "http://localhost:8080/v1",- default_model: "local-model",- models: [],- requires_key: false,- help_text:- "llama.cpp server with OpenAI-compatible API. Default port: 8080.",- },- {- id: "vllm",- name: "vLLM",- binding: "openai",- base_url: "http://localhost:8000/v1",- default_model: "local-model",- models: [],- requires_key: false,- help_text: "vLLM high-throughput inference server. Default port: 8000.",- },- {- id: "custom",- name: "Custom Local Server",- binding: "openai",- base_url: "http://localhost:8000/v1",- default_model: "",- models: [],- requires_key: false,- help_text:- "Any OpenAI-compatible local server. Configure the URL and model manually.",- },- ];- // Environment variables states- const [envConfig, setEnvConfig] = useState<EnvConfigResponse | null>(null);- const [editedEnvVars, setEditedEnvVars] = useState<Record<string, string>>(- {},- );- const [showSensitive, setShowSensitive] = useState<Record<string, boolean>>(- {},- );- const [envSaving, setEnvSaving] = useState(false);- const [envSaveSuccess, setEnvSaveSuccess] = useState(false);- const [envError, setEnvError] = useState("");- const [testResults, setTestResults] = useState<TestResults | null>(null);- const [testing, setTesting] = useState(false);- // Individual service testing states- const [testingService, setTestingService] = useState<Record<string, boolean>>(- {},- );- const [serviceTestResults, setServiceTestResults] = useState<- Record<- string,- {- status: string;- model: string | null;- error: string | null;- response_time_ms: number | null;- message: string | null;- }- >- >({});-- // LLM Providers state- const [providers, setProviders] = useState<LLMProvider[]>([]);- const [loadingProviders, setLoadingProviders] = useState(false);- const [editingProvider, setEditingProvider] = useState<LLMProvider | null>(- null,- ); // null means adding new- const [selectedPresetId, setSelectedPresetId] = useState<string>("ollama");- const [customModelInput, setCustomModelInput] = useState(true);- const [showProviderForm, setShowProviderForm] = useState(false);- const [testProviderResult, setTestProviderResult] = useState<{- success: boolean;- message: string;- } | null>(null);- const [testingProvider, setTestingProvider] = useState(false);- const [fetchedModels, setFetchedModels] = useState<string[]>([]);- const [fetchingModels, setFetchingModels] = useState(false);- const [savingProvider, setSavingProvider] = useState(false);- const [providerError, setProviderError] = useState<string | null>(null);- const [originalProviderName, setOriginalProviderName] = useState<- string | null- >(null);-- // LLM Mode state- const [llmModeInfo, setLlmModeInfo] = useState<LLMModeInfo | null>(null);- const [providerTypeFilter, setProviderTypeFilter] = useState<- "all" | "api" | "local"- >("all");-- // Create debounced theme save function- const debouncedSaveTheme = useRef(- debounce(async (themeValue: "light" | "dark", uiSettings: UISettings) => {- try {- await fetch(apiUrl("/api/v1/settings/ui"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...uiSettings, theme: themeValue }),- });- } catch (err) {- // Silently fail - theme is still saved to localStorage- }- }, 500),- ).current;-- // RAG providers state- const [ragProviders, setRagProviders] = useState<- Array<{- id: string;- name: string;- description: string;- supported_modes: string[];- }>- >([]);- const [currentRagProvider, setCurrentRagProvider] =- useState<string>("raganything");- const [loadingRagProviders, setLoadingRagProviders] = useState(false);-- // Web search config state (fetched from backend)- const [webSearchConfig, setWebSearchConfig] =- useState<WebSearchConfigResponse | null>(null);+ const [activeTab, setActiveTab] = useState<TabType>("overview");+ const [status, setStatus] = useState<FullStatus | null>(null);+ const [ports, setPorts] = useState<PortsInfo | null>(null);+ const [loading, setLoading] = useState(true);+ // Load initial datauseEffect(() => {- fetchSettings();- fetchEnvConfig();- fetchRagProviders();- fetchLLMMode();- fetchWebSearchConfig();- if (activeTab === "local_models") {- fetchProviders();- }- }, [uiSettings, activeTab]);-- const fetchLLMMode = async () => {- try {- const res = await fetch(apiUrl("/api/v1/config/llm/mode/"));- if (res.ok) {- const data = await res.json();- setLlmModeInfo(data);- }- } catch (err) {- console.error("Failed to fetch LLM mode:", err);- }- };+ loadStatus();+ loadPorts();+ }, []);- const fetchProviders = async () => {- setLoadingProviders(true);+ const loadStatus = async () => {try {- const res = await fetch(apiUrl("/api/v1/config/llm/"));+ const res = await fetch(apiUrl("/api/v1/config/status"));if (res.ok) {const data = await res.json();- setProviders(data);+ setStatus(data);}- } catch (err) {- console.error("Failed to fetch providers:", err);+ } catch (e) {+ console.error("Failed to load config status:", e);} finally {- setLoadingProviders(false);+ setLoading(false);}};- const fetchRagProviders = async () => {- setLoadingRagProviders(true);+ const loadPorts = async () => {try {- const res = await fetch(apiUrl("/api/v1/settings/rag/providers"));+ const res = await fetch(apiUrl("/api/v1/config/ports"));if (res.ok) {const data = await res.json();- setRagProviders(data.providers || []);- setCurrentRagProvider(data.current || "lightrag");+ setPorts(data);}- } catch (err) {- console.error("Failed to fetch RAG providers:", err);- } finally {- setLoadingRagProviders(false);+ } catch (e) {+ console.error("Failed to load ports:", e);}};- const fetchWebSearchConfig = async () => {- try {- const res = await fetch(apiUrl("/api/v1/settings/web-search/config"));- if (res.ok) {- const data: WebSearchConfigResponse = await res.json();- setWebSearchConfig(data);- }- } catch (err) {- console.error("Failed to fetch web search config:", err);- }- };+ const tabs: { id: TabType; label: string; icon: React.ReactNode }[] = [+ {+ id: "overview",+ label: "Overview",+ icon: <SettingsIcon className="w-4 h-4" />,+ },+ { id: "llm", label: "LLM", icon: <Brain className="w-4 h-4" /> },+ {+ id: "embedding",+ label: "Embedding",+ icon: <Database className="w-4 h-4" />,+ },+ { id: "tts", label: "TTS", icon: <Volume2 className="w-4 h-4" /> },+ { id: "search", label: "Search", icon: <Search className="w-4 h-4" /> },+ ];- const fetchModels = async () => {- if (!editingProvider || !editingProvider.base_url) return;- setFetchingModels(true);- setFetchedModels([]);+ if (loading) {+ return (+ <div className="min-h-screen bg-slate-50 dark:bg-slate-900 flex items-center justify-center">+ <Loader2 className="w-8 h-8 animate-spin text-blue-500" />+ </div>+ );+ }- try {- const preset = PROVIDER_PRESETS.find((p) => p.id === selectedPresetId);- const requiresKey = preset ? preset.requires_key : true;+ return (+ <div className="min-h-screen bg-slate-50 dark:bg-slate-900">+ <div className="max-w-6xl mx-auto p-6">+ {/* Header */}+ <div className="flex items-center gap-3 mb-6">+ <div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-xl">+ <SettingsIcon className="w-6 h-6 text-blue-600 dark:text-blue-400" />+ </div>+ <div>+ <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">+ {uiSettings.language === "zh" ? "设置" : "Settings"}+ </h1>+ <p className="text-sm text-slate-500 dark:text-slate-400">+ {uiSettings.language === "zh"+ ? "配置 AI 服务和界面偏好"+ : "Configure your AI services and preferences"}+ </p>+ </div>+ </div>- const res = await fetch(apiUrl("/api/v1/config/llm/models/"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...editingProvider, requires_key: requiresKey }),- });+ {/* General Settings - Theme & Language */}+ <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4 mb-6">+ <div className="flex flex-wrap items-center gap-6">+ {/* Theme Toggle */}+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400">+ {uiSettings.theme === "dark" ? (+ <Moon className="w-4 h-4" />+ ) : (+ <Sun className="w-4 h-4" />+ )}+ <span>{uiSettings.language === "zh" ? "主题" : "Theme"}</span>+ </div>+ <div className="flex p-1 bg-slate-100 dark:bg-slate-700 rounded-lg">+ <button+ onClick={() => updateTheme("light")}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm transition-all ${+ uiSettings.theme === "light"+ ? "bg-white dark:bg-slate-600 text-slate-900 dark:text-slate-100 shadow-sm"+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"+ }`}+ >+ <Sun className="w-3.5 h-3.5" />+ {uiSettings.language === "zh" ? "浅色" : "Light"}+ </button>+ <button+ onClick={() => updateTheme("dark")}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm transition-all ${+ uiSettings.theme === "dark"+ ? "bg-white dark:bg-slate-600 text-slate-900 dark:text-slate-100 shadow-sm"+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"+ }`}+ >+ <Moon className="w-3.5 h-3.5" />+ {uiSettings.language === "zh" ? "深色" : "Dark"}+ </button>+ </div>+ </div>- const data = await res.json();- if (- data.success &&- Array.isArray(data.models) &&- data.models.length > 0- ) {- setFetchedModels(data.models);- setCustomModelInput(false);- } else {- // Fallback to preset models if available- if (preset && preset.models.length > 0) {- setFetchedModels(preset.models);- if (!data.success) {- console.warn(- "Backend model fetch failed, using presets:",- data.message,- );- }- } else {- alert(`No models found. ${data.message || ""}`);- }- }- } catch (err) {- console.error(err);- const preset = PROVIDER_PRESETS.find((p) => p.id === selectedPresetId);- if (preset && preset.models.length > 0) {- setFetchedModels(preset.models);- } else {- alert("Failed to connect to backend for model fetching.");- }- } finally {- setFetchingModels(false);- }- };+ {/* Separator */}+ <div className="h-8 w-px bg-slate-200 dark:bg-slate-700 hidden sm:block" />- const handleProviderSave = async (provider: LLMProvider) => {- setSavingProvider(true);- setProviderError(null);- try {- // 1. Validate model exists at the provider (optional)- setProviderError("Validating model...");-- const preset = PROVIDER_PRESETS.find((p) => p.id === selectedPresetId);- const requiresKey = preset ? preset.requires_key : true;-- let isModelValid = false;- try {- const modelCheckRes = await fetch(- apiUrl("/api/v1/config/llm/models/"),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...provider, requires_key: requiresKey }),- },- );+ {/* Language Selector */}+ <div className="flex items-center gap-3">+ <div className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400">+ <Globe className="w-4 h-4" />+ <span>+ {uiSettings.language === "zh" ? "语言" : "Language"}+ </span>+ </div>+ <div className="flex p-1 bg-slate-100 dark:bg-slate-700 rounded-lg">+ {LANGUAGE_OPTIONS.map((lang) => (+ <button+ key={lang.value}+ onClick={() => updateLanguage(lang.value)}+ className={`px-3 py-1.5 rounded-md text-sm transition-all ${+ uiSettings.language === lang.value+ ? "bg-white dark:bg-slate-600 text-slate-900 dark:text-slate-100 shadow-sm"+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"+ }`}+ >+ {lang.label}+ </button>+ ))}+ </div>+ </div>+ </div>+ </div>- const modelData = await modelCheckRes.json();- if (modelData.success && Array.isArray(modelData.models)) {- const normalizeModel = (m: string) => m.split(":")[0].toLowerCase();- const enteredModel = provider.model;- const normalizedEntered = normalizeModel(enteredModel);+ {/* Tabs */}+ <div className="flex gap-1 p-1 bg-slate-100 dark:bg-slate-800 rounded-xl mb-6">+ {tabs.map((tab) => (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id)}+ className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${+ activeTab === tab.id+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"+ : "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"+ }`}+ >+ {tab.icon}+ {tab.label}+ </button>+ ))}+ </div>- const isMatch = modelData.models.some(- (m: string) =>- m === enteredModel || normalizeModel(m) === normalizedEntered,- );+ {/* Content */}+ <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">+ {activeTab === "overview" && (+ <OverviewTab status={status} ports={ports} onRefresh={loadStatus} />+ )}+ {activeTab === "llm" && (+ <ConfigTab+ configType="llm"+ title="LLM Configuration"+ description="Configure language model providers"+ onUpdate={loadStatus}+ />+ )}+ {activeTab === "embedding" && (+ <ConfigTab+ configType="embedding"+ title="Embedding Configuration"+ description="Configure embedding model providers"+ onUpdate={loadStatus}+ showDimensions+ />+ )}+ {activeTab === "tts" && (+ <ConfigTab+ configType="tts"+ title="TTS Configuration"+ description="Configure text-to-speech providers"+ onUpdate={loadStatus}+ showVoice+ />+ )}+ {activeTab === "search" && (+ <ConfigTab+ configType="search"+ title="Search Configuration"+ description="Configure web search providers"+ onUpdate={loadStatus}+ isSearchConfig+ />+ )}+ </div>+ </div>+ </div>+ );+}- if (!isMatch) {- const availableModels = modelData.models.slice(0, 5).join(", ");- const warning = `Model "${enteredModel}" not found at provider. Available: ${availableModels}${modelData.models.length > 5 ? "..." : ""}. Continue anyway?`;- if (!confirm(warning)) {- setSavingProvider(false);- setProviderError(null);- return;- }- } else {- isModelValid = true;- }- } else {- // Model fetch failed but proceed with save- console.warn("Model validation failed:", modelData.message);- }- } catch (validationErr) {- console.warn("Model validation error:", validationErr);- // Continue with save even if validation fails- }+// Overview Tab Component+function OverviewTab({+ status,+ ports,+ onRefresh,+}: {+ status: FullStatus | null;+ ports: PortsInfo | null;+ onRefresh: () => void;+}) {+ const services = [+ { key: "llm" as const, label: "LLM", icon: Brain, color: "purple" },+ {+ key: "embedding" as const,+ label: "Embedding",+ icon: Database,+ color: "indigo",+ },+ { key: "tts" as const, label: "TTS", icon: Volume2, color: "emerald" },+ { key: "search" as const, label: "Search", icon: Search, color: "amber" },+ ];- setProviderError(- isModelValid ? "Model verified. Saving..." : "Saving...",- );+ return (+ <div className="p-6 space-y-6">+ {/* Refresh Button */}+ <div className="flex justify-end">+ <button+ onClick={onRefresh}+ className="flex items-center gap-2 px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"+ >+ <RefreshCw className="w-4 h-4" />+ Refresh+ </button>+ </div>- // 2. Proceed with save- const isUpdate =- originalProviderName !== null && originalProviderName !== "";- const method = isUpdate ? "PUT" : "POST";- const url = isUpdate- ? apiUrl(- `/api/v1/config/llm/${encodeURIComponent(originalProviderName!)}`,- )- : apiUrl("/api/v1/config/llm/");+ {/* Service Status Cards */}+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {services.map((service) => {+ const s = status?.[service.key];+ const Icon = service.icon;+ const isConfigured = s?.configured;++ return (+ <div+ key={service.key}+ className={`p-4 rounded-xl border ${+ isConfigured+ ? "border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-900/20"+ : "border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50"+ }`}+ >+ <div className="flex items-start justify-between">+ <div className="flex items-center gap-3">+ <div+ className={`p-2 rounded-lg ${+ isConfigured+ ? "bg-green-100 dark:bg-green-800/50"+ : "bg-slate-100 dark:bg-slate-700"+ }`}+ >+ <Icon+ className={`w-5 h-5 ${+ isConfigured+ ? "text-green-600 dark:text-green-400"+ : "text-slate-400"+ }`}+ />+ </div>+ <div>+ <h3 className="font-semibold text-slate-900 dark:text-slate-100">+ {service.label}+ </h3>+ <p className="text-sm text-slate-500 dark:text-slate-400">+ {s?.active_config_name || "Not configured"}+ </p>+ </div>+ </div>+ {isConfigured ? (+ <Check className="w-5 h-5 text-green-500" />+ ) : (+ <AlertCircle className="w-5 h-5 text-slate-400" />+ )}+ </div>+ {s?.model && (+ <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-700">+ <div className="flex items-center gap-2 text-sm">+ <span className="text-slate-500 dark:text-slate-400">+ Model:+ </span>+ <span className="font-mono text-slate-700 dark:text-slate-300">+ {s.model}+ </span>+ </div>+ {s.provider && (+ <div className="flex items-center gap-2 text-sm mt-1">+ <span className="text-slate-500 dark:text-slate-400">+ Provider:+ </span>+ <span className="text-slate-700 dark:text-slate-300">+ {s.provider}+ </span>+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>- const res = await fetch(url, {- method,- headers: { "Content-Type": "application/json" },- body: JSON.stringify(provider),- });+ {/* Port Information */}+ {ports && (+ <div className="p-4 rounded-xl border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50">+ <div className="flex items-center gap-2 mb-3">+ <Server className="w-5 h-5 text-slate-400" />+ <h3 className="font-semibold text-slate-900 dark:text-slate-100">+ Port Configuration+ </h3>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div>+ <span className="text-sm text-slate-500 dark:text-slate-400">+ Backend Port+ </span>+ <p className="font-mono text-lg text-slate-700 dark:text-slate-300">+ {ports.backend_port}+ </p>+ </div>+ <div>+ <span className="text-sm text-slate-500 dark:text-slate-400">+ Frontend Port+ </span>+ <p className="font-mono text-lg text-slate-700 dark:text-slate-300">+ {ports.frontend_port}+ </p>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}++// Configuration Tab Component+function ConfigTab({+ configType,+ title,+ description,+ onUpdate,+ showDimensions = false,+ showVoice = false,+ isSearchConfig = false,+}: {+ configType: ConfigType;+ title: string;+ description: string;+ onUpdate: () => void;+ showDimensions?: boolean;+ showVoice?: boolean;+ isSearchConfig?: boolean;+}) {+ const [configs, setConfigs] = useState<ConfigItem[]>([]);+ const [loading, setLoading] = useState(true);+ const [showAddForm, setShowAddForm] = useState(false);+ const [editingConfig, setEditingConfig] = useState<ConfigItem | null>(null);+ const [testing, setTesting] = useState<string | null>(null);+ const [testResult, setTestResult] = useState<{+ success: boolean;+ message: string;+ } | null>(null);++ useEffect(() => {+ loadConfigs();+ }, [configType]);+ const loadConfigs = async () => {+ try {+ const res = await fetch(apiUrl(`/api/v1/config/${configType}`));if (res.ok) {- fetchProviders();- setShowProviderForm(false);- setEditingProvider(null);- setOriginalProviderName(null);- } else {- const err = await res.json();- setProviderError(err.detail || "Failed to save provider");+ const data = await res.json();+ setConfigs(data.configs || []);}- } catch (err) {- console.error(err);- setProviderError("An error occurred: " + (err as any).message);+ } catch (e) {+ console.error(`Failed to load ${configType} configs:`, e);} finally {- setSavingProvider(false);+ setLoading(false);}};- const handleDeleteProvider = async (name: string) => {- if (!confirm(`Delete provider ${name}?`)) return;+ const setActive = async (configId: string) => {try {- let url;- if (!name) {- // Handle empty name using query param endpoint- url = apiUrl("/api/v1/config/llm/?name=");- } else {- url = apiUrl(`/api/v1/config/llm/${encodeURIComponent(name)}`);- }-- const res = await fetch(url, {- method: "DELETE",- });+ const res = await fetch(+ apiUrl(`/api/v1/config/${configType}/${configId}/active`),+ {+ method: "POST",+ },+ );if (res.ok) {- fetchProviders();- } else {- const err = await res.json();- alert(`Failed to delete provider: ${err.detail || res.statusText}`);+ loadConfigs();+ onUpdate();}- } catch (err) {- console.error(err);- alert("Failed to delete provider: " + (err as any).message);+ } catch (e) {+ console.error("Failed to set active config:", e);}};- const handleActivateProvider = async (name: string) => {+ const deleteConfig = async (configId: string) => {+ if (!confirm("Are you sure you want to delete this configuration?")) return;+try {- const res = await fetch(apiUrl("/api/v1/config/llm/active/"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name }),- });- if (res.ok) fetchProviders();- } catch (err) {- console.error(err);+ const res = await fetch(+ apiUrl(`/api/v1/config/${configType}/${configId}`),+ {+ method: "DELETE",+ },+ );+ if (res.ok) {+ loadConfigs();+ onUpdate();+ }+ } catch (e) {+ console.error("Failed to delete config:", e);}};- const handleTestProvider = async (provider: LLMProvider) => {- setTestingProvider(true);- setTestProviderResult(null);- try {- // Find preset to check if key is required- const preset = PROVIDER_PRESETS.find((p) => p.id === selectedPresetId);- const requiresKey = preset ? preset.requires_key : true;+ const testConnection = async (config: ConfigItem) => {+ // Search configs don't support testing+ if (isSearchConfig) return;- const res = await fetch(apiUrl("/api/v1/config/llm/test/"), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...provider, requires_key: requiresKey }),- });- const data = await res.json();- setTestProviderResult(data);- } catch (err) {- setTestProviderResult({ success: false, message: "Connection failed" });- } finally {- setTestingProvider(false);- }- };+ setTesting(config.id);+ setTestResult(null);- const fetchSettings = async () => {try {- const res = await fetch(apiUrl("/api/v1/settings/"));- if (res.ok) {- const responseData = await res.json();- setData(responseData);- setEditedConfig(JSON.parse(JSON.stringify(responseData.config)));- if (!editedUI) {- const uiData = JSON.parse(JSON.stringify(responseData.ui));- // localStorage takes priority over backend- const storedTheme = localStorage.getItem("deeptutor-theme");- if (storedTheme === "light" || storedTheme === "dark") {- uiData.theme = storedTheme;- }- setEditedUI(uiData);- // Apply theme if present- if (uiData.theme) {- applyTheme(uiData.theme);- }- }- } else {- setError("Failed to load settings");- }- } catch (err) {- setError("Failed to connect to backend");+ // Use the config ID based test endpoint - this resolves use_env references on the backend+ const res = await fetch(+ apiUrl(`/api/v1/config/${configType}/${config.id}/test`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ },+ );+ const data = await res.json();+ setTestResult(data);+ } catch (e) {+ setTestResult({ success: false, message: "Connection test failed" });} finally {- setLoading(false);+ setTesting(null);}};- const fetchEnvConfig = async () => {- try {- const res = await fetch(apiUrl("/api/v1/settings/env/"));- if (res.ok) {- const responseData: EnvConfigResponse = await res.json();- setEnvConfig(responseData);- const initialValues: Record<string, string> = {};- responseData.variables.forEach((v) => {- initialValues[v.key] = v.value;- });- setEditedEnvVars(initialValues);- // Auto test on load- testEnvConfig();- }- } catch (err) {- console.error("Failed to fetch env config:", err);- }- };+ if (loading) {+ return (+ <div className="p-8 flex justify-center">+ <Loader2 className="w-6 h-6 animate-spin text-blue-500" />+ </div>+ );+ }- const handleEnvVarChange = (key: string, value: string) => {- setEditedEnvVars((prev) => ({ ...prev, [key]: value }));-- // Sync SEARCH_PROVIDER env var with config dropdown- 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 = {};- if (value) {- newConfig.tools.web_search.provider = value;- } else {- delete newConfig.tools.web_search.provider;- }- return newConfig;- });- }- };+ return (+ <div className="p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div>+ <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">+ {title}+ </h2>+ <p className="text-sm text-slate-500 dark:text-slate-400">+ {description}+ </p>+ </div>+ <button+ onClick={() => setShowAddForm(!showAddForm)}+ className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"+ >+ <Plus className="w-4 h-4" />+ Add Configuration+ </button>+ </div>- const toggleSensitiveVisibility = (key: string) => {- setShowSensitive((prev) => ({ ...prev, [key]: !prev[key] }));- };+ {/* Add/Edit Form */}+ {(showAddForm || editingConfig) && (+ <ConfigForm+ configType={configType}+ showDimensions={showDimensions}+ showVoice={showVoice}+ isSearchConfig={isSearchConfig}+ editConfig={editingConfig}+ onSuccess={() => {+ setShowAddForm(false);+ setEditingConfig(null);+ loadConfigs();+ onUpdate();+ }}+ onCancel={() => {+ setShowAddForm(false);+ setEditingConfig(null);+ }}+ />+ )}++ {/* Test Result */}+ {testResult && (+ <div+ className={`mb-4 p-3 rounded-lg text-sm ${+ testResult.success+ ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800"+ : "bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800"+ }`}+ >+ {testResult.message}+ </div>+ )}++ {/* Configuration List */}+ <div className="space-y-3">+ {configs.map((config) => (+ <div+ key={config.id}+ className={`p-4 rounded-xl border transition-all ${+ config.is_active+ ? "border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20"+ : "border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50"+ }`}+ >+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ {config.is_active && (+ <div className="w-2 h-2 rounded-full bg-blue-500" />+ )}+ <div>+ <div className="flex items-center gap-2">+ <span className="font-medium text-slate-900 dark:text-slate-100">+ {config.name}+ </span>+ {config.is_default && (+ <span className="px-2 py-0.5 text-xs bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-400 rounded">+ Default+ </span>+ )}+ {config.is_active && (+ <span className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 rounded">+ Active+ </span>+ )}+ </div>+ <div className="flex items-center gap-3 mt-1 text-sm text-slate-500 dark:text-slate-400">+ <span>Provider: {config.provider}</span>+ {config.model && <span>Model: {config.model}</span>}+ {showDimensions && config.dimensions && (+ <span>Dimensions: {config.dimensions}</span>+ )}+ {showVoice && config.voice && (+ <span>Voice: {config.voice}</span>+ )}+ </div>+ </div>+ </div>+ <div className="flex items-center gap-2">+ {!config.is_active && (+ <button+ onClick={() => setActive(config.id)}+ className="px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"+ >+ Set Active+ </button>+ )}+ {!isSearchConfig && (+ <button+ onClick={() => testConnection(config)}+ disabled={testing === config.id}+ className="px-3 py-1.5 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ >+ {testing === config.id ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ "Test"+ )}+ </button>+ )}+ {!config.is_default && (+ <button+ onClick={() => {+ setEditingConfig(config);+ setShowAddForm(false);+ }}+ className="p-1.5 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ title="Edit"+ >+ <Pencil className="w-4 h-4" />+ </button>+ )}+ {!config.is_default && (+ <button+ onClick={() => deleteConfig(config.id)}+ className="p-1.5 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"+ title="Delete"+ >+ <Trash2 className="w-4 h-4" />+ </button>+ )}+ </div>+ </div>+ </div>+ ))}- const handleEnvSave = async () => {- setEnvSaving(true);- setEnvSaveSuccess(false);- setEnvError("");+ {configs.length === 0 && (+ <div className="text-center py-8 text-slate-500 dark:text-slate-400">+ No configurations found. Add one to get started.+ </div>+ )}+ </div>+ </div>+ );+}- try {- const updates = Object.entries(editedEnvVars)- .filter(([key, value]) => {- const original = envConfig?.variables.find((v) => v.key === key);- if (- original?.sensitive &&- value.includes("*") &&- value === original.value- ) {- return false;- }- return true;- })- .map(([key, value]) => ({ key, value }));-- const res = await fetch(apiUrl("/api/v1/settings/env/"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ variables: updates }),- });+// Configuration Form Component (Add/Edit)+function ConfigForm({+ configType,+ showDimensions,+ showVoice,+ isSearchConfig,+ editConfig,+ onSuccess,+ onCancel,+}: {+ configType: ConfigType;+ showDimensions: boolean;+ showVoice: boolean;+ isSearchConfig: boolean;+ editConfig?: ConfigItem | null;+ onSuccess: () => void;+ onCancel: () => void;+}) {+ const isEditMode = !!editConfig;+ const [saving, setSaving] = useState(false);+ const [testing, setTesting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [testResult, setTestResult] = useState<{+ success: boolean;+ message: string;+ } | null>(null);- if (!res.ok) {- const errorData = await res.json();- throw new Error(- errorData.detail?.errors?.join(", ") || "Failed to save",- );- }+ // Helper to check if a value uses env reference format {use_env: "VAR_NAME"}+ const isEnvReference = (value: any): boolean => {+ return !!(value && typeof value === "object" && "use_env" in value);+ };- setEnvSaveSuccess(true);- setTimeout(() => setEnvSaveSuccess(false), 2000);+ // Helper to get display value - returns empty string if env reference, otherwise the value+ const getDisplayValue = (value: any): string => {+ if (isEnvReference(value)) return "";+ return typeof value === "string" ? value : "";+ };- await fetchEnvConfig();- await testEnvConfig();- } catch (err: any) {- setEnvError(err.message || "Failed to save environment variables");- } finally {- setEnvSaving(false);+ // Check initial env reference states (computed once based on editConfig)+ const initialUseEnvBaseUrl = editConfig+ ? isEnvReference(editConfig.base_url)+ : false;+ const initialUseEnvApiKey = editConfig+ ? isEnvReference(editConfig.api_key)+ : false;++ // Form state - initialize from editConfig if editing, handle env references+ const [name, setName] = useState(editConfig?.name || "");+ const [provider, setProvider] = useState(+ editConfig?.provider || PROVIDER_OPTIONS[configType][0],+ );+ const [baseUrl, setBaseUrl] = useState(+ editConfig ? getDisplayValue(editConfig.base_url) : "",+ );+ const [useEnvBaseUrl, setUseEnvBaseUrl] =+ useState<boolean>(initialUseEnvBaseUrl);+ const [apiKey, setApiKey] = useState(""); // Never pre-fill API key for security+ const [useEnvApiKey, setUseEnvApiKey] =+ useState<boolean>(initialUseEnvApiKey);+ const [showApiKey, setShowApiKey] = useState(false);+ const [model, setModel] = useState(editConfig?.model || "");+ const [dimensions, setDimensions] = useState(editConfig?.dimensions || 3072);+ const [voice, setVoice] = useState(editConfig?.voice || "alloy");++ // Check if current provider is local (doesn't require API key)+ const isLocalProvider = LOCAL_PROVIDERS.includes(provider);++ // Auto-fill base URL when switching to local provider+ const handleProviderChange = (newProvider: string) => {+ setProvider(newProvider);+ if (+ LOCAL_PROVIDERS.includes(newProvider) &&+ LOCAL_PROVIDER_URLS[newProvider]+ ) {+ setBaseUrl(LOCAL_PROVIDER_URLS[newProvider]);+ setUseEnvBaseUrl(false);+ setUseEnvApiKey(false);+ setApiKey("");}};- const testEnvConfig = async () => {- setTesting(true);- try {- const res = await fetch(apiUrl("/api/v1/settings/env/test/"), {- method: "POST",+ // Test connection before saving+ const handleTestConnection = async () => {+ if (isSearchConfig) return;++ // Validate required fields+ if (!useEnvBaseUrl && !baseUrl) {+ setTestResult({+ success: false,+ message: "Base URL is required for testing",});- if (res.ok) {- const results = await res.json();- setTestResults(results);- }- } catch (err) {- console.error("Failed to test env config:", err);- } finally {- setTesting(false);+ return;}- };+ if (!isLocalProvider && !useEnvApiKey && !apiKey) {+ setTestResult({+ success: false,+ message: "API Key is required for cloud providers",+ });+ return;+ }+ if (!model) {+ setTestResult({ success: false, message: "Model name is required" });+ return;+ }+ if (configType === "embedding" && !dimensions) {+ setTestResult({+ success: false,+ message: "Dimensions is required for embedding models",+ });+ return;+ }++ setTesting(true);+ setTestResult(null);- // Test a single service (llm, embedding, tts)- const testSingleService = async (service: "llm" | "embedding" | "tts") => {- setTestingService((prev) => ({ ...prev, [service]: true }));try {- const res = await fetch(apiUrl(`/api/v1/settings/env/test/${service}`), {+ const res = await fetch(apiUrl(`/api/v1/config/${configType}/test`), {method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ provider,+ // Send use_env object if using env, otherwise send the actual value+ base_url: useEnvBaseUrl+ ? { use_env: getEnvVarForBaseUrl(configType) }+ : baseUrl,+ api_key: isLocalProvider+ ? ""+ : useEnvApiKey+ ? { use_env: getEnvVarForApiKey(configType) }+ : apiKey,+ model,+ // Include dimensions for embedding configs+ ...(configType === "embedding"+ ? { dimensions: Number(dimensions) }+ : {}),+ // Include voice for TTS configs+ ...(configType === "tts" && voice ? { voice } : {}),+ }),+ });+ const data = await res.json();+ // Ensure message is not empty+ setTestResult({+ success: data.success ?? false,+ message:+ data.message ||+ (data.success ? "Connection successful" : "Connection failed"),+ });+ } catch (e: any) {+ setTestResult({+ success: false,+ message: e?.message || "Connection test failed - network error",});- if (res.ok) {- const result = await res.json();- setServiceTestResults((prev) => ({ ...prev, [service]: result }));- // Also update testResults for status icons- setTestResults((prev) =>- prev- ? {- ...prev,- [service]: {- status:- result.status === "success" ? "configured" : result.status,- model: result.model,- error: result.error,- },- }- : null,- );- }- } catch (err) {- console.error(`Failed to test ${service}:`, err);- setServiceTestResults((prev) => ({- ...prev,- [service]: {- status: "error",- model: null,- error: "Connection failed",- response_time_ms: null,- message: null,- },- }));} finally {- setTestingService((prev) => ({ ...prev, [service]: false }));- }- };-- const getCategoryIcon = (iconName: string) => {- switch (iconName) {- case "brain":- return <Brain className="w-4 h-4" />;- case "database":- return <Database className="w-4 h-4" />;- case "volume":- return <Volume2 className="w-4 h-4" />;- case "search":- return <Search className="w-4 h-4" />;- case "settings":- return <SettingsIcon className="w-4 h-4" />;- default:- return <Key className="w-4 h-4" />;- }- };-- const getStatusIcon = (status: string) => {- switch (status) {- case "configured":- return <CheckCircle className="w-4 h-4 text-green-500" />;- case "not_configured":- return <XCircle className="w-4 h-4 text-amber-500" />;- case "error":- return <AlertCircle className="w-4 h-4 text-red-500" />;- default:- return <Info className="w-4 h-4 text-slate-400" />;+ setTesting(false);}};- const applyTheme = (theme: "light" | "dark") => {- // Persist theme to localStorage and document immediately- setTheme(theme);- };-- const handleSave = async () => {- if (!editedConfig || !editedUI) return;+ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();setSaving(true);- setSaveSuccess(false);- setError("");+ setError(null);try {- // 1. Save Environment Variables if they exist- if (Object.keys(editedEnvVars).length > 0) {- const envUpdates = Object.entries(editedEnvVars)- .filter(([key, value]) => {- const original = envConfig?.variables.find((v) => v.key === key);- // Don't send masked values back if they haven't changed- if (- original?.sensitive &&- value.includes("*") &&- value === original.value- ) {- return false;- }- return true;- })- .map(([key, value]) => ({ key, value }));-- if (envUpdates.length > 0) {- const envRes = await fetch(apiUrl("/api/v1/settings/env"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ variables: envUpdates }),- });- if (!envRes.ok) {- const errorData = await envRes.json();- throw new Error(- errorData.detail?.errors?.join(", ") ||- "Failed to save environment variables",- );- }- // Reload env config immediately to get updated state (including persistence)- await fetchEnvConfig();- }+ const payload: Record<string, any> = {+ name,+ provider,+ // For local providers, API key is optional; for cloud providers, use env or direct value+ api_key: isLocalProvider+ ? apiKey || "" // Empty string for local providers if not provided+ : useEnvApiKey+ ? { use_env: getEnvVarForApiKey(configType) }+ : apiKey,+ };++ if (!isSearchConfig) {+ payload.base_url = useEnvBaseUrl+ ? { use_env: getEnvVarForBaseUrl(configType) }+ : baseUrl;+ payload.model = model;}- // 2. Save Config- const configRes = await fetch(apiUrl("/api/v1/settings/config"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ config: editedConfig }),- });+ if (showDimensions) {+ payload.dimensions = dimensions;+ }++ if (showVoice) {+ payload.voice = voice;+ }- if (!configRes.ok) throw new Error("Failed to save configuration");+ // Use PUT for edit, POST for add+ const url = isEditMode+ ? apiUrl(`/api/v1/config/${configType}/${editConfig.id}`)+ : apiUrl(`/api/v1/config/${configType}`);+ const method = isEditMode ? "PUT" : "POST";- // 3. Save UI Settings- const uiRes = await fetch(apiUrl("/api/v1/settings/ui"), {- method: "PUT",+ const res = await fetch(url, {+ method,headers: { "Content-Type": "application/json" },- body: JSON.stringify(editedUI),+ body: JSON.stringify(payload),});- if (!uiRes.ok) throw new Error("Failed to save UI settings");-- const newConfig = await configRes.json();- const newUI = await uiRes.json();-- setData((prev) =>- prev ? { ...prev, config: newConfig, ui: newUI } : null,- );-- // Sync theme immediately when saving- if (editedUI.theme) {- setTheme(editedUI.theme);+ if (res.ok) {+ onSuccess();+ } else {+ const data = await res.json();+ setError(+ data.detail ||+ `Failed to ${isEditMode ? "update" : "add"} configuration`,+ );}-- await refreshSettings();-- setSaveSuccess(true);- setTimeout(() => setSaveSuccess(false), 2000);- } catch (err: any) {- setError(err.message || "Failed to save settings");+ } catch (e) {+ setError(`Failed to ${isEditMode ? "update" : "add"} configuration`);} finally {setSaving(false);}};- const handleConfigChange = (- section: string,- key: string,- value: any,- subSection?: string,- ) => {- setEditedConfig((prev) => {- if (!prev) return null;- const newConfig = { ...prev };-- if (subSection) {- if (!newConfig[section]) newConfig[section] = {};- if (!newConfig[section][subSection])- newConfig[section][subSection] = {};- newConfig[section][subSection][key] = value;- } else {- if (!newConfig[section]) newConfig[section] = {};- newConfig[section][key] = value;- }- return newConfig;- });-- // Sync search provider selection with SEARCH_PROVIDER env var- if (- section === "tools" &&- subSection === "web_search" &&- key === "provider"- ) {- setEditedEnvVars((prev) => ({ ...prev, SEARCH_PROVIDER: value }));- }- };-- const handleUIChange = (key: keyof UISettings, value: any) => {- setEditedUI((prev) => {- if (!prev) return null;- const newUI = { ...prev, [key]: value };- if (key === "theme") {- applyTheme(value);- // Debounced auto-save to backend- debouncedSaveTheme(value, newUI);- }- return newUI;- });- };-- if (loading) {- return (- <div className="h-screen flex items-center justify-center">- <Loader2 className="w-8 h-8 animate-spin text-blue-600 dark:text-blue-400" />- </div>- );- }-- if (!editedConfig || !editedUI)- return (- <div className="p-8 text-red-500 dark:text-red-400">- Error loading data- </div>- );-return (- <div className="h-screen overflow-y-auto animate-fade-in">- {/* Sticky Save Button at Top */}- <div className="sticky top-0 z-50 bg-white dark:bg-slate-900 border-b border-slate-200 dark:border-slate-700 shadow-md">- <div className="max-w-4xl mx-auto p-6 flex items-center justify-between">- <div>- <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">- System Settings- </h1>- </div>- <button- onClick={handleSave}- disabled={saving}- className={`py-2 px-6 rounded-lg font-medium flex items-center gap-2 transition-all ${- saving- ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"- : saveSuccess- ? "bg-green-500 text-white"- : "bg-blue-600 text-white hover:bg-blue-700"- }`}- >- {saving ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : saveSuccess ? (- <Check className="w-4 h-4" />- ) : (- <Save className="w-4 h-4" />- )}- {saving- ? t("Saving...")- : saveSuccess- ? t("Saved")- : t("Save All Changes")}- </button>+ <form+ onSubmit={handleSubmit}+ className="mb-6 p-4 rounded-xl border border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/20"+ >+ <h3 className="font-medium text-slate-900 dark:text-slate-100 mb-4">+ {isEditMode+ ? `Edit Configuration: ${editConfig.name}`+ : "Add New Configuration"}+ </h3>++ {error && (+ <div className="mb-4 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm border border-red-200 dark:border-red-800">+ {error}</div>- </div>-- <div className="max-w-4xl mx-auto p-8">- {/* Header */}- <div className="flex items-center justify-between mb-6">- <div>- <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 flex items-center gap-3">- <div className="p-2 bg-blue-50 dark:bg-blue-900/30 rounded-xl">- <SettingsIcon className="w-6 h-6 text-blue-600 dark:text-blue-400" />- </div>- {t("System Settings")}- </h1>- <p className="text-slate-500 dark:text-slate-400 mt-2 ml-1">- {t("Manage system configuration and preferences")}- </p>- </div>+ )}++ {testResult && (+ <div+ className={`mb-4 p-3 rounded-lg text-sm ${+ testResult.success+ ? "bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800"+ : "bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800"+ }`}+ >+ {testResult.message}</div>-- {/* Tab Navigation */}- <div className="flex items-center gap-1 p-1 bg-slate-100 dark:bg-slate-800 rounded-xl mb-4">- <button- onClick={() => setActiveTab("general")}- className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${- activeTab === "general"- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"- : "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"- }`}- >- <Sliders className="w-4 h-4" />- {t("General Settings")}- </button>- <button- onClick={() => setActiveTab("environment")}- className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${- activeTab === "environment"- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"- : "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"- }`}- >- <Key className="w-4 h-4" />- {t("Environment Variables")}- {testResults && (- <span- className={`ml-1 w-2 h-2 rounded-full ${- Object.values(testResults).every(- (r) => r.status === "configured",- )- ? "bg-green-500"- : Object.values(testResults).some(- (r) => r.status === "error",- )- ? "bg-red-500"- : "bg-amber-500"- }`}- />- )}- </button>- <button- onClick={() => setActiveTab("local_models")}- className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${- activeTab === "local_models"- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"- : "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"- }`}- >- <Server className="w-4 h-4" />- {t("LLM Providers")}- {llmModeInfo && (- <span- className={`ml-1 px-1.5 py-0.5 text-[9px] rounded font-medium ${- llmModeInfo.mode === "hybrid"- ? "bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400"- : llmModeInfo.mode === "api"- ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400"- : "bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"- }`}- >- {llmModeInfo.mode.toUpperCase()}- </span>- )}- </button>+ )}++ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ {/* Name */}+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Name+ </label>+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ required+ placeholder="My Configuration"+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ /></div>- {/* Configuration Status Panel - Quick Test */}- <div className="mb-6 bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-2.5 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-slate-50 to-blue-50/30 dark:from-slate-800/50 dark:to-blue-900/20 flex items-center justify-between">- <div className="flex items-center gap-2">- <Cpu className="w-4 h-4 text-blue-500 dark:text-blue-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("Configuration Status")}- </h2>- </div>- <span className="text-[10px] text-slate-500 dark:text-slate-400">- {t("Click each card to test")}- </span>+ {/* Provider */}+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Provider+ </label>+ <div className="relative">+ <select+ value={provider}+ onChange={(e) => handleProviderChange(e.target.value)}+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm appearance-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ >+ {PROVIDER_OPTIONS[configType].map((p) => (+ <option key={p} value={p}>+ {p}+ {LOCAL_PROVIDERS.includes(p) ? " (local)" : ""}+ </option>+ ))}+ </select>+ <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" /></div>- <div className="p-3">- <div className="grid grid-cols-1 md:grid-cols-3 gap-3">- {/* LLM Status */}- <div- className={`p-3 rounded-lg border transition-all ${- serviceTestResults.llm?.status === "success" ||- testResults?.llm?.status === "configured"- ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"- : serviceTestResults.llm?.status === "error" ||- testResults?.llm?.status === "error"- ? "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"- : "bg-slate-50 dark:bg-slate-700/50 border-slate-200 dark:border-slate-600"- }`}- >- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Brain className="w-4 h-4 text-purple-500" />- <span className="text-xs font-semibold text-slate-700 dark:text-slate-200">- LLM- </span>- </div>- <div className="flex items-center gap-1.5">- {serviceTestResults.llm?.response_time_ms && (- <span className="text-[9px] text-slate-400">- {serviceTestResults.llm.response_time_ms}ms- </span>- )}- {(serviceTestResults.llm || testResults?.llm) &&- getStatusIcon(- serviceTestResults.llm?.status === "success"- ? "configured"- : serviceTestResults.llm?.status ||- testResults?.llm?.status ||- "unknown",- )}- </div>- </div>- <p className="text-[10px] text-slate-600 dark:text-slate-400 font-mono truncate mb-1">- {serviceTestResults.llm?.model ||- testResults?.llm?.model ||- editedEnvVars["LLM_MODEL"] ||- t("Not configured")}- </p>- <p className="text-[10px] text-slate-500 dark:text-slate-500 truncate mb-2">- {editedEnvVars["LLM_HOST"]- ? editedEnvVars["LLM_HOST"].includes("localhost") ||- editedEnvVars["LLM_HOST"].includes("127.0.0.1")- ? `🏠 ${editedEnvVars["LLM_HOST"]}`- : `☁️ ${editedEnvVars["LLM_HOST"]}`- : t("No endpoint")}- </p>- {serviceTestResults.llm?.message && (- <p className="text-[9px] text-green-600 dark:text-green-400 truncate mb-2">- {serviceTestResults.llm.message}- </p>- )}- {serviceTestResults.llm?.error && (- <p className="text-[9px] text-red-600 dark:text-red-400 truncate mb-2">- {serviceTestResults.llm.error}- </p>- )}- <button- onClick={() => testSingleService("llm")}- disabled={testingService.llm}- className="w-full py-1.5 text-[10px] font-medium text-purple-600 dark:text-purple-400 bg-purple-50 dark:bg-purple-900/30 hover:bg-purple-100 dark:hover:bg-purple-900/50 rounded flex items-center justify-center gap-1.5 transition-colors border border-purple-200 dark:border-purple-800 disabled:opacity-50"- >- {testingService.llm ? (- <Loader2 className="w-3 h-3 animate-spin" />- ) : (- <RefreshCw className="w-3 h-3" />- )}- {testingService.llm ? t("Testing...") : t("Test LLM")}- </button>- </div>+ </div>- {/* Embedding Status */}- <div- className={`p-3 rounded-lg border transition-all ${- serviceTestResults.embedding?.status === "success" ||- testResults?.embedding?.status === "configured"- ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"- : serviceTestResults.embedding?.status === "error" ||- testResults?.embedding?.status === "error"- ? "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"- : "bg-slate-50 dark:bg-slate-700/50 border-slate-200 dark:border-slate-600"- }`}- >- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Database className="w-4 h-4 text-indigo-500" />- <span className="text-xs font-semibold text-slate-700 dark:text-slate-200">- Embedding- </span>- </div>- <div className="flex items-center gap-1.5">- {serviceTestResults.embedding?.response_time_ms && (- <span className="text-[9px] text-slate-400">- {serviceTestResults.embedding.response_time_ms}ms- </span>- )}- {(serviceTestResults.embedding || testResults?.embedding) &&- getStatusIcon(- serviceTestResults.embedding?.status === "success"- ? "configured"- : serviceTestResults.embedding?.status ||- testResults?.embedding?.status ||- "unknown",- )}- </div>- </div>- <p className="text-[10px] text-slate-600 dark:text-slate-400 font-mono truncate mb-1">- {serviceTestResults.embedding?.model ||- testResults?.embedding?.model ||- editedEnvVars["EMBEDDING_MODEL"] ||- t("Not configured")}- </p>- <p className="text-[10px] text-slate-500 dark:text-slate-500 truncate mb-2">- {editedEnvVars["EMBEDDING_HOST"]- ? editedEnvVars["EMBEDDING_HOST"].includes("localhost") ||- editedEnvVars["EMBEDDING_HOST"].includes("127.0.0.1")- ? `🏠 ${editedEnvVars["EMBEDDING_HOST"]}`- : `☁️ ${editedEnvVars["EMBEDDING_HOST"]}`- : t("No endpoint")}- </p>- {serviceTestResults.embedding?.message && (- <p className="text-[9px] text-green-600 dark:text-green-400 truncate mb-2">- {serviceTestResults.embedding.message}- </p>- )}- {serviceTestResults.embedding?.error && (- <p className="text-[9px] text-red-600 dark:text-red-400 truncate mb-2">- {serviceTestResults.embedding.error}- </p>- )}- <button- onClick={() => testSingleService("embedding")}- disabled={testingService.embedding}- className="w-full py-1.5 text-[10px] font-medium text-indigo-600 dark:text-indigo-400 bg-indigo-50 dark:bg-indigo-900/30 hover:bg-indigo-100 dark:hover:bg-indigo-900/50 rounded flex items-center justify-center gap-1.5 transition-colors border border-indigo-200 dark:border-indigo-800 disabled:opacity-50"- >- {testingService.embedding ? (- <Loader2 className="w-3 h-3 animate-spin" />- ) : (- <RefreshCw className="w-3 h-3" />- )}- {testingService.embedding- ? t("Testing...")- : t("Test Embedding")}- </button>+ {/* Base URL (not for search) */}+ {!isSearchConfig && (+ <div className="md:col-span-2">+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Base URL+ {useEnvBaseUrl && (+ <span className="ml-2 text-xs font-normal text-blue-500">+ (using ${getEnvVarForBaseUrl(configType)})+ </span>+ )}+ </label>+ <div className="flex items-center gap-3">+ <div className="flex-1">+ <input+ type="text"+ value={useEnvBaseUrl ? "" : baseUrl}+ onChange={(e) => setBaseUrl(e.target.value)}+ disabled={useEnvBaseUrl}+ placeholder={+ useEnvBaseUrl+ ? `Using ${getEnvVarForBaseUrl(configType)} from .env`+ : "https://api.openai.com/v1"+ }+ className={`w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${+ useEnvBaseUrl+ ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic"+ : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600"+ }`}+ /></div>+ <label className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">+ <input+ type="checkbox"+ checked={useEnvBaseUrl}+ onChange={(e) => {+ setUseEnvBaseUrl(e.target.checked);+ if (e.target.checked) setBaseUrl("");+ }}+ className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"+ />+ Use .env+ </label>+ </div>+ </div>+ )}- {/* TTS Status */}- <div- className={`p-3 rounded-lg border transition-all ${- serviceTestResults.tts?.status === "success" ||- testResults?.tts?.status === "configured"- ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"- : serviceTestResults.tts?.status === "error" ||- testResults?.tts?.status === "error"- ? "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"- : "bg-slate-50 dark:bg-slate-700/50 border-slate-200 dark:border-slate-600"+ {/* API Key - Optional for local providers */}+ <div className="md:col-span-2">+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ API Key+ {isLocalProvider ? (+ <span className="ml-2 text-xs font-normal text-slate-400">+ (optional for local providers)+ </span>+ ) : useEnvApiKey ? (+ <span className="ml-2 text-xs font-normal text-blue-500">+ (using ${getEnvVarForApiKey(configType)})+ </span>+ ) : null}+ </label>+ <div className="flex items-center gap-3">+ <div className="flex-1 relative">+ <input+ type={showApiKey ? "text" : "password"}+ value={useEnvApiKey ? "" : apiKey}+ onChange={(e) => setApiKey(e.target.value)}+ disabled={useEnvApiKey}+ placeholder={+ isLocalProvider+ ? "Not required"+ : useEnvApiKey+ ? `Using ${getEnvVarForApiKey(configType)} from .env`+ : "sk-..."+ }+ className={`w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent ${+ useEnvApiKey+ ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-600 dark:text-blue-400 italic"+ : "bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600"}`}- >- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Volume2 className="w-4 h-4 text-rose-500" />- <span className="text-xs font-semibold text-slate-700 dark:text-slate-200">- TTS- </span>- </div>- <div className="flex items-center gap-1.5">- {serviceTestResults.tts?.response_time_ms && (- <span className="text-[9px] text-slate-400">- {serviceTestResults.tts.response_time_ms}ms- </span>- )}- {(serviceTestResults.tts || testResults?.tts) &&- getStatusIcon(- serviceTestResults.tts?.status === "success"- ? "configured"- : serviceTestResults.tts?.status ||- testResults?.tts?.status ||- "unknown",- )}- </div>- </div>- <p className="text-[10px] text-slate-600 dark:text-slate-400 font-mono truncate mb-1">- {serviceTestResults.tts?.model ||- testResults?.tts?.model ||- editedEnvVars["TTS_MODEL"] ||- t("Not configured")}- </p>- <p className="text-[10px] text-slate-500 dark:text-slate-500 truncate mb-2">- {editedEnvVars["TTS_URL"] || t("No endpoint")}- </p>- {serviceTestResults.tts?.message && (- <p className="text-[9px] text-green-600 dark:text-green-400 truncate mb-2">- {serviceTestResults.tts.message}- </p>- )}- {serviceTestResults.tts?.error && (- <p className="text-[9px] text-red-600 dark:text-red-400 truncate mb-2">- {serviceTestResults.tts.error}- </p>- )}+ />+ {!useEnvApiKey && (<button- onClick={() => testSingleService("tts")}- disabled={testingService.tts}- className="w-full py-1.5 text-[10px] font-medium text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-900/30 hover:bg-rose-100 dark:hover:bg-rose-900/50 rounded flex items-center justify-center gap-1.5 transition-colors border border-rose-200 dark:border-rose-800 disabled:opacity-50"+ type="button"+ onClick={() => setShowApiKey(!showApiKey)}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">- {testingService.tts ? (- <Loader2 className="w-3 h-3 animate-spin" />+ {showApiKey ? (+ <EyeOff className="w-4 h-4" />) : (- <RefreshCw className="w-3 h-3" />+ <Eye className="w-4 h-4" />)}- {testingService.tts ? t("Testing...") : t("Test TTS")}</button>- </div>+ )}</div>+ {!isLocalProvider && (+ <label className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400 whitespace-nowrap">+ <input+ type="checkbox"+ checked={useEnvApiKey}+ onChange={(e) => {+ setUseEnvApiKey(e.target.checked);+ if (e.target.checked) setApiKey("");+ }}+ className="rounded border-slate-300 text-blue-600 focus:ring-blue-500"+ />+ Use .env+ </label>+ )}</div></div>- {error && (- <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl flex items-center gap-3 text-red-700 dark:text-red-400 font-medium">- <AlertCircle className="w-5 h-5" />- <span>{error}</span>+ {/* Model (not for search) */}+ {!isSearchConfig && (+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Model+ </label>+ <input+ type="text"+ value={model}+ onChange={(e) => setModel(e.target.value)}+ required+ placeholder="gpt-4o"+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ /></div>)}- {/* General Settings Tab */}- {activeTab === "general" && (- <div className="space-y-4">- {/* Row 1: Interface + System Language + Active Model */}- <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">- {/* Interface Settings */}- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <Globe className="w-4 h-4 text-blue-500 dark:text-blue-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("Interface Preferences")}- </h2>- </div>- <div className="p-4 space-y-4">- {/* Theme Mode */}- <div>- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">- {t("Theme")}- </label>- <div className="flex bg-slate-100 dark:bg-slate-700 p-0.5 rounded-lg">- {["light", "dark"].map((themeOption) => (- <button- key={themeOption}- onClick={() =>- handleUIChange("theme", themeOption as any)- }- className={`flex-1 py-1.5 px-3 rounded-md text-xs font-medium flex items-center justify-center gap-1.5 transition-all ${- editedUI.theme === themeOption- ? "bg-white dark:bg-slate-600 text-blue-600 dark:text-blue-400 shadow-sm"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- {themeOption === "light" ? (- <Sun className="w-3.5 h-3.5" />- ) : (- <Moon className="w-3.5 h-3.5" />- )}- <span>- {themeOption === "light"- ? t("Light Mode")- : t("Dark Mode")}- </span>- </button>- ))}- </div>- </div>- {/* Interface Language */}- <div>- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">- {t("Language")}- </label>- <select- value={editedUI.language}- onChange={(e) =>- handleUIChange("language", e.target.value)- }- className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"- >- <option value="en">{t("English")}</option>- <option value="zh">{t("Chinese")}</option>- </select>- </div>- </div>- </section>-- {/* System Language */}- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <Server className="w-4 h-4 text-purple-500 dark:text-purple-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("System Configuration")}- </h2>- </div>- <div className="p-4">- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">- {t("System Language")}- </label>- <p className="text-[10px] text-slate-400 dark:text-slate-500 mb-2">- {t("Default language for system operations")}- </p>- <select- value={editedConfig.system?.language || "en"}- onChange={(e) =>- handleConfigChange("system", "language", e.target.value)- }- className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"- >- <option value="en">English</option>- <option value="zh">Chinese</option>- </select>- </div>- </section>-- {/* Active Models Status */}- {data?.env && (- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center justify-between">- <div className="flex items-center gap-2">- <Cpu className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("Active Models")}- </h2>- </div>- <span className="text-[10px] bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 px-1.5 py-0.5 rounded font-medium">- {t("Status")}- </span>- </div>- <div className="p-4">- <div className="flex items-center gap-3 p-3 bg-emerald-50 dark:bg-emerald-900/20 rounded-lg border border-emerald-100 dark:border-emerald-800">- <div className="p-2 bg-white dark:bg-slate-700 rounded-lg shadow-sm">- <Server className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />- </div>- <div className="min-w-0 flex-1">- <p className="text-xs text-emerald-700 dark:text-emerald-300 font-medium">- {t("Active LLM Model")}- </p>- <p className="text-sm font-bold text-emerald-900 dark:text-emerald-200 font-mono truncate">- {data.env.model || t("Not configured")}- </p>- </div>- </div>- </div>- </section>- )}- </div>-- {/* Row 2: RAG Provider (Currently locked to RAG-Anything) */}- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <Database className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("RAG Provider")}- </h2>- </div>- <div className="p-4">- <div className="flex flex-col lg:flex-row lg:items-start gap-4">- <div className="flex-1">- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">- {t("Active RAG System")}- </label>- <p className="text-[10px] text-slate-400 dark:text-slate-500 mb-2">- {t(- "RAG-Anything provides end-to-end academic document processing with MinerU and LightRAG",- )}- </p>- {loadingRagProviders ? (- <div className="flex items-center gap-2 text-sm text-slate-500">- <Loader2 className="w-4 h-4 animate-spin" />- <span>Loading providers...</span>- </div>- ) : (- <div className="w-full p-2 bg-slate-100 dark:bg-slate-700/50 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-700 dark:text-slate-300 flex items-center justify-between">- <span>- RAG-Anything - End-to-end academic document processing- (MinerU + LightRAG)- </span>- <span className="text-[10px] px-2 py-0.5 bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 rounded-full">- Default- </span>- </div>- )}- </div>- <div className="lg:w-1/2 text-xs text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-700/50 p-3 rounded-lg border border-slate-100 dark:border-slate-600">- <p>- RAG-Anything combines MinerU for multimodal PDF parsing- (images, tables, equations) with LightRAG for knowledge- graph construction.- </p>- <p className="mt-1.5">- <span className="font-medium text-slate-600 dark:text-slate-300">- Supported modes:- </span>{" "}- hybrid, local, global, naive- </p>- </div>- </div>- </div>- </section>-- {/* Row 3: Research Tools (Web Search + Knowledge Base) + TTS */}- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- {/* Research Tools - Web Search */}- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <Globe className="w-4 h-4 text-blue-500 dark:text-blue-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("Web Search")}- </h2>- </div>- <div className="p-4 space-y-4">- {/* Enable/Disable Toggle */}- <div className="flex items-center justify-between">- <span className="text-xs font-medium text-slate-700 dark:text-slate-300">- {t("Enable Web Search")}- </span>- <div className="relative inline-flex items-center cursor-pointer">- <input- type="checkbox"- checked={- editedConfig.tools?.web_search?.enabled ?? true- }- onChange={(e) =>- handleConfigChange(- "tools",- "enabled",- e.target.checked,- "web_search",- )- }- className="sr-only peer"- />- <div className="w-9 h-5 bg-slate-200 dark:bg-slate-600 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 dark:after:border-slate-500 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>- </div>- </div>-- {/* Provider Selection */}- <div>- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">- {t("Search Provider")}- </label>- <select- value={- editedEnvVars["SEARCH_PROVIDER"] ||- editedConfig.tools?.web_search?.provider ||- "perplexity"- }- onChange={(e) =>- handleConfigChange(- "tools",- "provider",- e.target.value,- "web_search",- )- }- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"- >- {(webSearchConfig?.providers || []).map((p) => (- <option key={p.id} value={p.id}>- {p.name}- </option>- ))}- </select>- <p className="text-[10px] text-slate-500 dark:text-slate-400 mt-1">- Also updates SEARCH_PROVIDER env variable- </p>- </div>-- {/* Max Results */}- <div>- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">- {t("Max Results")}- </label>- <input- type="number"- min="1"- max="20"- value={editedConfig.tools?.web_search?.max_results || 5}- onChange={(e) =>- handleConfigChange(- "tools",- "max_results",- e.target.value === "" ? 5 : parseInt(e.target.value),- "web_search",- )- }- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"- />- </div>-- {/* Consolidation Settings */}- <div className="p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600 space-y-3">- <div>- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">- {t("Answer Consolidation")}- </label>- <select- value={- editedConfig.tools?.web_search?.consolidation ||- "template"- }- onChange={(e) =>- handleConfigChange(- "tools",- "consolidation",- e.target.value,- "web_search",- )- }- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"- >- {(- webSearchConfig?.consolidation_types || [- "none",- "template",- "llm",- ]- ).map((type) => (- <option key={type} value={type}>- {type.charAt(0).toUpperCase() + type.slice(1)}- </option>- ))}- </select>- <p className="text-[10px] text-slate-500 dark:text-slate-400 mt-1">- For SERP providers that return raw results.- </p>- </div>-- {(editedConfig.tools?.web_search?.consolidation ===- "template" ||- editedConfig.tools?.web_search?.consolidation ===- "llm") && (- <div className="text-[10px] text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 p-2 rounded space-y-1">- <div>- Consolidation only works with:{" "}- {webSearchConfig?.template_providers?.join(", ") ||- "serper, jina, serper_scholar"}- </div>- {editedConfig.tools?.web_search?.consolidation ===- "llm" && (- <div className="text-amber-700 dark:text-amber-300 font-medium">- ⚠️ LLM consolidation is an experimental feature.- </div>- )}- </div>- )}- </div>- </div>- </section>-- {/* Knowledge Base */}- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <Database className="w-4 h-4 text-purple-500 dark:text-purple-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("Knowledge Base")}- </h2>- </div>- <div className="p-4 space-y-3">- <div>- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">- {t("Default KB")}- </label>- <input- type="text"- value={editedConfig.tools?.rag_tool?.default_kb || ""}- onChange={(e) =>- handleConfigChange(- "tools",- "default_kb",- e.target.value,- "rag_tool",- )- }- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"- />- </div>- <div>- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">- {t("Base Directory")}- </label>- <input- type="text"- value={editedConfig.tools?.rag_tool?.kb_base_dir || ""}- onChange={(e) =>- handleConfigChange(- "tools",- "kb_base_dir",- e.target.value,- "rag_tool",- )- }- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs font-mono text-slate-600 dark:text-slate-300"- />- </div>- </div>- </section>- </div>-- {/* TTS Settings */}- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <Volume2 className="w-4 h-4 text-rose-500 dark:text-rose-400" />- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {t("Text-to-Speech")}- </h2>- </div>- <div className="p-4 grid grid-cols-2 gap-4">- <div>- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">- {t("Default Voice")}- </label>- <input- type="text"- value={editedConfig.tts?.default_voice || "Cherry"}- onChange={(e) =>- handleConfigChange("tts", "default_voice", e.target.value)- }- className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"- />- </div>- <div>- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">- {t("Default Language")}- </label>- <input- type="text"- value={editedConfig.tts?.default_language || "English"}- onChange={(e) =>- handleConfigChange(- "tts",- "default_language",- e.target.value,- )- }- className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"- />- </div>- </div>- </section>+ {/* Dimensions (embedding only) */}+ {showDimensions && (+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Dimensions+ </label>+ <input+ type="number"+ value={dimensions}+ onChange={(e) => setDimensions(parseInt(e.target.value))}+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ /></div>)}- {/* Environment Variables Tab */}- {activeTab === "environment" && envConfig && (- <div className="space-y-4">- {/* Environment Variables by Category - 2-column layout */}- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- {envConfig.categories.map((category) => {- const categoryVars = envConfig.variables.filter(- (v) => v.category === category.id,- );- if (categoryVars.length === 0) return null;-- return (- <section- key={category.id}- className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden"- >- <div className="px-4 py-2.5 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">- <div className="text-blue-500 dark:text-blue-400">- {getCategoryIcon(category.icon)}- </div>- <div>- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">- {category.name}- </h2>- <p className="text-[10px] text-slate-500 dark:text-slate-400">- {category.description}- </p>- </div>- </div>-- <div className="p-4 space-y-3">- {categoryVars.map((envVar) => (- <div key={envVar.key} className="space-y-1">- <div className="flex items-center justify-between">- <label className="text-xs font-medium text-slate-700 dark:text-slate-300 flex items-center gap-1.5">- <code className="bg-slate-100 dark:bg-slate-700 px-1.5 py-0.5 rounded text-slate-800 dark:text-slate-200 text-[10px]">- {envVar.key}- </code>- {envVar.required && (- <span className="text-red-500 text-[9px] font-semibold">- REQUIRED- </span>- )}- {envVar.is_set && (- <CheckCircle className="w-3 h-3 text-green-500" />- )}- </label>- {envVar.sensitive && (- <button- onClick={() =>- toggleSensitiveVisibility(envVar.key)- }- className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 p-0.5"- >- {showSensitive[envVar.key] ? (- <EyeOff className="w-3.5 h-3.5" />- ) : (- <Eye className="w-3.5 h-3.5" />- )}- </button>- )}- </div>- <p className="text-[10px] text-slate-500 dark:text-slate-400 line-clamp-1">- {envVar.description}- </p>- <input- type={- envVar.sensitive && !showSensitive[envVar.key]- ? "password"- : "text"- }- value={editedEnvVars[envVar.key] || ""}- onChange={(e) =>- handleEnvVarChange(envVar.key, e.target.value)- }- placeholder={- envVar.default || `Enter ${envVar.key}`- }- className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-xs text-slate-900 dark:text-slate-100 font-mono placeholder:text-slate-300 dark:placeholder:text-slate-500 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"- />- </div>- ))}- </div>- </section>- );- })}- </div>-- {/* Save Environment Variables */}- <div className="pt-2 pb-4">- {envError && (- <div className="mb-3 p-2.5 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center gap-2 text-red-700 dark:text-red-400 text-xs">- <AlertCircle className="w-4 h-4" />- <span>{envError}</span>- </div>- )}- <button- onClick={handleEnvSave}- disabled={envSaving}- className={`w-full py-3 rounded-xl font-bold text-base flex items-center justify-center gap-2 transition-all ${- envSaving- ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"- : envSaveSuccess- ? "bg-green-500 text-white shadow-lg shadow-green-500/30"- : "bg-gradient-to-r from-amber-500 to-orange-500 text-white hover:shadow-lg hover:shadow-orange-500/30 hover:-translate-y-0.5"- }`}+ {/* Voice (TTS only) */}+ {showVoice && (+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ Voice+ </label>+ <div className="relative">+ <select+ value={voice}+ onChange={(e) => setVoice(e.target.value)}+ className="w-full px-3 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-lg text-sm appearance-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">- {envSaving ? (- <Loader2 className="w-5 h-5 animate-spin" />- ) : envSaveSuccess ? (- <Check className="w-5 h-5" />- ) : (- <Key className="w-5 h-5" />- )}- {envSaveSuccess- ? t("Environment Updated!")- : t("Apply Environment Changes")}- </button>+ {VOICE_OPTIONS.map((v) => (+ <option key={v} value={v}>+ {v}+ </option>+ ))}+ </select>+ <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" /></div></div>)}+ </div>- {/* LLM Providers Tab */}- {activeTab === "local_models" && (- <div className="space-y-4">- {/* LLM Mode Status Banner */}- {llmModeInfo && (- <div- className={`p-4 rounded-xl border ${- llmModeInfo.mode === "hybrid"- ? "bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800"- : llmModeInfo.mode === "api"- ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"- : "bg-emerald-50 dark:bg-emerald-900/20 border-emerald-200 dark:border-emerald-800"- }`}- >- <div className="flex items-center justify-between">- <div className="flex items-center gap-3">- <div- className={`p-2 rounded-lg ${- llmModeInfo.mode === "hybrid"- ? "bg-purple-100 dark:bg-purple-800/30"- : llmModeInfo.mode === "api"- ? "bg-blue-100 dark:bg-blue-800/30"- : "bg-emerald-100 dark:bg-emerald-800/30"- }`}- >- <Cpu- className={`w-5 h-5 ${- llmModeInfo.mode === "hybrid"- ? "text-purple-600 dark:text-purple-400"- : llmModeInfo.mode === "api"- ? "text-blue-600 dark:text-blue-400"- : "text-emerald-600 dark:text-emerald-400"- }`}- />- </div>- <div>- <div className="flex items-center gap-2">- <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-100">- {t("LLM Mode")}:{" "}- <span className="uppercase">{llmModeInfo.mode}</span>- </h3>- <span- className={`px-2 py-0.5 text-[10px] rounded-full font-medium ${- llmModeInfo.effective_source === "provider"- ? "bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300"- : "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400"- }`}- >- {llmModeInfo.effective_source === "provider"- ? t("Using Provider")- : t("Using ENV")}- </span>- </div>- <p className="text-xs text-slate-600 dark:text-slate-400 mt-0.5">- {llmModeInfo.mode === "hybrid"- ? t(- "Both API and Local providers available. Active provider takes priority.",- )- : llmModeInfo.mode === "api"- ? t("Only API (cloud) providers are used.")- : t("Only Local (self-hosted) providers are used.")}- </p>- </div>- </div>- {llmModeInfo.active_provider && (- <div className="text-right">- <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase tracking-wider">- {t("Active")}- </p>- <p className="text-sm font-semibold text-slate-900 dark:text-slate-100">- {llmModeInfo.active_provider.name}- </p>- <p className="text-xs text-slate-500 dark:text-slate-400 font-mono">- {llmModeInfo.active_provider.model}- </p>- </div>- )}- </div>- </div>- )}-- {/* Header & Add Button */}- <div className="flex justify-between items-center bg-white dark:bg-slate-800 px-4 py-3 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">- <div>- <h2 className="text-sm font-semibold text-slate-900 dark:text-slate-100">- {t("LLM Providers")}- </h2>- <p className="text-xs text-slate-500 dark:text-slate-400">- {t(- "Manage both API and Local LLM providers. Set LLM_MODE in Environment Variables to control which type is used.",- )}- </p>- </div>- <button- onClick={() => {- const defaultPreset = PROVIDER_PRESETS[0];- setEditingProvider({- name: "",- binding: defaultPreset.binding,- base_url: defaultPreset.base_url || "",- api_key: "",- model: defaultPreset.default_model,- is_active: false,- provider_type: "local",- requires_key: defaultPreset.requires_key,- });- setOriginalProviderName(null);- setSelectedPresetId(defaultPreset.id);- setFetchedModels([]);- setShowProviderForm(true);- setTestProviderResult(null);- }}- className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg flex items-center gap-1.5 text-xs font-medium transition-colors"- >- <Server className="w-3.5 h-3.5" />- {t("Add Provider")}- </button>- </div>-- {/* Provider Type Filter */}- <div className="flex items-center gap-2 bg-white dark:bg-slate-800 px-4 py-2 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">- <span className="text-xs text-slate-500 dark:text-slate-400">- {t("Filter")}:- </span>- <div className="flex bg-slate-100 dark:bg-slate-700 p-0.5 rounded-lg">- {(["all", "api", "local"] as const).map((filter) => (- <button- key={filter}- onClick={() => setProviderTypeFilter(filter)}- className={`px-3 py-1 rounded-md text-xs font-medium transition-all ${- providerTypeFilter === filter- ? "bg-white dark:bg-slate-600 text-blue-600 dark:text-blue-400 shadow-sm"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- {filter === "all"- ? t("All")- : filter === "api"- ? t("API (Cloud)")- : t("Local")}- </button>- ))}- </div>- </div>+ {/* Actions */}+ <div className="flex justify-between items-center mt-4">+ {/* Test Connection Button (left side) */}+ <div>+ {!isSearchConfig && (+ <button+ type="button"+ onClick={handleTestConnection}+ disabled={testing || (!baseUrl && !useEnvBaseUrl)}+ className="flex items-center gap-2 px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 rounded-lg transition-colors"+ >+ {testing ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : (+ <TestTube className="w-4 h-4" />+ )}+ Test Connection+ </button>+ )}+ </div>- {/* Provider List */}- {loadingProviders ? (- <div className="flex justify-center p-6">- <Loader2 className="w-6 h-6 animate-spin text-emerald-500" />- </div>- ) : providers.filter(- (p) =>- providerTypeFilter === "all" ||- p.provider_type === providerTypeFilter,- ).length === 0 ? (- <div className="text-center p-8 bg-slate-50 dark:bg-slate-800/50 rounded-xl border border-dashed border-slate-300 dark:border-slate-700">- <Server className="w-10 h-10 text-slate-300 dark:text-slate-600 mx-auto mb-2" />- <p className="text-sm text-slate-500 dark:text-slate-400">- {providerTypeFilter === "all"- ? t("No providers configured yet.")- : providerTypeFilter === "api"- ? t("No API providers configured.")- : t("No local providers configured.")}- </p>- <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">- {t("Add providers to manage your LLM configurations.")}- </p>- </div>+ {/* Cancel and Save Buttons (right side) */}+ <div className="flex gap-3">+ <button+ type="button"+ onClick={onCancel}+ className="px-4 py-2 text-sm text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"+ >+ Cancel+ </button>+ <button+ type="submit"+ disabled={saving}+ className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg text-sm font-medium transition-colors"+ >+ {saving ? (+ <Loader2 className="w-4 h-4 animate-spin" />+ ) : isEditMode ? (+ <Check className="w-4 h-4" />) : (- <div className="grid gap-3">- {providers- .filter(- (p) =>- providerTypeFilter === "all" ||- p.provider_type === providerTypeFilter,- )- .map((provider) => (- <div- key={provider.name}- className={`bg-white dark:bg-slate-800 px-4 py-3 rounded-xl shadow-sm border transition-all ${provider.is_active ? "border-blue-500 ring-1 ring-blue-500/20" : "border-slate-200 dark:border-slate-700"}`}- >- <div className="flex justify-between items-center">- <div className="flex items-center gap-3 min-w-0 flex-1">- <div- className={`p-2 rounded-lg flex-shrink-0 ${provider.is_active ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400" : "bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400"}`}- >- <Server className="w-4 h-4" />- </div>- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2 flex-wrap">- <h3 className="font-semibold text-slate-900 dark:text-slate-100 text-sm">- {provider.name}- </h3>- {provider.is_active && (- <span className="px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-[10px] rounded font-medium">- Active- </span>- )}- <span- className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${- provider.provider_type === "api"- ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400"- : "bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"- }`}- >- {provider.provider_type === "api"- ? "☁️ API"- : "🏠 Local"}- </span>- <span className="text-[10px] bg-slate-100 dark:bg-slate-700 px-1.5 py-0.5 rounded border border-slate-200 dark:border-slate-600 uppercase tracking-wider font-semibold text-slate-500">- {provider.binding}- </span>- </div>- <div className="flex items-center gap-2 mt-0.5 text-xs text-slate-500 dark:text-slate-400">- <span className="font-medium text-slate-600 dark:text-slate-300">- {provider.model}- </span>- <span className="text-slate-300 dark:text-slate-600">- •- </span>- <span className="font-mono truncate text-[10px]">- {provider.base_url}- </span>- </div>- </div>- </div>- <div className="flex items-center gap-1 flex-shrink-0 ml-2">- {!provider.is_active && (- <button- onClick={() =>- handleActivateProvider(provider.name)- }- className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-md transition-colors"- title="Set as Active"- >- <CheckCircle className="w-4 h-4" />- </button>- )}- <button- onClick={() => handleTestProvider(provider)}- className="p-1.5 text-slate-400 hover:text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-md transition-colors"- title="Test Connection"- >- <RefreshCw className="w-4 h-4" />- </button>- <button- onClick={() => {- setEditingProvider({ ...provider });- setOriginalProviderName(provider.name);- const preset =- PROVIDER_PRESETS.find(- (p) =>- p.base_url &&- provider.base_url.includes(p.base_url),- ) ||- PROVIDER_PRESETS.find((p) => p.id === "custom");- if (preset) setSelectedPresetId(preset.id);- setFetchedModels([]);- setShowProviderForm(true);- setTestProviderResult(null);- }}- className="p-1.5 text-slate-400 hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded-md transition-colors"- title="Edit"- >- <Sliders className="w-4 h-4" />- </button>- <button- onClick={() => handleDeleteProvider(provider.name)}- className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors"- title="Delete"- >- <XCircle className="w-4 h-4" />- </button>- </div>- </div>- </div>- ))}- </div>+ <Plus className="w-4 h-4" />)}-- {/* Edit/Add Form Modal */}- {showProviderForm && editingProvider && (- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">- <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl w-full max-w-md overflow-hidden flex flex-col max-h-[85vh]">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-emerald-50/50 dark:bg-emerald-900/20 flex justify-between items-center">- <h3 className="font-semibold text-sm text-slate-900 dark:text-slate-100 flex items-center gap-2">- <Server className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />- {editingProvider.name- ? t("Edit Provider")- : t("Add Provider")}- </h3>- <button- onClick={() => setShowProviderForm(false)}- className="text-slate-400 hover:text-slate-600 p-1"- >- <XCircle className="w-5 h-5" />- </button>- </div>- <div className="p-4 overflow-y-auto space-y-3">- {/* Provider Type Selection */}- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">- {t("Provider Type")}- </label>- <div className="flex bg-slate-100 dark:bg-slate-700 p-0.5 rounded-lg">- <button- type="button"- onClick={() =>- setEditingProvider((prev) =>- prev- ? {- ...prev,- provider_type: "local",- requires_key: false,- }- : null,- )- }- className={`flex-1 py-1.5 px-3 rounded-md text-xs font-medium flex items-center justify-center gap-1.5 transition-all ${- editingProvider.provider_type === "local"- ? "bg-white dark:bg-slate-600 text-emerald-600 dark:text-emerald-400 shadow-sm"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- 🏠 {t("Local")}- </button>- <button- type="button"- onClick={() =>- setEditingProvider((prev) =>- prev- ? {- ...prev,- provider_type: "api",- requires_key: true,- }- : null,- )- }- className={`flex-1 py-1.5 px-3 rounded-md text-xs font-medium flex items-center justify-center gap-1.5 transition-all ${- editingProvider.provider_type === "api"- ? "bg-white dark:bg-slate-600 text-blue-600 dark:text-blue-400 shadow-sm"- : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"- }`}- >- ☁️ {t("API (Cloud)")}- </button>- </div>- <p className="mt-1 text-[10px] text-slate-500 dark:text-slate-400">- {editingProvider.provider_type === "local"- ? t(- "Local servers (Ollama, LM Studio, vLLM) running on your machine.",- )- : t(- "Cloud API providers (OpenAI, Anthropic, DeepSeek, etc.).",- )}- </p>- </div>-- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">- {t("Server Preset")}- </label>- <select- value={selectedPresetId}- onChange={(e) => {- const newId = e.target.value;- setSelectedPresetId(newId);- const preset = PROVIDER_PRESETS.find(- (p) => p.id === newId,- );- if (preset && editingProvider) {- setEditingProvider({- ...editingProvider,- binding: preset.binding,- base_url:- preset.base_url || editingProvider.base_url,- model:- preset.default_model || editingProvider.model,- requires_key: preset.requires_key,- });- setCustomModelInput(preset.models.length === 0);- setFetchedModels([]);- }- }}- className="w-full p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100 font-medium"- >- {PROVIDER_PRESETS.map((preset) => (- <option key={preset.id} value={preset.id}>- {preset.name}- </option>- ))}- </select>- {PROVIDER_PRESETS.find((p) => p.id === selectedPresetId)- ?.help_text && (- <p className="mt-1 text-[10px] text-slate-500 dark:text-slate-400">- {- PROVIDER_PRESETS.find(- (p) => p.id === selectedPresetId,- )?.help_text- }- </p>- )}- </div>- <div className="grid grid-cols-2 gap-3">- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">- Name- </label>- <input- type="text"- value={editingProvider.name}- onChange={(e) =>- setEditingProvider((prev) =>- prev ? { ...prev, name: e.target.value } : null,- )- }- disabled={- !!providers.find(- (p) =>- p.name === editingProvider.name &&- p.name !== "",- )- }- placeholder="My Provider"- className="w-full p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm"- />- </div>- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">- Binding- </label>- <input- type="text"- value={editingProvider.binding}- disabled- className="w-full p-2 bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg text-sm text-slate-500"- />- </div>- </div>-- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">- Base URL- </label>- <input- type="text"- value={editingProvider.base_url}- onChange={(e) =>- setEditingProvider((prev) =>- prev ? { ...prev, base_url: e.target.value } : null,- )- }- placeholder={- selectedPresetId === "lmstudio"- ? "http://127.0.0.1:1234"- : selectedPresetId === "ollama"- ? "http://localhost:11434/v1"- : "http://localhost:8080/v1"- }- className={`w-full p-2 bg-slate-50 dark:bg-slate-700 border rounded-lg font-mono text-xs ${- editingProvider.base_url.includes(- "/chat/completions",- ) || editingProvider.base_url.includes("/models/")- ? "border-red-400 dark:border-red-500 ring-1 ring-red-400/30"- : "border-slate-200 dark:border-slate-600"- }`}- />- {/* Base URL validation warning */}- {(editingProvider.base_url.includes(- "/chat/completions",- ) ||- editingProvider.base_url.includes("/models/")) && (- <div className="mt-1.5 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">- <p className="text-[11px] text-red-600 dark:text-red-400 font-medium flex items-center gap-1">- <AlertCircle className="w-3 h-3" />- {t("Invalid URL format detected")}- </p>- <p className="text-[10px] text-red-500 dark:text-red-400/80 mt-0.5">- {t(- "Base URL should NOT include '/chat/completions' or '/models/'. The system will append these automatically.",- )}- </p>- <p className="text-[10px] text-red-500 dark:text-red-400/80 mt-0.5">- {t("Example")}:{" "}- <code className="bg-red-100 dark:bg-red-800/30 px-1 rounded">- http://127.0.0.1:1234- </code>{" "}- {t("or")}{" "}- <code className="bg-red-100 dark:bg-red-800/30 px-1 rounded">- http://127.0.0.1:1234/v1- </code>- </p>- </div>- )}- {/* Normal help text */}- {!editingProvider.base_url.includes(- "/chat/completions",- ) &&- !editingProvider.base_url.includes("/models/") && (- <p className="mt-1 text-[10px] text-slate-500 dark:text-slate-400">- {t(- "Only enter the base URL. '/chat/completions' will be appended automatically.",- )}- </p>- )}- </div>-- {PROVIDER_PRESETS.find((p) => p.id === selectedPresetId)- ?.requires_key && (- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">- {t("API Key")}{" "}- <span className="text-slate-400">- ({t("optional for local")})- </span>- </label>- <input- type="password"- value={editingProvider.api_key}- onChange={(e) =>- setEditingProvider((prev) =>- prev- ? { ...prev, api_key: e.target.value }- : null,- )- }- placeholder={t(- "Usually not required for local servers",- )}- className="w-full p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg font-mono text-xs"- />- </div>- )}-- <div>- <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1 flex justify-between">- <span>Model</span>- {PROVIDER_PRESETS.find((p) => p.id === selectedPresetId)- ?.models.length! > 0 && (- <button- onClick={() =>- setCustomModelInput(!customModelInput)- }- className="text-[10px] text-blue-600 hover:underline"- >- {customModelInput- ? "Select from list"- : "Enter custom"}- </button>- )}- </label>- <div className="flex gap-2">- {!customModelInput &&- (fetchedModels.length > 0 ||- PROVIDER_PRESETS.find(- (p) => p.id === selectedPresetId,- )?.models.length! > 0) ? (- <div className="relative flex-1">- <select- value={editingProvider.model}- onChange={(e) =>- setEditingProvider((prev) =>- prev- ? { ...prev, model: e.target.value }- : null,- )- }- className="w-full p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm appearance-none"- >- {fetchedModels.length > 0 ? (- <>- <option value="" disabled>- Select a fetched model- </option>- {fetchedModels.map((m) => (- <option key={m} value={m}>- {m}- </option>- ))}- </>- ) : (- PROVIDER_PRESETS.find(- (p) => p.id === selectedPresetId,- )?.models.map((m) => (- <option key={m} value={m}>- {m}- </option>- ))- )}- </select>- <div className="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none text-slate-500">- <svg- className="w-3.5 h-3.5"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="2"- d="M19 9l-7 7-7-7"- ></path>- </svg>- </div>- </div>- ) : (- <input- type="text"- value={editingProvider.model}- onChange={(e) =>- setEditingProvider((prev) =>- prev- ? { ...prev, model: e.target.value }- : null,- )- }- placeholder="gpt-4o-mini"- className="flex-1 p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm"- />- )}- <button- type="button"- onClick={fetchModels}- disabled={fetchingModels || !editingProvider.base_url}- className="p-2 bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 rounded-lg hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors disabled:opacity-50"- title="Refresh Models from API"- >- {fetchingModels ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : (- <RotateCcw className="w-4 h-4" />- )}- </button>- </div>- </div>- <div className="flex items-center justify-between pt-1">- <button- type="button"- onClick={() => handleTestProvider(editingProvider)}- disabled={testingProvider}- className="text-xs text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1"- >- {testingProvider ? (- <Loader2 className="w-3 h-3 animate-spin" />- ) : (- <RefreshCw className="w-3 h-3" />- )}- Test Connection- </button>- {testProviderResult && (- <span- className={`text-[10px] px-2 py-0.5 rounded ${testProviderResult.success ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300" : "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300"}`}- >- {testProviderResult.success- ? "Success!"- : `Failed: ${testProviderResult.message}`}- </span>- )}- </div>- </div>- <div className="px-4 py-3 border-t border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex flex-col gap-2">- {providerError && (- <div className="p-2 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg text-red-600 dark:text-red-400 text-xs">- {providerError}- </div>- )}- <div className="flex justify-end gap-2">- <button- onClick={() => setShowProviderForm(false)}- className="px-3 py-1.5 text-xs text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg font-medium"- >- Cancel- </button>- <button- onClick={() => handleProviderSave(editingProvider)}- disabled={savingProvider}- className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-medium shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"- >- {savingProvider && (- <Loader2 className="w-3 h-3 animate-spin" />- )}- {savingProvider ? t("Saving...") : t("Save Server")}- </button>- </div>- </div>- </div>- </div>- )}- </div>- )}+ {isEditMode ? "Save Changes" : "Add Configuration"}+ </button>+ </div></div>- </div>+ </form>);}++// Helper functions to get env var names+function getEnvVarForBaseUrl(configType: ConfigType): string {+ const mapping: Record<ConfigType, string> = {+ llm: "LLM_HOST",+ embedding: "EMBEDDING_HOST",+ tts: "TTS_URL",+ search: "SEARCH_PROVIDER", // Provider name, not URL (search uses SEARCH_API_KEY for auth)+ };+ return mapping[configType];+}++function getEnvVarForApiKey(configType: ConfigType): string {+ const mapping: Record<ConfigType, string> = {+ llm: "LLM_API_KEY",+ embedding: "EMBEDDING_API_KEY",+ tts: "TTS_API_KEY",+ search: "SEARCH_API_KEY", // Unified API key for all search providers+ };+ return mapping[configType];+}diff --git a/web/components/AddToNotebookModal.tsx b/web/components/AddToNotebookModal.tsxindex c17f669e8..dcac6f135 100644--- a/web/components/AddToNotebookModal.tsx+++ b/web/components/AddToNotebookModal.tsx@@ -23,7 +23,7 @@ interface NotebookOption {interface AddToNotebookModalProps {isOpen: boolean;onClose: () => void;- recordType: "solve" | "question" | "research" | "co_writer";+ recordType: "solve" | "question" | "research" | "co_writer" | "chat";title: string;userQuery: string;output: string;@@ -151,18 +151,18 @@ export default function AddToNotebookModal({return (<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 animate-in fade-in">- <div className="bg-white rounded-2xl shadow-2xl w-[480px] max-h-[80vh] flex flex-col animate-in zoom-in-95">+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-[480px] max-h-[80vh] flex flex-col animate-in zoom-in-95">{/* Header */}- <div className="p-4 border-b border-slate-100 flex items-center justify-between bg-gradient-to-r from-indigo-50 to-purple-50 rounded-t-2xl">- <h3 className="font-bold text-slate-900 flex items-center gap-2">- <Book className="w-5 h-5 text-indigo-600" />+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-900/30 dark:to-purple-900/30 rounded-t-2xl">+ <h3 className="font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">+ <Book className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />Add to Notebook</h3><buttononClick={onClose}- className="p-1 hover:bg-white/50 rounded-lg transition-colors"+ className="p-1 hover:bg-white/50 dark:hover:bg-slate-700 rounded-lg transition-colors">- <X className="w-5 h-5 text-slate-500" />+ <X className="w-5 h-5 text-slate-500 dark:text-slate-400" /></button></div>@@ -170,33 +170,35 @@ export default function AddToNotebookModal({<div className="flex-1 overflow-y-auto p-4">{success ? (<div className="py-12 text-center animate-in zoom-in-95">- <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">- <Check className="w-8 h-8 text-green-600" />+ <div className="w-16 h-16 bg-green-100 dark:bg-green-900/40 rounded-full flex items-center justify-center mx-auto mb-4">+ <Check className="w-8 h-8 text-green-600 dark:text-green-400" /></div>- <h4 className="text-lg font-bold text-slate-900 mb-1">+ <h4 className="text-lg font-bold text-slate-900 dark:text-slate-100 mb-1">Added Successfully!</h4>- <p className="text-sm text-slate-500">+ <p className="text-sm text-slate-500 dark:text-slate-400">Record has been saved to {selectedIds.length} notebook{selectedIds.length > 1 ? "s" : ""}</p></div>) : loading ? (<div className="py-12 text-center">- <Loader2 className="w-8 h-8 text-indigo-600 animate-spin mx-auto mb-2" />- <p className="text-slate-500">Loading notebooks...</p>+ <Loader2 className="w-8 h-8 text-indigo-600 dark:text-indigo-400 animate-spin mx-auto mb-2" />+ <p className="text-slate-500 dark:text-slate-400">+ Loading notebooks...+ </p></div>) : (<>{/* Record Preview */}- <div className="mb-4 p-3 bg-slate-50 rounded-xl border border-slate-100">- <div className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-1">+ <div className="mb-4 p-3 bg-slate-50 dark:bg-slate-700/50 rounded-xl border border-slate-100 dark:border-slate-600">+ <div className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">Record Preview</div>- <h4 className="font-semibold text-slate-900 truncate">+ <h4 className="font-semibold text-slate-900 dark:text-slate-100 truncate">{title}</h4>- <p className="text-xs text-slate-500 line-clamp-2 mt-1">+ <p className="text-xs text-slate-500 dark:text-slate-400 line-clamp-2 mt-1">{userQuery}</p></div>@@ -204,12 +206,12 @@ export default function AddToNotebookModal({{/* Notebook Selection */}<div className="mb-4"><div className="flex items-center justify-between mb-2">- <label className="text-xs font-bold text-slate-500 uppercase tracking-wider">+ <label className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">Select Notebooks</label><buttononClick={() => setShowCreateForm(!showCreateForm)}- className="text-xs text-indigo-600 hover:text-indigo-700 flex items-center gap-1"+ className="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700 dark:hover:text-indigo-300 flex items-center gap-1"><Plus className="w-3 h-3" />New Notebook@@ -218,7 +220,7 @@ export default function AddToNotebookModal({{/* Create New Notebook Form */}{showCreateForm && (- <div className="mb-3 p-3 bg-indigo-50 rounded-xl border border-indigo-100 animate-in slide-in-from-top-2">+ <div className="mb-3 p-3 bg-indigo-50 dark:bg-indigo-900/30 rounded-xl border border-indigo-100 dark:border-indigo-800 animate-in slide-in-from-top-2"><inputtype="text"value={newNotebook.name}@@ -229,11 +231,13 @@ export default function AddToNotebookModal({}))}placeholder="Notebook name"- className="w-full px-3 py-2 mb-2 border border-indigo-200 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none bg-white"+ className="w-full px-3 py-2 mb-2 border border-indigo-200 dark:border-indigo-700 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 outline-none bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100"autoFocus/><div className="flex items-center gap-2 mb-2">- <span className="text-xs text-slate-500">Color:</span>+ <span className="text-xs text-slate-500 dark:text-slate-400">+ Color:+ </span><div className="flex gap-1">{COLORS.slice(0, 6).map((color) => (<button@@ -243,7 +247,7 @@ export default function AddToNotebookModal({}className={`w-5 h-5 rounded transition-all ${newNotebook.color === color- ? "ring-2 ring-offset-1 ring-slate-400 scale-110"+ ? "ring-2 ring-offset-1 ring-slate-400 dark:ring-slate-500 dark:ring-offset-slate-800 scale-110": ""}`}style={{ backgroundColor: color }}@@ -254,7 +258,7 @@ export default function AddToNotebookModal({<div className="flex justify-end gap-2"><buttononClick={() => setShowCreateForm(false)}- className="px-3 py-1.5 text-xs text-slate-600 hover:bg-white rounded-lg transition-colors"+ className="px-3 py-1.5 text-xs text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 rounded-lg transition-colors">Cancel</button>@@ -273,9 +277,11 @@ export default function AddToNotebookModal({{/* Notebook List */}{notebooks.length === 0 ? (<div className="py-8 text-center">- <FolderOpen className="w-10 h-10 text-slate-200 mx-auto mb-2" />- <p className="text-sm text-slate-500">No notebooks yet</p>- <p className="text-xs text-slate-400">+ <FolderOpen className="w-10 h-10 text-slate-200 dark:text-slate-600 mx-auto mb-2" />+ <p className="text-sm text-slate-500 dark:text-slate-400">+ No notebooks yet+ </p>+ <p className="text-xs text-slate-400 dark:text-slate-500">Create your first notebook above</p></div>@@ -287,8 +293,8 @@ export default function AddToNotebookModal({onClick={() => toggleNotebook(nb.id)}className={`w-full p-3 rounded-xl flex items-center gap-3 transition-all border-2 text-left ${selectedIds.includes(nb.id)- ? "bg-indigo-50 border-indigo-300"- : "bg-white border-slate-200 hover:border-indigo-200 hover:bg-slate-50"+ ? "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-700"+ : "bg-white dark:bg-slate-700/50 border-slate-200 dark:border-slate-600 hover:border-indigo-200 dark:hover:border-indigo-700 hover:bg-slate-50 dark:hover:bg-slate-700"}`}><div@@ -301,10 +307,10 @@ export default function AddToNotebookModal({<BookOpen className="w-5 h-5" /></div><div className="flex-1 min-w-0">- <h4 className="font-semibold text-slate-900 truncate text-sm">+ <h4 className="font-semibold text-slate-900 dark:text-slate-100 truncate text-sm">{nb.name}</h4>- <p className="text-xs text-slate-500">+ <p className="text-xs text-slate-500 dark:text-slate-400">{nb.record_count} records</p></div>@@ -312,7 +318,7 @@ export default function AddToNotebookModal({className={`w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all ${selectedIds.includes(nb.id)? "bg-indigo-600 border-indigo-600"- : "border-slate-300"+ : "border-slate-300 dark:border-slate-500"}`}>{selectedIds.includes(nb.id) && (@@ -330,8 +336,8 @@ export default function AddToNotebookModal({{/* Footer */}{!success && !loading && (- <div className="p-4 border-t border-slate-100 flex justify-between items-center">- <span className="text-xs text-slate-500">+ <div className="p-4 border-t border-slate-100 dark:border-slate-700 flex justify-between items-center">+ <span className="text-xs text-slate-500 dark:text-slate-400">{selectedIds.length > 0? `${selectedIds.length} notebook${selectedIds.length > 1 ? "s" : ""} selected`: "Select at least one notebook"}@@ -339,7 +345,7 @@ export default function AddToNotebookModal({<div className="flex gap-2"><buttononClick={onClose}- className="px-4 py-2 text-slate-600 hover:bg-slate-100 rounded-lg transition-colors text-sm"+ className="px-4 py-2 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors text-sm">Cancel</button>diff --git a/web/components/LayoutWrapper.tsx b/web/components/LayoutWrapper.tsxnew file mode 100644index 000000000..5ad65649c--- /dev/null+++ b/web/components/LayoutWrapper.tsx@@ -0,0 +1,15 @@+"use client";++interface LayoutWrapperProps {+ children: React.ReactNode;+}++/**+ * LayoutWrapper - Simplified+ *+ * Previously handled setup wizard display logic.+ * Now just a simple wrapper for children.+ */+export default function LayoutWrapper({ children }: LayoutWrapperProps) {+ return <>{children}</>;+}diff --git a/web/components/Sidebar.tsx b/web/components/Sidebar.tsxindex 81a05c8db..087a7aaa4 100644--- a/web/components/Sidebar.tsx+++ b/web/components/Sidebar.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useState, useRef, useEffect, useMemo } from "react";import Link from "next/link";import Image from "next/image";import { usePathname } from "next/navigation";@@ -20,6 +20,10 @@ import {Globe,ChevronsLeft,ChevronsRight,+ GripVertical,+ Check,+ X,+ LucideIcon,} from "lucide-react";import { useGlobal } from "@/context/GlobalContext";import { getTranslation } from "@/lib/i18n";@@ -27,164 +31,206 @@ import { getTranslation } from "@/lib/i18n";const SIDEBAR_EXPANDED_WIDTH = 256;const SIDEBAR_COLLAPSED_WIDTH = 64;+// Navigation item type+interface NavItem {+ name: string;+ href: string;+ icon: LucideIcon;+}++// All available navigation items (static reference)+const ALL_NAV_ITEMS: Record<string, { icon: LucideIcon; nameKey: string }> = {+ "/": { icon: Home, nameKey: "Home" },+ "/history": { icon: History, nameKey: "History" },+ "/knowledge": { icon: BookOpen, nameKey: "Knowledge Bases" },+ "/notebook": { icon: Book, nameKey: "Notebooks" },+ "/question": { icon: PenTool, nameKey: "Question Generator" },+ "/solver": { icon: Calculator, nameKey: "Smart Solver" },+ "/guide": { icon: GraduationCap, nameKey: "Guided Learning" },+ "/ideagen": { icon: Lightbulb, nameKey: "IdeaGen" },+ "/research": { icon: Microscope, nameKey: "Deep Research" },+ "/co_writer": { icon: Edit3, nameKey: "Co-Writer" },+};+export default function Sidebar() {const pathname = usePathname();- const { uiSettings, sidebarCollapsed, toggleSidebar } = useGlobal();+ const {+ uiSettings,+ sidebarCollapsed,+ toggleSidebar,+ sidebarDescription,+ setSidebarDescription,+ sidebarNavOrder,+ setSidebarNavOrder,+ } = useGlobal();const lang = uiSettings.language;const t = (key: string) => getTranslation(lang, key);const [showTooltip, setShowTooltip] = useState<string | null>(null);- const navGroups = [- {- name: "",- items: [- { name: t("Home"), href: "/", icon: Home },- { name: t("History"), href: "/history", icon: History },- { name: t("Knowledge Bases"), href: "/knowledge", icon: BookOpen },- { name: t("Notebooks"), href: "/notebook", icon: Book },- ],- },- {- name: t("Learn"),- items: [- { name: t("Question Generator"), href: "/question", icon: PenTool },- { name: t("Smart Solver"), href: "/solver", icon: Calculator },- { name: t("Guided Learning"), href: "/guide", icon: GraduationCap },- ],- },- {- name: t("Research"),- items: [- { name: t("IdeaGen"), href: "/ideagen", icon: Lightbulb },- { name: t("Deep Research"), href: "/research", icon: Microscope },- { name: t("Co-Writer"), href: "/co_writer", icon: Edit3 },- ],- },- ];+ // Editable description state+ const [isEditingDescription, setIsEditingDescription] = useState(false);+ const [editingDescriptionValue, setEditingDescriptionValue] =+ useState(sidebarDescription);+ const descriptionInputRef = useRef<HTMLInputElement>(null);- const currentWidth = sidebarCollapsed- ? SIDEBAR_COLLAPSED_WIDTH- : SIDEBAR_EXPANDED_WIDTH;+ // Drag and drop state+ const [draggedItem, setDraggedItem] = useState<string | null>(null);+ const [dragOverItem, setDragOverItem] = useState<string | null>(null);+ const [dragGroup, setDragGroup] = useState<"start" | "learnResearch" | null>(+ null,+ );- // Collapsed sidebar- if (sidebarCollapsed) {- return (- <div- className="relative flex-shrink-0 bg-slate-50/80 dark:bg-slate-800/80 h-full border-r border-slate-200 dark:border-slate-700 flex flex-col"- style={{ width: SIDEBAR_COLLAPSED_WIDTH }}- >- {/* Header */}- <div className="px-2 py-3 border-b border-slate-100 dark:border-slate-700 flex justify-center">- <div className="w-8 h-8 rounded-lg flex items-center justify-center overflow-hidden">- <Image- src="/logo.png"- alt="DeepTutor Logo"- width={32}- height={32}- className="object-contain"- priority- />- </div>- </div>+ // Build navigation items from saved order+ const buildNavItems = (hrefs: string[]): NavItem[] => {+ return hrefs+ .filter((href) => ALL_NAV_ITEMS[href])+ .map((href) => ({+ name: t(ALL_NAV_ITEMS[href].nameKey),+ href,+ icon: ALL_NAV_ITEMS[href].icon,+ }));+ };- {/* Navigation */}- <nav className="flex-1 overflow-y-auto py-2 space-y-1">- {navGroups.map((group, idx) => (- <div key={idx} className="space-y-0.5 px-2">- {group.items.map((item) => {- const isActive = pathname === item.href;- return (- <div key={item.href} className="relative">- <Link- href={item.href}- className={`group flex items-center justify-center p-2 rounded-md border ${- isActive- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border-slate-100 dark:border-slate-600"- : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-blue-600 dark:hover:text-blue-400 hover:shadow-sm border-transparent hover:border-slate-100 dark:hover:border-slate-600"- }`}- onMouseEnter={() => setShowTooltip(item.href)}- onMouseLeave={() => setShowTooltip(null)}- >- <item.icon- className={`w-5 h-5 flex-shrink-0 ${- isActive- ? "text-blue-500 dark:text-blue-400"- : "text-slate-400 dark:text-slate-500 group-hover:text-blue-500 dark:group-hover:text-blue-400"- }`}- />- </Link>- {showTooltip === item.href && (- <div className="absolute left-full ml-2 top-1/2 -translate-y-1/2 z-50 px-2.5 py-1.5 bg-slate-900 dark:bg-slate-700 text-white text-xs rounded-lg shadow-lg whitespace-nowrap pointer-events-none">- {item.name}- <div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-slate-900 dark:border-r-slate-700" />- </div>- )}- </div>- );- })}- {idx < navGroups.length - 1 && (- <div className="h-px bg-slate-200 dark:bg-slate-700 my-2" />- )}- </div>- ))}- </nav>-- {/* Footer */}- <div className="px-2 py-2 border-t border-slate-100 dark:border-slate-700 bg-slate-50/30 dark:bg-slate-800/30">- <div className="relative">- <Link- href="/settings"- className={`flex items-center justify-center p-2 rounded-md ${- pathname === "/settings"- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border border-slate-100 dark:border-slate-600"- : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-slate-900 dark:hover:text-slate-100"- }`}- onMouseEnter={() => setShowTooltip("/settings")}- onMouseLeave={() => setShowTooltip(null)}- >- <Settings- className={`w-5 h-5 flex-shrink-0 ${- pathname === "/settings"- ? "text-blue-500 dark:text-blue-400"- : "text-slate-400 dark:text-slate-500"- }`}- />- </Link>- {showTooltip === "/settings" && (- <div className="absolute left-full ml-2 top-1/2 -translate-y-1/2 z-50 px-2.5 py-1.5 bg-slate-900 dark:bg-slate-700 text-white text-xs rounded-lg shadow-lg whitespace-nowrap pointer-events-none">- {t("Settings")}- <div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-slate-900 dark:border-r-slate-700" />- </div>- )}- </div>+ const navGroups = useMemo(+ () => [+ {+ id: "start" as const,+ name: "WORKSPACE",+ items: buildNavItems(sidebarNavOrder.start),+ },+ {+ id: "learnResearch" as const,+ name: t("Learn") + " & " + t("Research"),+ items: buildNavItems(sidebarNavOrder.learnResearch),+ },+ ],+ [sidebarNavOrder, lang],+ );- {/* Expand button at bottom */}- <button- onClick={toggleSidebar}- className="w-full mt-2 flex items-center justify-center p-2 rounded-md text-slate-400 dark:text-slate-500 hover:bg-white dark:hover:bg-slate-700 hover:text-blue-500 dark:hover:text-blue-400 hover:shadow-sm border border-transparent hover:border-slate-100 dark:hover:border-slate-600"- title={t("Expand sidebar")}- >- <ChevronsRight className="w-4 h-4" />- </button>- </div>- </div>+ // Handle description edit+ const handleDescriptionEdit = () => {+ setEditingDescriptionValue(sidebarDescription);+ setIsEditingDescription(true);+ };++ const handleDescriptionSave = () => {+ setSidebarDescription(+ editingDescriptionValue.trim() || "✨ Your description here",);- }+ setIsEditingDescription(false);+ };++ const handleDescriptionCancel = () => {+ setEditingDescriptionValue(sidebarDescription);+ setIsEditingDescription(false);+ };++ const handleDescriptionKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter") {+ handleDescriptionSave();+ } else if (e.key === "Escape") {+ handleDescriptionCancel();+ }+ };++ // Focus input when editing starts+ useEffect(() => {+ if (isEditingDescription && descriptionInputRef.current) {+ descriptionInputRef.current.focus();+ descriptionInputRef.current.select();+ }+ }, [isEditingDescription]);++ // Drag and drop handlers+ const handleDragStart = (+ e: React.DragEvent,+ href: string,+ groupId: "start" | "learnResearch",+ ) => {+ setDraggedItem(href);+ setDragGroup(groupId);+ e.dataTransfer.effectAllowed = "move";+ e.dataTransfer.setData("text/plain", href);+ };++ const handleDragOver = (+ e: React.DragEvent,+ href: string,+ groupId: "start" | "learnResearch",+ ) => {+ e.preventDefault();+ if (dragGroup !== groupId) return; // Only allow drag within same group+ if (draggedItem !== href) {+ setDragOverItem(href);+ }+ };++ const handleDragLeave = () => {+ setDragOverItem(null);+ };++ const handleDrop = (+ e: React.DragEvent,+ targetHref: string,+ groupId: "start" | "learnResearch",+ ) => {+ e.preventDefault();+ if (!draggedItem || dragGroup !== groupId) return;++ const groupKey = groupId;+ const currentOrder = [...sidebarNavOrder[groupKey]];+ const draggedIndex = currentOrder.indexOf(draggedItem);+ const targetIndex = currentOrder.indexOf(targetHref);++ if (+ draggedIndex !== -1 &&+ targetIndex !== -1 &&+ draggedIndex !== targetIndex+ ) {+ // Remove dragged item and insert at new position+ currentOrder.splice(draggedIndex, 1);+ currentOrder.splice(targetIndex, 0, draggedItem);++ setSidebarNavOrder({+ ...sidebarNavOrder,+ [groupKey]: currentOrder,+ });+ }++ setDraggedItem(null);+ setDragOverItem(null);+ setDragGroup(null);+ };++ const handleDragEnd = () => {+ setDraggedItem(null);+ setDragOverItem(null);+ setDragGroup(null);+ };++ const currentWidth = sidebarCollapsed+ ? SIDEBAR_COLLAPSED_WIDTH+ : SIDEBAR_EXPANDED_WIDTH;- // Expanded sidebarreturn (<div- className="relative flex-shrink-0 bg-slate-50/80 dark:bg-slate-800/80 h-full border-r border-slate-200 dark:border-slate-700 flex flex-col"+ className="relative flex-shrink-0 bg-slate-50/80 dark:bg-slate-800/80 h-full border-r border-slate-200 dark:border-slate-700 flex flex-col transition-all duration-300 ease-in-out overflow-hidden"style={{ width: currentWidth }}>{/* Header */}- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700">+ <div+ className={`border-b border-slate-100 dark:border-slate-700 transition-all duration-300 ${+ sidebarCollapsed ? "px-2 py-3" : "px-4 py-3"+ }`}+ ><div className="flex flex-col gap-2">- <div className="flex items-center justify-between">+ <div+ className={`flex items-center ${sidebarCollapsed ? "justify-center" : "justify-between"}`}+ ><div className="flex items-center gap-2.5">- <div className="w-8 h-8 rounded-lg flex items-center justify-center overflow-hidden">+ <div className="w-8 h-8 rounded-lg flex items-center justify-center overflow-hidden flex-shrink-0"><Imagesrc="/logo.png"alt="DeepTutor Logo"@@ -194,15 +240,27 @@ export default function Sidebar() {priority/></div>- <h1 className="font-bold text-slate-900 dark:text-slate-100 tracking-tight text-base truncate">+ <h1+ className={`font-bold text-slate-900 dark:text-slate-100 tracking-tight text-base whitespace-nowrap transition-all duration-300 ${+ sidebarCollapsed+ ? "opacity-0 w-0 overflow-hidden"+ : "opacity-100"+ }`}+ >DeepTutor</h1></div>- <div className="flex items-center gap-0.5">+ <div+ className={`flex items-center gap-0.5 transition-all duration-300 ${+ sidebarCollapsed+ ? "opacity-0 w-0 overflow-hidden"+ : "opacity-100"+ }`}+ >{/* Collapse button */}<buttononClick={toggleSidebar}- className="text-slate-400 hover:text-blue-500 dark:hover:text-blue-400 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded"+ className="text-slate-400 hover:text-blue-500 dark:hover:text-blue-400 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-colors"title={t("Collapse sidebar")}><ChevronsLeft className="w-4 h-4" />@@ -211,7 +269,7 @@ export default function Sidebar() {href="https://hkuds.github.io/DeepTutor/"target="_blank"rel="noopener noreferrer"- className="text-slate-400 hover:text-blue-500 dark:hover:text-blue-400 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded"+ className="text-slate-400 hover:text-blue-500 dark:hover:text-blue-400 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-colors"title="Visit DeepTutor Homepage"><Globe className="w-4 h-4" />@@ -220,7 +278,7 @@ export default function Sidebar() {href="https://github.com/HKUDS/DeepTutor"target="_blank"rel="noopener noreferrer"- className="text-slate-400 hover:text-slate-800 dark:hover:text-slate-200 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded"+ className="text-slate-400 hover:text-slate-800 dark:hover:text-slate-200 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-700 rounded transition-colors"title="View on GitHub"><Github className="w-4 h-4" />@@ -228,71 +286,232 @@ export default function Sidebar() {</div></div>- <div className="text-[10px] font-medium text-slate-500 dark:text-slate-400 bg-slate-100/50 dark:bg-slate-700/50 px-2 py-1.5 rounded-md border border-slate-100 dark:border-slate-600 truncate">- ✨ Data Intelligence Lab @ HKU+ {/* Editable Description - only show when expanded */}+ <div+ className={`transition-all duration-300 ${+ sidebarCollapsed ? "opacity-0 h-0 overflow-hidden" : "opacity-100"+ }`}+ >+ {isEditingDescription ? (+ <div className="flex items-center gap-1">+ <input+ ref={descriptionInputRef}+ type="text"+ value={editingDescriptionValue}+ onChange={(e) => setEditingDescriptionValue(e.target.value)}+ onKeyDown={handleDescriptionKeyDown}+ className="flex-1 text-[10px] font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-600 px-2 py-1.5 rounded-md border border-blue-300 dark:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20"+ placeholder="Enter your description..."+ />+ <button+ onClick={handleDescriptionSave}+ className="p-1 text-green-500 hover:text-green-600 dark:text-green-400 dark:hover:text-green-300"+ title="Save"+ >+ <Check className="w-3.5 h-3.5" />+ </button>+ <button+ onClick={handleDescriptionCancel}+ className="p-1 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300"+ title="Cancel"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ ) : (+ <div+ onClick={handleDescriptionEdit}+ className="text-[10px] font-medium text-slate-500 dark:text-slate-400 bg-slate-100/50 dark:bg-slate-700/50 px-2 py-1.5 rounded-md border border-slate-100 dark:border-slate-600 truncate cursor-pointer hover:bg-slate-100 dark:hover:bg-slate-700 hover:border-slate-200 dark:hover:border-slate-500 transition-colors group"+ title="Click to edit"+ >+ <span className="group-hover:hidden">{sidebarDescription}</span>+ <span className="hidden group-hover:inline text-blue-500 dark:text-blue-400">+ ✏️ {t("Click to edit")}+ </span>+ </div>+ )}</div></div></div>{/* Navigation */}- <nav className="flex-1 overflow-y-auto px-3 py-2 space-y-3">+ <nav+ className={`flex-1 overflow-y-auto py-2 space-y-4 transition-all duration-300 ${+ sidebarCollapsed ? "px-2" : "px-2"+ }`}+ >{navGroups.map((group, idx) => (- <div key={idx}>- {group.name && (- <div className="text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider px-3 mb-1 truncate">- {group.name}- </div>- )}- <div className="space-y-0.5">+ <div key={group.id}>+ {/* Group title - only show when expanded */}+ <div+ className={`text-[10px] font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-2 truncate transition-all duration-300 ${+ sidebarCollapsed+ ? "opacity-0 h-0 overflow-hidden px-0"+ : "opacity-100 px-1"+ }`}+ >+ {group.name}+ </div>+ <div className="space-y-1">{group.items.map((item) => {const isActive = pathname === item.href;+ const isDragging = draggedItem === item.href;+ const isDragOver =+ dragOverItem === item.href && dragGroup === group.id;+return (- <Link+ <divkey={item.href}- href={item.href}- className={`group flex items-center gap-2.5 px-3 py-1.5 rounded-md border ${- isActive- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border-slate-100 dark:border-slate-600"- : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-blue-600 dark:hover:text-blue-400 hover:shadow-sm border-transparent hover:border-slate-100 dark:hover:border-slate-600"+ draggable={!sidebarCollapsed}+ onDragStart={(e) =>+ !sidebarCollapsed &&+ handleDragStart(e, item.href, group.id)+ }+ onDragOver={(e) =>+ !sidebarCollapsed &&+ handleDragOver(e, item.href, group.id)+ }+ onDragLeave={handleDragLeave}+ onDrop={(e) =>+ !sidebarCollapsed && handleDrop(e, item.href, group.id)+ }+ onDragEnd={handleDragEnd}+ className={`group relative ${isDragging ? "opacity-50" : ""} ${+ isDragOver ? "border-t-2 border-blue-500" : ""}`}>- <item.icon- className={`w-4 h-4 flex-shrink-0 ${+ <Link+ href={item.href}+ className={`flex items-center rounded-md border transition-all duration-200 ${+ sidebarCollapsed+ ? "justify-center p-2"+ : "gap-2.5 pl-2 pr-1.5 py-2"+ } ${isActive- ? "text-blue-500 dark:text-blue-400"- : "text-slate-400 dark:text-slate-500 group-hover:text-blue-500 dark:group-hover:text-blue-400"+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border-slate-100 dark:border-slate-600"+ : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-blue-600 dark:hover:text-blue-400 hover:shadow-sm border-transparent hover:border-slate-100 dark:hover:border-slate-600"}`}- />- <span className="font-medium text-sm truncate">- {item.name}- </span>- </Link>+ onMouseEnter={() =>+ sidebarCollapsed && setShowTooltip(item.href)+ }+ onMouseLeave={() => setShowTooltip(null)}+ >+ <item.icon+ className={`w-5 h-5 flex-shrink-0 transition-colors ${+ isActive+ ? "text-blue-500 dark:text-blue-400"+ : "text-slate-400 dark:text-slate-500 group-hover:text-blue-500 dark:group-hover:text-blue-400"+ }`}+ />+ <span+ className={`font-medium text-sm whitespace-nowrap flex-1 transition-all duration-300 ${+ sidebarCollapsed+ ? "opacity-0 w-0 overflow-hidden"+ : "opacity-100"+ }`}+ >+ {item.name}+ </span>+ {/* Drag handle - only show when expanded and hovering, now on right */}+ <div+ className={`flex-shrink-0 transition-all duration-300 ${+ sidebarCollapsed+ ? "w-0 opacity-0 overflow-hidden"+ : "opacity-0 group-hover:opacity-100"+ }`}+ >+ <GripVertical className="w-3.5 h-3.5 text-slate-300 dark:text-slate-600 cursor-grab active:cursor-grabbing" />+ </div>+ </Link>+ {/* Tooltip for collapsed state */}+ {sidebarCollapsed && showTooltip === item.href && (+ <div className="absolute left-full ml-2 top-1/2 -translate-y-1/2 z-50 px-2.5 py-1.5 bg-slate-900 dark:bg-slate-700 text-white text-xs rounded-lg shadow-lg whitespace-nowrap pointer-events-none">+ {item.name}+ <div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-slate-900 dark:border-r-slate-700" />+ </div>+ )}+ </div>);})}</div>+ {/* Divider between groups in collapsed mode */}+ {sidebarCollapsed && idx < navGroups.length - 1 && (+ <div className="h-px bg-slate-200 dark:bg-slate-700 my-2 mx-1" />+ )}</div>))}</nav>{/* Footer */}- <div className="px-3 py-2 border-t border-slate-100 dark:border-slate-700 bg-slate-50/30 dark:bg-slate-800/30">- <Link- href="/settings"- className={`w-full flex items-center gap-2.5 px-3 py-1.5 rounded-md text-sm ${- pathname === "/settings"- ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border border-slate-100 dark:border-slate-600"- : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-slate-900 dark:hover:text-slate-100"+ <div+ className={`border-t border-slate-100 dark:border-slate-700 bg-slate-50/30 dark:bg-slate-800/30 transition-all duration-300 ${+ sidebarCollapsed ? "px-2 py-2" : "px-2 py-2"+ }`}+ >+ <div className="relative">+ <Link+ href="/settings"+ className={`flex items-center rounded-md text-sm transition-all duration-200 ${+ sidebarCollapsed+ ? "justify-center p-2"+ : "gap-2.5 pl-2 pr-1.5 py-2"+ } ${+ pathname === "/settings"+ ? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm border border-slate-100 dark:border-slate-600"+ : "text-slate-600 dark:text-slate-300 hover:bg-white dark:hover:bg-slate-700 hover:text-slate-900 dark:hover:text-slate-100"+ }`}+ onMouseEnter={() => sidebarCollapsed && setShowTooltip("/settings")}+ onMouseLeave={() => setShowTooltip(null)}+ >+ <Settings+ className={`w-5 h-5 flex-shrink-0 transition-colors ${+ pathname === "/settings"+ ? "text-blue-500 dark:text-blue-400"+ : "text-slate-400 dark:text-slate-500"+ }`}+ />+ <span+ className={`whitespace-nowrap flex-1 transition-all duration-300 ${+ sidebarCollapsed+ ? "opacity-0 w-0 overflow-hidden"+ : "opacity-100"+ }`}+ >+ {t("Settings")}+ </span>+ </Link>+ {/* Tooltip for collapsed state */}+ {sidebarCollapsed && showTooltip === "/settings" && (+ <div className="absolute left-full ml-2 top-1/2 -translate-y-1/2 z-50 px-2.5 py-1.5 bg-slate-900 dark:bg-slate-700 text-white text-xs rounded-lg shadow-lg whitespace-nowrap pointer-events-none">+ {t("Settings")}+ <div className="absolute right-full top-1/2 -translate-y-1/2 border-4 border-transparent border-r-slate-900 dark:border-r-slate-700" />+ </div>+ )}+ </div>++ {/* Expand/Collapse button at bottom */}+ <button+ onClick={toggleSidebar}+ className={`w-full mt-2 flex items-center rounded-md text-slate-400 dark:text-slate-500 hover:bg-white dark:hover:bg-slate-700 hover:text-blue-500 dark:hover:text-blue-400 hover:shadow-sm border border-transparent hover:border-slate-100 dark:hover:border-slate-600 transition-all duration-200 ${+ sidebarCollapsed ? "justify-center p-2" : "gap-2.5 pl-2 pr-1.5 py-2"}`}+ title={sidebarCollapsed ? t("Expand sidebar") : t("Collapse sidebar")}>- <Settings- className={`w-4 h-4 flex-shrink-0 ${- pathname === "/settings"- ? "text-blue-500 dark:text-blue-400"- : "text-slate-400 dark:text-slate-500"+ <div className="w-5 h-5 flex items-center justify-center flex-shrink-0">+ {sidebarCollapsed ? (+ <ChevronsRight className="w-4 h-4" />+ ) : (+ <ChevronsLeft className="w-4 h-4" />+ )}+ </div>+ <span+ className={`text-sm whitespace-nowrap flex-1 transition-all duration-300 ${+ sidebarCollapsed ? "opacity-0 w-0 overflow-hidden" : "opacity-100"}`}- />- <span>{t("Settings")}</span>- </Link>+ >+ {t("Collapse sidebar")}+ </span>+ </button></div></div>);diff --git a/web/components/index.ts b/web/components/index.tsindex 4971dfbdd..7fc66b10c 100644--- a/web/components/index.ts+++ b/web/components/index.ts@@ -10,6 +10,8 @@ export { default as Sidebar } from "./Sidebar";export { default as ActivityDetail } from "./ActivityDetail";export { default as CoWriterEditor } from "./CoWriterEditor";export { default as AddToNotebookModal } from "./AddToNotebookModal";+export { default as SetupWizard } from "./SetupWizard";+export { default as LayoutWrapper } from "./LayoutWrapper";// Re-export types if neededexport type {} from "./AddToNotebookModal";diff --git a/web/components/question/ActiveQuestionDetail.tsx b/web/components/question/ActiveQuestionDetail.tsxdeleted file mode 100644index 485b58fb0..000000000--- a/web/components/question/ActiveQuestionDetail.tsx+++ /dev/null@@ -1,366 +0,0 @@-import React from "react";-import { QuestionTask } from "../../types/question";-import {- Terminal,- FileQuestion,- CheckCircle2,- AlertCircle,- Loader2,- Search,- Target,- Zap,- Link2,- Lightbulb,- BookOpen,-} from "lucide-react";-import ReactMarkdown from "react-markdown";-import remarkMath from "remark-math";-import rehypeKatex from "rehype-katex";-import { processLatexContent } from "@/lib/latex";--interface ActiveQuestionDetailProps {- task: QuestionTask | null;- mode?: "custom" | "mimic";-}--const getStatusBadge = (status: QuestionTask["status"], extended?: boolean) => {- if (status === "done" && extended) {- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 flex items-center gap-1">- <Zap className="w-3 h-3" />- Extended- </span>- );- }- switch (status) {- case "done":- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300">- Done- </span>- );- case "generating":- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 flex items-center gap-1">- <Loader2 className="w-3 h-3 animate-spin" />- Generating- </span>- );- case "analyzing":- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300 flex items-center gap-1">- <Search className="w-3 h-3" />- Analyzing- </span>- );- case "validating":- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 flex items-center gap-1">- <Search className="w-3 h-3" />- Validating- </span>- );- case "error":- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">- Error- </span>- );- default:- return (- <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400">- Pending- </span>- );- }-};--export const ActiveQuestionDetail: React.FC<ActiveQuestionDetailProps> = ({- task,- mode = "custom",-}) => {- const isMimicMode = mode === "mimic";- if (!task) {- return (- <div className="h-full flex flex-col items-center justify-center text-slate-400 dark:text-slate-500 bg-slate-50/50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700">- <Terminal className="w-12 h-12 mb-3 opacity-20" />- <p className="text-sm">Select a question task to view details</p>- </div>- );- }-- return (- <div className="h-full flex flex-col bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden">- {/* Header */}- <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex justify-between items-center">- <div className="flex items-center gap-2 overflow-hidden">- <FileQuestion className="w-4 h-4 text-slate-500 dark:text-slate-400 shrink-0" />- <h3- className="font-semibold text-slate-800 dark:text-slate-200 text-sm truncate"- title={task.id}- >- {task.id}- </h3>- </div>- <div className="flex items-center gap-2 shrink-0">- {task.round && (- <span className="text-xs font-mono text-slate-400 dark:text-slate-500">- Round {task.round}- </span>- )}- {getStatusBadge(task.status, task.extended)}- </div>- </div>-- {/* Content */}- <div className="flex-1 overflow-y-auto p-4 space-y-4">- {/* Focus / Origin Question Section */}- <div- className={`rounded-lg p-4 border ${isMimicMode ? "bg-amber-50 dark:bg-amber-900/30 border-amber-100 dark:border-amber-800" : "bg-indigo-50 dark:bg-indigo-900/30 border-indigo-100 dark:border-indigo-800"}`}- >- <div className="flex items-center gap-2 mb-2">- {isMimicMode ? (- <>- <BookOpen className="w-4 h-4 text-amber-600 dark:text-amber-400" />- <span className="text-xs font-bold uppercase tracking-wider text-amber-700 dark:text-amber-300">- Origin Question- </span>- </>- ) : (- <>- <Target className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />- <span className="text-xs font-bold uppercase tracking-wider text-indigo-600 dark:text-indigo-400">- Focus- </span>- </>- )}- </div>- {isMimicMode ? (- <div className="prose prose-sm dark:prose-invert max-w-none text-amber-900 dark:text-amber-200">- {task.focus ? (- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(task.focus)}- </ReactMarkdown>- ) : (- <span className="text-amber-600 dark:text-amber-400 italic">- N/A- </span>- )}- </div>- ) : (- <>- <p className="text-sm text-indigo-800 dark:text-indigo-200">- {task.focus || "N/A"}- </p>- {task.scenarioHint && (- <p className="text-xs text-indigo-600 dark:text-indigo-400 mt-2 italic">- Hint: {task.scenarioHint}- </p>- )}- </>- )}- </div>-- {/* Error Section */}- {task.error && (- <div className="bg-red-50 dark:bg-red-900/30 rounded-lg p-4 border border-red-100 dark:border-red-800">- <div className="flex items-center gap-2 mb-2">- <AlertCircle className="w-4 h-4 text-red-500 dark:text-red-400" />- <span className="text-xs font-bold uppercase tracking-wider text-red-600 dark:text-red-400">- Error- </span>- </div>- <p className="text-sm text-red-800 dark:text-red-200">- {task.error}- </p>- </div>- )}-- {/* Generated Question */}- {task.result?.question && (- <div className="space-y-4">- {/* Extension Analysis (for extended questions) */}- {task.extended && task.result.validation && (- <>- {task.result.validation.kb_connection && (- <div className="bg-amber-50 dark:bg-amber-900/30 rounded-lg p-4 border border-amber-100 dark:border-amber-800">- <div className="flex items-center gap-2 mb-2">- <Link2 className="w-4 h-4 text-amber-600 dark:text-amber-400" />- <span className="text-xs font-bold uppercase tracking-wider text-amber-700 dark:text-amber-300">- Knowledge Base Connection- </span>- </div>- <p className="text-sm text-amber-800 dark:text-amber-200">- {task.result.validation.kb_connection}- </p>- </div>- )}- {task.result.validation.extended_aspect && (- <div className="bg-orange-50 dark:bg-orange-900/30 rounded-lg p-4 border border-orange-100 dark:border-orange-800">- <div className="flex items-center gap-2 mb-2">- <Lightbulb className="w-4 h-4 text-orange-600 dark:text-orange-400" />- <span className="text-xs font-bold uppercase tracking-wider text-orange-700 dark:text-orange-300">- Extended Aspects- </span>- </div>- <p className="text-sm text-orange-800 dark:text-orange-200">- {task.result.validation.extended_aspect}- </p>- </div>- )}- </>- )}-- <div- className={`rounded-lg p-4 border ${task.extended ? "bg-amber-50 dark:bg-amber-900/30 border-amber-100 dark:border-amber-800" : "bg-emerald-50 dark:bg-emerald-900/30 border-emerald-100 dark:border-emerald-800"}`}- >- <div className="flex items-center gap-2 mb-2">- {task.extended ? (- <Zap className="w-4 h-4 text-amber-600 dark:text-amber-400" />- ) : (- <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />- )}- <span- className={`text-xs font-bold uppercase tracking-wider ${task.extended ? "text-amber-700 dark:text-amber-300" : "text-emerald-600 dark:text-emerald-400"}`}- >- {task.extended ? "Extended Question" : "Generated Question"}- </span>- </div>- <div className="text-sm text-slate-800 dark:text-slate-200 prose prose-sm dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {task.result.question.question}- </ReactMarkdown>- </div>- </div>-- {/* Options (for choice questions) */}- {task.result.question.options && (- <div className="bg-slate-50 dark:bg-slate-700 rounded-lg p-4 border border-slate-100 dark:border-slate-600">- <span className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 block mb-2">- Options- </span>- <div className="space-y-2">- {Object.entries(task.result.question.options).map(- ([key, value]) => (- <div key={key} className="flex items-start gap-2">- <span className="font-semibold text-sm text-slate-600 dark:text-slate-400">- {key}.- </span>- <span className="text-sm text-slate-700 dark:text-slate-300">- {value}- </span>- </div>- ),- )}- </div>- </div>- )}-- {/* Answer */}- <div className="bg-blue-50 dark:bg-blue-900/30 rounded-lg p-4 border border-blue-100 dark:border-blue-800">- <span className="text-xs font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400 block mb-2">- Correct Answer- </span>- <div className="text-sm text-slate-800 dark:text-slate-200 prose prose-sm dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {task.result.question.correct_answer}- </ReactMarkdown>- </div>- </div>-- {/* Explanation */}- {task.result.question.explanation && (- <div className="bg-purple-50 dark:bg-purple-900/30 rounded-lg p-4 border border-purple-100 dark:border-purple-800">- <span className="text-xs font-bold uppercase tracking-wider text-purple-600 dark:text-purple-400 block mb-2">- Explanation- </span>- <div className="text-sm text-slate-700 dark:text-slate-300 prose prose-sm dark:prose-invert max-w-none">- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {task.result.question.explanation}- </ReactMarkdown>- </div>- </div>- )}-- {/* Validation Info */}- {task.result.validation && (- <div className="bg-slate-50 dark:bg-slate-700 rounded-lg p-4 border border-slate-100 dark:border-slate-600">- <span className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 block mb-2">- Validation Summary- </span>- <div className="text-xs text-slate-600 dark:text-slate-400 space-y-1">- <p>- <strong>Status:</strong>{" "}- <span- className={- task.result.validation.decision === "approve"- ? "text-emerald-600 dark:text-emerald-400 font-medium"- : task.result.validation.decision === "extended"- ? "text-amber-600 dark:text-amber-400 font-medium"- : "text-amber-600 dark:text-amber-400"- }- >- {task.result.validation.decision === "extended"- ? "Extended (beyond KB scope)"- : task.result.validation.decision}- </span>- </p>- <p>- <strong>Rounds:</strong> {task.result.rounds}- </p>- {task.result.validation.reasoning && (- <p className="mt-2 text-slate-500 dark:text-slate-400 italic">- {task.result.validation.reasoning}- </p>- )}- </div>- </div>- )}- </div>- )}-- {/* Waiting state */}- {!task.result && !task.error && task.status === "pending" && (- <div className="text-center py-10 text-slate-400 dark:text-slate-500 text-xs italic">- Waiting to start generation...- </div>- )}-- {/* In progress state */}- {!task.result &&- !task.error &&- (task.status === "generating" ||- task.status === "analyzing" ||- task.status === "validating") && (- <div className="flex flex-col items-center justify-center py-10">- <Loader2 className="w-8 h-8 text-indigo-500 dark:text-indigo-400 animate-spin mb-3" />- <p className="text-sm text-slate-500 dark:text-slate-400">- {task.status === "generating"- ? "Generating question..."- : task.status === "analyzing"- ? "Analyzing relevance..."- : "Validating question..."}- </p>- {task.round && (- <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">- Round {task.round}- </p>- )}- </div>- )}- </div>- </div>- );-};diff --git a/web/components/question/LogDrawer.tsx b/web/components/question/LogDrawer.tsxnew file mode 100644index 000000000..f72d40dc5--- /dev/null+++ b/web/components/question/LogDrawer.tsx@@ -0,0 +1,374 @@+import React from "react";+import {+ X,+ Activity,+ CheckCircle2,+ Loader2,+ Target,+ Search,+ Database,+ Sparkles,+ RefreshCw,+ FileText,+ Clock,+ Trash2,+} from "lucide-react";++interface LogEntry {+ type: string;+ content: string;+ timestamp?: number;+ level?: string;+}++interface SubFocus {+ id: string;+ focus: string;+ scenario_hint?: string;+}++interface LogDrawerProps {+ isOpen: boolean;+ onClose: () => void;+ logs: LogEntry[];+ stage: string | null;+ progress?: {+ current?: number;+ total?: number;+ status?: string;+ };+ subFocuses?: SubFocus[];+ mode?: "custom" | "mimic";+ topic?: string;+ difficulty?: string;+ questionType?: string;+ count?: number;+ onClearLogs?: () => void;+}++export const LogDrawer: React.FC<LogDrawerProps> = ({+ isOpen,+ onClose,+ logs,+ stage,+ progress,+ subFocuses = [],+ mode = "custom",+ topic,+ difficulty,+ questionType,+ count,+ onClearLogs,+}) => {+ const isMimicMode = mode === "mimic";+ const isIdle = stage === "idle" || stage === null;+ const isGenerating = stage === "generating" || stage === "validating";+ const isComplete = stage === "complete";++ // Custom mode steps+ const customModeSteps = [+ {+ id: "init",+ label: "Initializing",+ icon: Sparkles,+ active: stage === "planning" && !progress?.status,+ done:+ stage === "researching" ||+ progress?.status === "generating_queries" ||+ progress?.status === "retrieving" ||+ progress?.status === "creating_plan" ||+ progress?.status === "plan_ready" ||+ isGenerating ||+ isComplete,+ },+ {+ id: "query",+ label: "Generating Search Queries",+ icon: Search,+ active:+ progress?.status === "generating_queries" ||+ progress?.status === "splitting_queries",+ done:+ stage === "researching" ||+ progress?.status === "retrieving" ||+ progress?.status === "creating_plan" ||+ progress?.status === "plan_ready" ||+ isGenerating ||+ isComplete,+ },+ {+ id: "research",+ label: "Retrieving Knowledge",+ icon: Database,+ active: stage === "researching" || progress?.status === "retrieving",+ done:+ progress?.status === "creating_plan" ||+ progress?.status === "plan_ready" ||+ isGenerating ||+ isComplete,+ },+ {+ id: "plan",+ label: "Creating Question Plan",+ icon: Target,+ active:+ progress?.status === "creating_plan" ||+ progress?.status === "planning_focuses",+ done: progress?.status === "plan_ready" || isGenerating || isComplete,+ },+ ];++ // Mimic mode steps+ const mimicModeSteps = [+ {+ id: "upload",+ label: "Uploading PDF",+ icon: Sparkles,+ active: stage === "uploading",+ done:+ stage === "parsing" ||+ stage === "extracting" ||+ isGenerating ||+ isComplete,+ },+ {+ id: "parse",+ label: "Parsing PDF (MinerU)",+ icon: RefreshCw,+ active: stage === "parsing",+ done: stage === "extracting" || isGenerating || isComplete,+ },+ {+ id: "extract",+ label: "Extracting Questions",+ icon: Search,+ active: stage === "extracting",+ done: isGenerating || isComplete,+ },+ {+ id: "ready",+ label: "Ready to Generate",+ icon: Target,+ active: false,+ done: isGenerating || isComplete,+ },+ ];++ const planningSteps = isMimicMode ? mimicModeSteps : customModeSteps;++ return (+ <>+ {/* Overlay */}+ {isOpen && (+ <div+ className="fixed inset-0 bg-black/30 dark:bg-black/50 z-40 transition-opacity"+ onClick={onClose}+ />+ )}++ {/* Drawer - matches the app styling */}+ <div+ className={`+ fixed top-0 right-0 h-full w-full sm:w-[400px] bg-white dark:bg-slate-800+ border-l border-slate-200 dark:border-slate-700 z-50+ transform transition-transform duration-300 ease-out+ shadow-2xl+ ${isOpen ? "translate-x-0" : "translate-x-full"}+ flex flex-col+ `}+ >+ {/* Header */}+ <div className="flex items-center justify-between px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 shrink-0">+ <div className="flex items-center gap-3">+ <div+ className={`p-2 rounded-lg ${+ isComplete+ ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"+ : isIdle+ ? "bg-slate-100 dark:bg-slate-700 text-slate-400"+ : "bg-purple-100 dark:bg-purple-900/40 text-purple-600 dark:text-purple-400"+ }`}+ >+ {isComplete ? (+ <CheckCircle2 className="w-4 h-4" />+ ) : isIdle ? (+ <Clock className="w-4 h-4" />+ ) : (+ <Activity className="w-4 h-4" />+ )}+ </div>+ <div>+ <h2 className="font-semibold text-slate-700 dark:text-slate-200 text-sm">+ {isComplete+ ? "Generation Complete"+ : isIdle+ ? "Ready"+ : "Generating"}+ </h2>+ <p className="text-xs text-slate-500 dark:text-slate-400">+ {stage || "idle"}{progress?.current && progress?.total ? ` · ${progress.current}/${progress.total}` : ""}+ </p>+ </div>+ </div>+ <button+ onClick={onClose}+ className="p-2 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors"+ >+ <X className="w-4 h-4 text-slate-400" />+ </button>+ </div>++ {/* Content */}+ <div className="flex-1 overflow-y-auto bg-slate-50/30 dark:bg-slate-900/30">+ {/* Topic Info */}+ {!isMimicMode && topic && (+ <div className="px-4 py-4 border-b border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800">+ <p className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">+ Configuration+ </p>+ <p className="text-sm font-medium text-slate-700 dark:text-slate-200 mb-2">+ {topic}+ </p>+ <div className="flex flex-wrap gap-3 text-xs text-slate-500 dark:text-slate-400">+ <span>+ Difficulty: <strong className="capitalize text-slate-700 dark:text-slate-200">{difficulty}</strong>+ </span>+ <span>+ Type: <strong className="capitalize text-slate-700 dark:text-slate-200">{questionType}</strong>+ </span>+ <span>+ Count: <strong className="text-slate-700 dark:text-slate-200">{count}</strong>+ </span>+ </div>+ </div>+ )}++ {/* Mimic Mode Info */}+ {isMimicMode && (+ <div className="px-4 py-4 border-b border-slate-100 dark:border-slate-700 bg-amber-50 dark:bg-amber-900/20">+ <div className="flex items-center gap-2 mb-2">+ <FileText className="w-4 h-4 text-amber-600 dark:text-amber-400" />+ <p className="text-xs font-bold text-amber-700 dark:text-amber-400 uppercase tracking-wider">+ Mimic Exam Mode+ </p>+ </div>+ <p className="text-sm text-amber-800 dark:text-amber-300">+ Generating questions based on reference exam paper+ </p>+ </div>+ )}++ {/* Planning Steps Timeline */}+ {!isIdle && (+ <div className="px-4 py-4 border-b border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800">+ <p className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-4">+ Progress+ </p>+ <div className="space-y-3">+ {planningSteps.map((step) => (+ <div key={step.id} className="flex items-center gap-3">+ <div+ className={`flex-shrink-0 w-7 h-7 rounded-full flex items-center justify-center ${+ step.done+ ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"+ : step.active+ ? "bg-purple-100 dark:bg-purple-900/40 text-purple-600 dark:text-purple-400"+ : "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"+ }`}+ >+ {step.done ? (+ <CheckCircle2 className="w-3.5 h-3.5" />+ ) : step.active ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : (+ <step.icon className="w-3.5 h-3.5" />+ )}+ </div>+ <span+ className={`text-sm ${+ step.done+ ? "text-emerald-700 dark:text-emerald-300"+ : step.active+ ? "text-purple-700 dark:text-purple-300 font-medium"+ : "text-slate-400 dark:text-slate-500"+ }`}+ >+ {step.label}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Sub-Focuses */}+ {subFocuses.length > 0 && (+ <div className="px-4 py-4 border-b border-slate-100 dark:border-slate-700 bg-white dark:bg-slate-800">+ <p className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-3">+ Question Focuses ({subFocuses.length})+ </p>+ <div className="space-y-2 max-h-[200px] overflow-y-auto">+ {subFocuses.map((focus) => (+ <div+ key={focus.id}+ className="px-3 py-2 bg-slate-50 dark:bg-slate-700 text-slate-600 dark:text-slate-300 text-xs rounded-lg border border-slate-100 dark:border-slate-600"+ >+ <div className="flex items-center gap-2 font-semibold text-purple-600 dark:text-purple-400 mb-1">+ <Target className="w-3 h-3" />+ {focus.id}+ </div>+ <p className="text-slate-500 dark:text-slate-400 line-clamp-2">+ {focus.focus}+ </p>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Live Logs */}+ <div className="px-4 py-4 bg-white dark:bg-slate-800">+ <div className="flex items-center justify-between mb-3">+ <p className="text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider">+ Logs ({logs.length})+ </p>+ {logs.length > 0 && onClearLogs && (+ <button+ onClick={onClearLogs}+ className="flex items-center gap-1 text-xs text-slate-400 hover:text-red-500 dark:hover:text-red-400 px-2 py-1 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"+ title="Clear logs"+ >+ <Trash2 className="w-3 h-3" />+ Clear+ </button>+ )}+ </div>+ {logs.length === 0 ? (+ <div className="text-center py-8 text-slate-400 dark:text-slate-500">+ <Activity className="w-8 h-8 mx-auto mb-2 opacity-30" />+ <p className="text-xs">Waiting for logs...</p>+ </div>+ ) : (+ <div className="space-y-1.5 max-h-[300px] overflow-y-auto pr-1">+ {logs.slice(-50).map((log, idx) => (+ <div+ key={idx}+ className={`text-xs px-3 py-2 rounded-lg break-words ${+ log.type === "error"+ ? "bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 border border-red-100 dark:border-red-800"+ : log.type === "success"+ ? "bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 border border-emerald-100 dark:border-emerald-800"+ : "bg-slate-50 dark:bg-slate-700 text-slate-600 dark:text-slate-300 border border-slate-100 dark:border-slate-600"+ }`}+ >+ {log.content}+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ </div>+ </>+ );+};diff --git a/web/components/question/QuestionDashboard.tsx b/web/components/question/QuestionDashboard.tsxdeleted file mode 100644index 44c2f2373..000000000--- a/web/components/question/QuestionDashboard.tsx+++ /dev/null@@ -1,819 +0,0 @@-import React, { useState, useEffect } from "react";-import {- QuestionState,- QuestionTokenStats,- QuestionTask,-} from "../../types/question";-import { QuestionTaskGrid } from "./QuestionTaskGrid";-import { ActiveQuestionDetail } from "./ActiveQuestionDetail";-import {- GitBranch,- Zap,- CheckCircle2,- Loader2,- LayoutDashboard,- Activity,- Clock,- Search,- FileQuestion,- Target,- AlertCircle,- DollarSign,- Cpu,- ChevronRight,- Database,- RefreshCw,- Sparkles,-} from "lucide-react";--type ProcessTab = "planning" | "generating";--// Progress info from GlobalContext-interface GlobalContextProgress {- stage:- | "planning"- | "researching"- | "generating"- | "validating"- | "complete"- // Mimic mode stages- | "uploading"- | "parsing"- | "extracting"- | null;- progress: {- current?: number;- total?: number;- round?: number;- max_rounds?: number;- status?: string;- };- subFocuses?: Array<{ id: string; focus: string; scenario_hint?: string }>;- activeQuestions?: string[];- completedQuestions?: number;- failedQuestions?: number;- extendedQuestions?: number;-}--// Logs from GlobalContext-interface LogEntry {- type: string;- content: string;- timestamp?: number;- level?: string;-}--interface QuestionDashboardProps {- // Support both QuestionState (from reducer) and GlobalContext data- state?: QuestionState;- // GlobalContext data (alternative to state)- globalProgress?: GlobalContextProgress;- globalLogs?: LogEntry[];- globalResults?: any[];- globalTopic?: string;- globalDifficulty?: string;- globalType?: string;- globalCount?: number;- globalStep?: "config" | "generating" | "result";- globalMode?: "custom" | "mimic"; // Mode for different progress display- // Common props- selectedTaskId: string | null;- onTaskSelect: (taskId: string) => void;- tokenStats?: QuestionTokenStats;-}--export const QuestionDashboard: React.FC<QuestionDashboardProps> = ({- state,- globalProgress,- globalLogs = [],- globalResults = [],- globalTopic = "",- globalDifficulty = "",- globalType = "",- globalCount = 0,- globalStep = "config",- globalMode = "custom",- selectedTaskId,- onTaskSelect,- tokenStats,-}) => {- // Determine if using QuestionState or GlobalContext data- const useGlobalContext = !state || state.global.stage === "idle";-- // Extract data from either source- const stage = useGlobalContext- ? globalProgress?.stage ||- (globalStep === "generating"- ? "generating"- : globalStep === "result"- ? "complete"- : "idle")- : state!.global.stage;-- const isIdle = stage === "idle" || stage === null;- const isCompleted = stage === "complete" || globalStep === "result";- const isPlanning = stage === "planning";- const isResearching = stage === "researching";- const isGenerating = stage === "generating" || stage === "validating";-- // Mimic mode stages- const isUploading = stage === "uploading";- const isParsing = stage === "parsing";- const isExtracting = stage === "extracting";- const isMimicMode = globalMode === "mimic";- const isMimicPlanning = isUploading || isParsing || isExtracting;-- const completedQuestions = useGlobalContext- ? globalProgress?.completedQuestions || globalResults.length- : state!.global.completedQuestions;-- const totalQuestions = useGlobalContext- ? globalProgress?.progress?.total || globalCount- : state!.global.totalQuestions;-- const failedQuestions = useGlobalContext- ? globalProgress?.failedQuestions || 0- : state!.global.failedQuestions;-- const extendedCount = useGlobalContext- ? globalProgress?.extendedQuestions ||- globalResults.filter((r: any) => r.extended).length- : state!.global.extendedQuestions || 0;-- const subFocuses = useGlobalContext- ? globalProgress?.subFocuses || []- : state!.subFocuses;-- const logs = useGlobalContext ? globalLogs : state!.logs;- const results = useGlobalContext ? globalResults : state!.results;-- // Build tasks from results when using GlobalContext- const tasks = useGlobalContext- ? buildTasksFromResults(globalResults, globalProgress, globalMode)- : state!.tasks;-- const activeTaskIds = useGlobalContext- ? globalProgress?.activeQuestions || []- : state!.activeTaskIds;-- const [activeProcessTab, setActiveProcessTab] =- useState<ProcessTab>("planning");-- const steps: { id: ProcessTab; label: string; icon: React.ElementType }[] = [- { id: "planning", label: "Planning", icon: GitBranch },- { id: "generating", label: "Generating", icon: Zap },- ];-- const stageOrder: Record<string, number> = {- idle: -1,- planning: 0,- researching: 0,- // Mimic mode stages map to planning- uploading: 0,- parsing: 0,- extracting: 0,- generating: 1,- validating: 1,- complete: 2,- };-- const currentStageIndex = stageOrder[stage || "idle"] ?? -1;-- // Check if a tab has content- const isTabAvailable = (tabId: ProcessTab): boolean => {- const tabIndex = steps.findIndex((s) => s.id === tabId);- return currentStageIndex >= tabIndex;- };-- // Check if a tab is currently active- const isTabCurrentlyActive = (tabId: ProcessTab): boolean => {- if (tabId === "planning") {- return isPlanning || isResearching || isMimicPlanning;- }- return isGenerating;- };-- // Auto-switch to current stage tab when stage changes- useEffect(() => {- if (isPlanning || isResearching || isMimicPlanning) {- setActiveProcessTab("planning");- } else if (isGenerating) {- setActiveProcessTab("generating");- }- }, [isPlanning, isResearching, isGenerating, isMimicPlanning]);-- // Clickable Step Tabs- const StepTabs = () => (- <div className="flex items-center gap-1 bg-slate-100/80 dark:bg-slate-700/80 backdrop-blur-sm p-1 rounded-xl border border-slate-200/50 dark:border-slate-600/50 shadow-sm">- {steps.map((step, idx) => {- const available = isTabAvailable(step.id);- const isCurrentStage = isTabCurrentlyActive(step.id);- const isSelected = activeProcessTab === step.id;- const isPassed = currentStageIndex > idx || isCompleted;-- return (- <button- key={step.id}- onClick={() => available && setActiveProcessTab(step.id)}- disabled={!available}- className={`- flex items-center gap-2 px-4 py-2 rounded-lg transition-all relative- ${- isSelected- ? "bg-white dark:bg-slate-600 shadow-sm border border-slate-200 dark:border-slate-500 text-indigo-700 dark:text-indigo-300"- : available- ? "hover:bg-white/50 dark:hover:bg-slate-600/50 text-slate-600 dark:text-slate-300"- : "text-slate-300 dark:text-slate-500 cursor-not-allowed"- }- `}- >- {/* Status indicator */}- {isPassed ? (- <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />- ) : isCurrentStage ? (- <Loader2 className="w-4 h-4 text-indigo-500 dark:text-indigo-400 animate-spin" />- ) : available ? (- <step.icon className="w-4 h-4" />- ) : (- <Clock className="w-4 h-4 text-slate-300 dark:text-slate-500" />- )}- <span className="text-sm font-medium">{step.label}</span>-- {/* Active indicator dot */}- {isCurrentStage && !isCompleted && (- <span className="absolute -top-1 -right-1 flex h-2.5 w-2.5">- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>- <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-indigo-500"></span>- </span>- )}- </button>- );- })}- </div>- );-- // Planning Content with Timeline- const PlanningContent = () => {- const progressStatus = globalProgress?.progress?.status;-- // Custom mode steps- const customModeSteps = [- {- id: "init",- label: "Initializing",- icon: Sparkles,- active: isPlanning && !progressStatus,- done:- isResearching ||- progressStatus === "generating_queries" ||- progressStatus === "retrieving" ||- progressStatus === "creating_plan" ||- progressStatus === "plan_ready" ||- isGenerating ||- isCompleted,- },- {- id: "query",- label: "Generating Search Queries",- icon: Search,- active:- progressStatus === "generating_queries" ||- progressStatus === "splitting_queries",- done:- isResearching ||- progressStatus === "retrieving" ||- progressStatus === "creating_plan" ||- progressStatus === "plan_ready" ||- isGenerating ||- isCompleted,- },- {- id: "research",- label: "Retrieving Background Knowledge",- icon: Database,- active: isResearching || progressStatus === "retrieving",- done:- progressStatus === "creating_plan" ||- progressStatus === "plan_ready" ||- progressStatus === "completed" ||- isGenerating ||- isCompleted,- },- {- id: "plan",- label: "Creating Question Plan",- icon: Target,- active:- progressStatus === "creating_plan" ||- progressStatus === "planning_focuses",- done:- progressStatus === "plan_ready" ||- subFocuses.length > 0 ||- isGenerating ||- isCompleted,- },- ];-- // Mimic mode steps - use stage directly for clearer logic- const mimicModeSteps = [- {- id: "upload",- label: "Uploading PDF",- icon: Sparkles,- active: isUploading,- done: isParsing || isExtracting || isGenerating || isCompleted,- },- {- id: "parse",- label: "Parsing PDF (MinerU)",- icon: RefreshCw,- active: isParsing,- done: isExtracting || isGenerating || isCompleted,- },- {- id: "extract",- label: "Extracting Reference Questions",- icon: Search,- active: isExtracting,- done: isGenerating || isCompleted,- },- {- id: "ready",- label: "Ready to Generate",- icon: Target,- active: false,- done: isGenerating || isCompleted,- },- ];-- const planningSteps = isMimicMode ? mimicModeSteps : customModeSteps;-- return (- <div className="flex-1 flex gap-6 overflow-hidden">- {/* Left: Timeline */}- <div className="flex-1 bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm p-6 overflow-y-auto">- <h3 className="font-bold text-slate-700 dark:text-slate-200 mb-6 flex items-center gap-2">- <GitBranch className="w-5 h-5 text-indigo-500 dark:text-indigo-400" />- Planning Progress- </h3>-- {/* Topic Info - Custom Mode */}- {!isMimicMode && globalTopic && (- <div className="mb-6 p-4 bg-indigo-50 dark:bg-indigo-900/30 rounded-lg border border-indigo-100 dark:border-indigo-800">- <div className="flex items-center gap-3 mb-2">- <div className="text-xs font-bold text-indigo-500 dark:text-indigo-400 uppercase tracking-wider">- Topic- </div>- </div>- <p className="text-sm text-indigo-900 dark:text-indigo-200 font-medium">- {globalTopic}- </p>- <div className="flex gap-4 mt-2 text-xs text-indigo-600 dark:text-indigo-400">- <span>- Difficulty:{" "}- <strong className="capitalize">{globalDifficulty}</strong>- </span>- <span>- Type: <strong className="capitalize">{globalType}</strong>- </span>- <span>- Count: <strong>{globalCount}</strong>- </span>- </div>- </div>- )}-- {/* Mode Info - Mimic Mode */}- {isMimicMode && (- <div className="mb-6 p-4 bg-amber-50 dark:bg-amber-900/30 rounded-lg border border-amber-100 dark:border-amber-800">- <div className="flex items-center gap-3 mb-2">- <div className="text-xs font-bold text-amber-600 dark:text-amber-400 uppercase tracking-wider">- Mimic Exam Mode- </div>- </div>- <p className="text-sm text-amber-900 dark:text-amber-200 font-medium">- Generating questions based on reference exam paper- </p>- {totalQuestions > 0 && (- <div className="flex gap-4 mt-2 text-xs text-amber-700 dark:text-amber-400">- <span>- Reference Questions: <strong>{totalQuestions}</strong>- </span>- </div>- )}- </div>- )}-- {/* Timeline Steps */}- <div className="space-y-4">- {planningSteps.map((step, idx) => (- <div key={step.id} className="flex items-start gap-3">- <div- className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${- step.done- ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"- : step.active- ? "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400"- : "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"- }`}- >- {step.done ? (- <CheckCircle2 className="w-4 h-4" />- ) : step.active ? (- <Loader2 className="w-4 h-4 animate-spin" />- ) : (- <step.icon className="w-4 h-4" />- )}- </div>- <div className="flex-1 pt-1">- <p- className={`text-sm font-medium ${- step.done- ? "text-emerald-700 dark:text-emerald-300"- : step.active- ? "text-indigo-700 dark:text-indigo-300"- : "text-slate-400 dark:text-slate-500"- }`}- >- {step.label}- </p>- {step.active && (- <p className="text-xs text-slate-500 dark:text-slate-400 mt-1 animate-pulse">- Processing...- </p>- )}- </div>- </div>- ))}- </div>-- {/* Sub-Focuses Preview */}- {subFocuses.length > 0 && (- <div className="mt-6 pt-4 border-t border-slate-100 dark:border-slate-700">- <p className="text-xs font-bold text-slate-400 dark:text-slate-500 uppercase tracking-wider mb-3">- Question Focuses ({subFocuses.length})- </p>- <div className="space-y-2 max-h-48 overflow-y-auto">- {subFocuses.map((focus: any) => (- <div- key={focus.id}- className="px-3 py-2 bg-slate-50 dark:bg-slate-700 text-slate-700 dark:text-slate-300 text-xs rounded-lg border border-slate-100 dark:border-slate-600"- >- <div className="flex items-center gap-2 font-semibold text-indigo-600 dark:text-indigo-400">- <Target className="w-3 h-3" />- {focus.id}- </div>- <p className="mt-1 text-slate-600 dark:text-slate-400">- {focus.focus}- </p>- </div>- ))}- </div>- </div>- )}- </div>-- {/* Right: Live Logs */}- <div className="w-[350px] bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm flex flex-col">- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 flex items-center justify-between">- <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">- <Activity className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />- Live Logs- </h3>- <span className="text-xs text-slate-400 dark:text-slate-500">- {logs.length} entries- </span>- </div>- <div className="flex-1 overflow-y-auto p-3 space-y-2">- {logs.length === 0 ? (- <div className="text-center text-slate-400 dark:text-slate-500 py-8">- <Activity className="w-8 h-8 mx-auto mb-2 opacity-30" />- <p className="text-xs">Waiting for logs...</p>- </div>- ) : (- logs.slice(-50).map((log: any, idx: number) => (- <div- key={idx}- className={`text-xs px-2 py-1.5 rounded ${- log.type === "error"- ? "bg-red-50 dark:bg-red-900/40 text-red-700 dark:text-red-300"- : log.type === "success"- ? "bg-emerald-50 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300"- : "bg-slate-50 dark:bg-slate-700 text-slate-600 dark:text-slate-400"- }`}- >- {log.content}- </div>- ))- )}- </div>- </div>- </div>- );- };-- // Generating Content with Question Progress- const GeneratingContent = () => {- const hasContent = Object.keys(tasks).length > 0 || results.length > 0;-- if (!hasContent) {- return (- <div className="flex-1 flex items-center justify-center">- <div className="text-center">- <Loader2 className="w-12 h-12 mx-auto mb-3 text-indigo-500 dark:text-indigo-400 animate-spin" />- <p className="text-slate-600 dark:text-slate-300 font-medium">- Initializing question generation...- </p>- <p className="text-slate-400 dark:text-slate-500 text-sm mt-1">- Preparing tasks...- </p>- </div>- </div>- );- }-- return (- <div className="flex-1 min-h-0 flex gap-6">- {/* Left: Task Grid */}- <div className="flex-[3] min-w-0 flex flex-col gap-4">- <div className="flex items-center justify-between">- <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">- <FileQuestion className="w-4 h-4 text-amber-500 dark:text-amber-400" />- Question Tasks- {isCompleted && (- <span className="text-xs font-normal text-slate-400 dark:text-slate-500 ml-2">- (Completed)- </span>- )}- </h3>- <div className="flex items-center gap-3 text-xs text-slate-500 dark:text-slate-400">- {isGenerating && activeTaskIds.length > 0 && (- <span className="text-indigo-600 dark:text-indigo-400 font-medium">- {activeTaskIds.length} active- </span>- )}- <span>- {completedQuestions} / {totalQuestions} completed- </span>- {extendedCount > 0 && (- <span className="text-amber-600 dark:text-amber-400">- {extendedCount} extended- </span>- )}- {failedQuestions > 0 && (- <span className="text-red-500 dark:text-red-400">- {failedQuestions} failed- </span>- )}- </div>- </div>- <div className="flex-1 overflow-y-auto pr-2">- <QuestionTaskGrid- tasks={tasks}- activeTaskIds={isGenerating ? activeTaskIds : []}- selectedTaskId={selectedTaskId}- onTaskSelect={onTaskSelect}- mode={globalMode}- />- </div>- </div>-- {/* Right: Active Details */}- <div className="flex-[2] min-w-[400px] flex flex-col gap-4">- <h3 className="font-bold text-slate-700 dark:text-slate-200 flex items-center gap-2">- <Activity className="w-4 h-4 text-indigo-500 dark:text-indigo-400" />- {isGenerating ? "Active Question" : "Question Details"}- </h3>- <div className="flex-1 min-h-0">- <ActiveQuestionDetail- task={selectedTaskId ? tasks[selectedTaskId] : null}- mode={globalMode}- />- </div>- </div>- </div>- );- };-- return (- <div className="flex flex-col h-full bg-slate-50/50 dark:bg-slate-900/50">- {/* Top Bar: Progress & Global Status */}- <div className="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 px-6 py-4 flex items-center justify-between shadow-sm shrink-0 z-20 relative">- <div className="flex items-center gap-4">- <div- className={`p-2 rounded-lg ${- isIdle- ? "bg-slate-100 dark:bg-slate-700 text-slate-400 dark:text-slate-500"- : isCompleted- ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"- : "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-400"- }`}- >- {isCompleted ? (- <CheckCircle2 className="w-5 h-5" />- ) : isIdle ? (- <FileQuestion className="w-5 h-5" />- ) : (- <LayoutDashboard className="w-5 h-5" />- )}- </div>- <div>- <h2 className="text-lg font-bold text-slate-800 dark:text-slate-100">- {isIdle- ? "Ready to Generate"- : isCompleted- ? "Generation Complete"- : "Question Generation"}- </h2>- <div className="flex items-center gap-2 text-xs text-slate-500 dark:text-slate-400 mt-0.5">- <span- className={`uppercase font-bold tracking-wider ${isCompleted ? "text-emerald-600 dark:text-emerald-400" : ""}`}- >- {stage || "idle"}- </span>- {totalQuestions > 0 && (- <>- <span>•</span>- <span>- {completedQuestions} / {totalQuestions} questions- </span>- </>- )}- {extendedCount > 0 && (- <>- <span>•</span>- <span className="text-amber-600 dark:text-amber-400 flex items-center gap-1">- <Zap className="w-3 h-3" />- {extendedCount} extended- </span>- </>- )}- {failedQuestions > 0 && (- <>- <span>•</span>- <span className="text-red-500 dark:text-red-400 flex items-center gap-1">- <AlertCircle className="w-3 h-3" />- {failedQuestions} failed- </span>- </>- )}- </div>- </div>- </div>-- {/* Performance & Cost Stats */}- <div className="flex items-center gap-4">- {tokenStats && tokenStats.calls > 0 && (- <div className="flex items-center gap-4 px-4 py-2 bg-slate-50 dark:bg-slate-700 rounded-lg border border-slate-200 dark:border-slate-600">- <div className="flex items-center gap-2">- <Cpu className="w-4 h-4 text-slate-400 dark:text-slate-500" />- <span className="text-xs text-slate-500 dark:text-slate-400">- <span className="font-medium text-slate-700 dark:text-slate-300">- {tokenStats.model}- </span>- </span>- </div>- <div className="h-4 w-px bg-slate-200 dark:bg-slate-600" />- <div className="text-xs text-slate-500 dark:text-slate-400">- Calls:{" "}- <span className="font-medium text-slate-700 dark:text-slate-300">- {tokenStats.calls}- </span>- </div>- <div className="h-4 w-px bg-slate-200 dark:bg-slate-600" />- <div className="text-xs text-slate-500 dark:text-slate-400">- Tokens:{" "}- <span className="font-medium text-slate-700 dark:text-slate-300">- {tokenStats.tokens.toLocaleString()}- </span>- </div>- <div className="h-4 w-px bg-slate-200 dark:bg-slate-600" />- <div className="flex items-center gap-1">- <DollarSign className="w-3 h-3 text-amber-500" />- <span className="text-xs font-semibold text-amber-600 dark:text-amber-400">- ${tokenStats.cost.toFixed(4)}- </span>- </div>- </div>- )}-- {/* Results Summary (when complete) */}- {isCompleted && results.length > 0 && (- <div className="flex items-center gap-2 bg-emerald-50 dark:bg-emerald-900/30 px-4 py-2 rounded-lg border border-emerald-100 dark:border-emerald-800">- <CheckCircle2 className="w-4 h-4 text-emerald-500 dark:text-emerald-400" />- <span className="text-sm font-medium text-emerald-700 dark:text-emerald-300">- {results.length} question{results.length > 1 ? "s" : ""}{" "}- generated- </span>- </div>- )}- </div>- </div>-- {/* Main Content Area */}- <div className="flex-1 flex flex-col min-h-0 overflow-hidden">- {/* Idle State */}- {isIdle ? (- <div className="flex-1 flex items-center justify-center p-6">- <div className="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 shadow-sm p-8 flex flex-col items-center justify-center text-center max-w-lg w-full">- <div className="w-16 h-16 bg-slate-100 dark:bg-slate-700 rounded-full flex items-center justify-center mb-4">- <FileQuestion className="w-8 h-8 text-slate-400 dark:text-slate-500" />- </div>- <h3 className="text-lg font-semibold text-slate-800 dark:text-slate-100 mb-2">- Ready to Generate Questions- </h3>- <p className="text-slate-500 dark:text-slate-400 text-sm">- Configure your requirements and click Generate to start.- </p>- </div>- </div>- ) : (- <>- {/* Step Tabs */}- <div className="px-6 pt-4 pb-2 flex justify-center shrink-0">- <StepTabs />- </div>-- {/* Tab Content */}- <div className="flex-1 overflow-hidden p-6 flex flex-col">- {activeProcessTab === "planning" && <PlanningContent />}- {activeProcessTab === "generating" && <GeneratingContent />}- </div>- </>- )}- </div>- </div>- );-};--// Helper function to build tasks from results-function buildTasksFromResults(- results: any[],- progress?: GlobalContextProgress,- mode?: "custom" | "mimic",-): Record<string, QuestionTask> {- const tasks: Record<string, QuestionTask> = {};- const isMimicMode = mode === "mimic";-- // First, create tasks from subFocuses if available (custom mode)- if (progress?.subFocuses && !isMimicMode) {- progress.subFocuses.forEach((focus, idx) => {- const existingResult = results.find(- (r: any) =>- r.question?.knowledge_point?.includes(focus.focus.slice(0, 20)) ||- idx < results.length,- );-- tasks[focus.id] = {- id: focus.id,- focus: focus.focus,- scenarioHint: focus.scenario_hint,- status: idx < results.length ? "done" : "pending",- result:- idx < results.length- ? {- success: true,- question_id: focus.id,- question: results[idx]?.question,- validation: results[idx]?.validation,- rounds: results[idx]?.rounds || 1,- extended: results[idx]?.extended,- }- : undefined,- extended: results[idx]?.extended,- lastUpdate: Date.now(),- };- });- }-- // If no subFocuses or mimic mode, create tasks from results directly- if (Object.keys(tasks).length === 0 && results.length > 0) {- results.forEach((result: any, idx: number) => {- const id = `q_${idx + 1}`;- // For mimic mode, use reference_question as focus (full original question)- // For custom mode fallback, use generated question preview- const focus = isMimicMode- ? result.reference_question || `Reference Question ${idx + 1}`- : result.question?.question?.slice(0, 50) + "..." ||- `Question ${idx + 1}`;-- tasks[id] = {- id,- focus,- status: "done",- result: {- success: true,- question_id: id,- question: result.question,- validation: result.validation,- rounds: result.rounds || 1,- extended: result.extended,- },- extended: result.extended,- lastUpdate: Date.now(),- };- });- }-- return tasks;-}diff --git a/web/components/question/QuestionTaskGrid.tsx b/web/components/question/QuestionTaskGrid.tsxdeleted file mode 100644index 3bf69bd71..000000000--- a/web/components/question/QuestionTaskGrid.tsx+++ /dev/null@@ -1,232 +0,0 @@-import React from "react";-import { QuestionTask } from "../../types/question";-import {- CheckCircle2,- Loader2,- Clock,- AlertCircle,- Activity,- FileQuestion,- Search,- Zap,- BookOpen,-} from "lucide-react";-import ReactMarkdown from "react-markdown";-import remarkMath from "remark-math";-import rehypeKatex from "rehype-katex";-import { processLatexContent } from "@/lib/latex";--interface QuestionTaskGridProps {- tasks: Record<string, QuestionTask>;- activeTaskIds: string[];- selectedTaskId: string | null;- onTaskSelect: (taskId: string) => void;- mode?: "custom" | "mimic";-}--const getStatusIcon = (status: QuestionTask["status"], extended?: boolean) => {- if (status === "done" && extended) {- return <Zap className="w-4 h-4 text-amber-500" />;- }- switch (status) {- case "done":- return <CheckCircle2 className="w-4 h-4 text-emerald-500" />;- case "generating":- return <Loader2 className="w-4 h-4 text-indigo-500 animate-spin" />;- case "analyzing":- return <Search className="w-4 h-4 text-purple-500 animate-pulse" />;- case "validating":- return <Search className="w-4 h-4 text-amber-500 animate-pulse" />;- case "error":- return <AlertCircle className="w-4 h-4 text-red-500" />;- default:- return <Clock className="w-4 h-4 text-slate-400" />;- }-};--const getStatusColor = (status: QuestionTask["status"], extended?: boolean) => {- if (status === "done" && extended) {- return "bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300";- }- switch (status) {- case "done":- return "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300";- case "generating":- return "bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300";- case "analyzing":- return "bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300";- case "validating":- return "bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300";- case "error":- return "bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300";- default:- return "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400";- }-};--export const QuestionTaskGrid: React.FC<QuestionTaskGridProps> = ({- tasks,- activeTaskIds,- selectedTaskId,- onTaskSelect,- mode = "custom",-}) => {- const isMimicMode = mode === "mimic";- // Sort tasks: Active first, then by status- const sortedTasks = Object.values(tasks).sort((a, b) => {- const score = (task: QuestionTask) => {- if (activeTaskIds.includes(task.id)) return 4;- if (- task.status === "generating" ||- task.status === "analyzing" ||- task.status === "validating"- )- return 3;- if (task.status === "pending") return 2;- return 1;- };- return score(b) - score(a);- });-- if (sortedTasks.length === 0) {- return (- <div className="flex flex-col items-center justify-center p-8 text-slate-400 dark:text-slate-500 border-2 border-dashed border-slate-200 dark:border-slate-700 rounded-xl">- <Activity className="w-8 h-8 mb-2 opacity-50" />- <p className="text-sm">No questions initialized yet</p>- </div>- );- }-- return (- <div className="grid grid-cols-1 xl:grid-cols-2 gap-4">- {sortedTasks.map((task) => {- const isActive = activeTaskIds.includes(task.id);- const isSelected = selectedTaskId === task.id;-- return (- <div- key={task.id}- onClick={() => onTaskSelect(task.id)}- className={`- relative p-4 rounded-xl border cursor-pointer transition-all duration-200- hover:shadow-md flex flex-col gap-3- ${- isSelected- ? "bg-indigo-50/50 dark:bg-indigo-900/30 border-indigo-500 ring-1 ring-indigo-500"- : "bg-white dark:bg-slate-800 border-slate-200 dark:border-slate-700 hover:border-indigo-300 dark:hover:border-indigo-500"- }- ${isActive ? "shadow-sm" : "opacity-90"}- `}- >- {/* Active Indicator Pulse */}- {isActive && (- <div className="absolute top-4 right-4 flex h-2 w-2">- <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>- <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>- </div>- )}-- <div className="flex items-start gap-3">- <div- className={`p-2 rounded-lg shrink-0 ${- task.status === "done" && task.extended- ? "bg-amber-50 dark:bg-amber-900/30"- : task.status === "done"- ? "bg-emerald-50 dark:bg-emerald-900/30"- : task.status === "error"- ? "bg-red-50 dark:bg-red-900/30"- : isActive- ? "bg-indigo-50 dark:bg-indigo-900/30"- : "bg-slate-100 dark:bg-slate-700"- }`}- >- {getStatusIcon(task.status, task.extended)}- </div>- <div className="flex-1 min-w-0">- <div className="flex items-start justify-between gap-2">- <h4- className="text-sm font-semibold text-slate-800 dark:text-slate-200 line-clamp-1 pr-4"- title={task.id}- >- {task.id}- </h4>- </div>- <div className="flex items-center gap-2 mt-1.5">- <span- className={`text-[10px] px-2 py-0.5 rounded-full font-medium uppercase tracking-wide ${getStatusColor(task.status, task.extended)}`}- >- {task.extended ? "extended" : task.status}- </span>- {task.round && task.maxRounds && (- <span className="text-[10px] text-slate-400 dark:text-slate-500 font-medium">- ROUND {task.round} / {task.maxRounds}- </span>- )}- </div>- </div>- </div>-- {/* Focus / Origin Question */}- <div- className={`bg-slate-50 dark:bg-slate-700 rounded-lg p-2.5 border border-slate-100 dark:border-slate-600 ${isMimicMode ? "min-h-[80px]" : "min-h-[48px]"}`}- >- {isMimicMode ? (- <div className="text-xs text-slate-600 dark:text-slate-400">- <div className="flex items-center gap-1 mb-2">- <BookOpen className="w-3 h-3 text-amber-500 dark:text-amber-400" />- <span className="font-semibold text-amber-600 dark:text-amber-400">- Origin Question:- </span>- </div>- <div className="prose prose-xs dark:prose-invert max-w-none leading-relaxed text-slate-700 dark:text-slate-300">- {task.focus ? (- <ReactMarkdown- remarkPlugins={[remarkMath]}- rehypePlugins={[rehypeKatex]}- >- {processLatexContent(task.focus)}- </ReactMarkdown>- ) : (- <span className="text-slate-400 dark:text-slate-500 italic">- Waiting to start...- </span>- )}- </div>- </div>- ) : (- <p className="text-xs text-slate-600 dark:text-slate-400 line-clamp-2 leading-relaxed">- <span className="font-medium text-slate-400 dark:text-slate-500 mr-1">- Focus:- </span>- {task.focus || "Waiting to start..."}- </p>- )}- </div>-- {/* Result preview or error */}- {task.result?.question && (- <div- className={`flex items-center gap-1.5 text-xs ${task.extended ? "text-amber-600 dark:text-amber-400" : "text-emerald-600 dark:text-emerald-400"}`}- >- {task.extended ? (- <Zap className="w-3 h-3" />- ) : (- <FileQuestion className="w-3 h-3" />- )}- <span className="line-clamp-1">- {task.result.question.question?.slice(0, 50)}...- </span>- </div>- )}- {task.error && (- <div className="flex items-center gap-1.5 text-xs text-red-600 dark:text-red-400">- <AlertCircle className="w-3 h-3" />- <span className="line-clamp-1">{task.error}</span>- </div>- )}- </div>- );- })}- </div>- );-};diff --git a/web/components/question/index.ts b/web/components/question/index.tsindex abcf1103f..f341feab1 100644--- a/web/components/question/index.ts+++ b/web/components/question/index.ts@@ -1,3 +1,2 @@-export { QuestionDashboard } from "./QuestionDashboard";-export { QuestionTaskGrid } from "./QuestionTaskGrid";-export { ActiveQuestionDetail } from "./ActiveQuestionDetail";+// Question Generator Components+export { LogDrawer } from "./LogDrawer";diff --git a/web/context/GlobalContext.tsx b/web/context/GlobalContext.tsxindex 503c73c0c..b4553161c 100644--- a/web/context/GlobalContext.tsx+++ b/web/context/GlobalContext.tsx@@ -15,6 +15,9 @@ import {type Theme,} from "@/lib/theme";+// Language storage key+const LANGUAGE_STORAGE_KEY = "deeptutor-language";+// --- Types ---interface LogEntry {type: string;@@ -232,6 +235,12 @@ interface ChatState {currentStage: string | null;}+// Sidebar Navigation Order Type+export interface SidebarNavOrder {+ start: string[]; // Array of href paths for START group+ learnResearch: string[]; // Array of href paths for LEARN & RESEARCH group+}+interface GlobalContextType {// SolversolverState: SolverState;@@ -283,6 +292,8 @@ interface GlobalContextType {// UI SettingsuiSettings: { theme: "light" | "dark"; language: "en" | "zh" };refreshSettings: () => Promise<void>;+ updateTheme: (theme: "light" | "dark") => Promise<void>;+ updateLanguage: (language: "en" | "zh") => Promise<void>;// SidebarsidebarWidth: number;@@ -290,6 +301,12 @@ interface GlobalContextType {sidebarCollapsed: boolean;setSidebarCollapsed: (collapsed: boolean) => void;toggleSidebar: () => void;++ // Sidebar Customization+ sidebarDescription: string;+ setSidebarDescription: (description: string) => Promise<void>;+ sidebarNavOrder: SidebarNavOrder;+ setSidebarNavOrder: (order: SidebarNavOrder) => Promise<void>;}const GlobalContext = createContext<GlobalContextType | undefined>(undefined);@@ -304,40 +321,99 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {const [isInitialized, setIsInitialized] = useState(false);const refreshSettings = async () => {+ // Try to load from backend API first, fallback to localStoragetry {const res = await fetch(apiUrl("/api/v1/settings"));if (res.ok) {const data = await res.json();- if (data.ui) {- // localStorage takes priority over backend- const storedTheme = getStoredTheme();- const themeToUse = storedTheme || data.ui.theme;-- setUiSettings({- theme: themeToUse,- language: data.ui.language,- });- // Apply and persist theme- setTheme(themeToUse);+ const serverTheme = data.ui?.theme || "light";+ const serverLanguage = data.ui?.language || "en";+ setUiSettings({+ theme: serverTheme,+ language: serverLanguage,+ });+ setTheme(serverTheme);+ // Sync to localStorage as cache+ if (typeof window !== "undefined") {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, serverLanguage);}+ return;}} catch (e) {- // Fall back to localStorage theme on error- const stored = getStoredTheme();- if (stored) {- setUiSettings((prev) => ({ ...prev, theme: stored }));- }+ console.warn(+ "Failed to load settings from server, using localStorage:",+ e,+ );+ }++ // Fallback to localStorage+ const storedTheme = getStoredTheme();+ const storedLanguage =+ typeof window !== "undefined"+ ? (localStorage.getItem(LANGUAGE_STORAGE_KEY) as "en" | "zh") || "en"+ : "en";++ const themeToUse = storedTheme || "light";+ setUiSettings({+ theme: themeToUse,+ language: storedLanguage,+ });+ setTheme(themeToUse);+ };++ const updateTheme = async (newTheme: "light" | "dark") => {+ // Update UI immediately+ setTheme(newTheme);+ setUiSettings((prev) => ({ ...prev, theme: newTheme }));++ // Persist to backend+ try {+ await fetch(apiUrl("/api/v1/settings/theme"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ theme: newTheme }),+ });+ } catch (e) {+ console.warn("Failed to save theme to server:", e);+ }+ };++ const updateLanguage = async (newLanguage: "en" | "zh") => {+ // Update UI immediately+ setUiSettings((prev) => ({ ...prev, language: newLanguage }));+ if (typeof window !== "undefined") {+ localStorage.setItem(LANGUAGE_STORAGE_KEY, newLanguage);+ }++ // Persist to backend+ try {+ await fetch(apiUrl("/api/v1/settings/language"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ language: newLanguage }),+ });+ } catch (e) {+ console.warn("Failed to save language to server:", e);}};useEffect(() => {- // Initialize theme immediately on first render+ // Initialize settings on first renderif (!isInitialized) {+ // First apply localStorage theme immediately to avoid flashconst initialTheme = initializeTheme();- setUiSettings((prev) => ({ ...prev, theme: initialTheme }));+ const storedLanguage =+ typeof window !== "undefined"+ ? (localStorage.getItem(LANGUAGE_STORAGE_KEY) as "en" | "zh") || "en"+ : "en";++ setUiSettings({+ theme: initialTheme,+ language: storedLanguage,+ });setIsInitialized(true);- // Then fetch from backend and sync+ // Then async load from server (which may override)refreshSettings();}}, [isInitialized]);@@ -398,6 +474,74 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {setSidebarCollapsed(!sidebarCollapsed);};+ // --- Sidebar Customization State ---+ const DEFAULT_DESCRIPTION = "✨ Data Intelligence Lab @ HKU";+ const DEFAULT_NAV_ORDER: SidebarNavOrder = {+ start: ["/", "/history", "/knowledge", "/notebook"],+ learnResearch: [+ "/question",+ "/solver",+ "/guide",+ "/ideagen",+ "/research",+ "/co_writer",+ ],+ };++ const [sidebarDescription, setSidebarDescriptionState] =+ useState<string>(DEFAULT_DESCRIPTION);+ const [sidebarNavOrder, setSidebarNavOrderState] =+ useState<SidebarNavOrder>(DEFAULT_NAV_ORDER);++ // Initialize sidebar customization from backend API+ useEffect(() => {+ const loadSidebarSettings = async () => {+ try {+ const response = await fetch(apiUrl("/api/v1/settings/sidebar"));+ if (response.ok) {+ const data = await response.json();+ if (data.description) {+ setSidebarDescriptionState(data.description);+ }+ if (data.nav_order) {+ setSidebarNavOrderState(data.nav_order);+ }+ }+ } catch (e) {+ console.error("Failed to load sidebar settings from backend:", e);+ }+ };+ loadSidebarSettings();+ }, []);++ const setSidebarDescription = async (description: string) => {+ setSidebarDescriptionState(description);+ // Save to backend+ try {+ await fetch(apiUrl("/api/v1/settings/sidebar/description"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ description }),+ });+ } catch (e) {+ console.error("Failed to save sidebar description:", e);+ }+ };++ const setSidebarNavOrder = async (order: SidebarNavOrder) => {+ setSidebarNavOrderState(order);+ // Save to backend+ try {+ await fetch(apiUrl("/api/v1/settings/sidebar/nav-order"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ nav_order: order }),+ });+ } catch (e) {+ console.error("Failed to save sidebar nav order:", e);+ }+ };+// --- Solver Logic ---const [solverState, setSolverState] = useState<SolverState>({isSolving: false,@@ -910,139 +1054,40 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {};};- const startMimicQuestionGen = async (- file: File | null,- paperPath: string,- kb: string,- maxQuestions?: number,- ) => {- if (questionWs.current) questionWs.current.close();-- // Support two modes: PDF upload or pre-parsed directory- const hasFile = file !== null;- const hasParsedPath = paperPath && paperPath.trim() !== "";-- if (!hasFile && !hasParsedPath) {- addQuestionLog({- type: "error",- content: "Please upload a PDF file or provide a parsed exam directory",- });- return;- }-- setQuestionState((prev) => ({- ...prev,- step: "generating",- mode: "mimic",- logs: [],- results: [],- selectedKb: kb,- uploadedFile: file,- paperPath: paperPath,- progress: {- stage: hasFile ? "uploading" : "parsing", // Start with uploading for PDF, parsing for pre-parsed- progress: { current: 0, total: maxQuestions || 1 },- },- agentStatus: {- QuestionGenerationAgent: "pending",- ValidationWorkflow: "pending",- RetrievalTool: "pending",- },- tokenStats: {- model: "Unknown",- calls: 0,- tokens: 0,- input_tokens: 0,- output_tokens: 0,- cost: 0.0,- },- }));-- const ws = new WebSocket(wsUrl("/api/v1/question/mimic"));- questionWs.current = ws;-- ws.onopen = async () => {- if (hasFile && file) {- // Convert file to base64- addQuestionLog({- type: "system",- content: "Preparing to upload PDF file...",- });- const reader = new FileReader();- reader.onload = () => {- const base64Data = (reader.result as string).split(",")[1]; // Remove data:application/pdf;base64, prefix- ws.send(- JSON.stringify({- mode: "upload",- pdf_data: base64Data,- pdf_name: file.name,- kb_name: kb,- max_questions: maxQuestions,- }),- );- addQuestionLog({- type: "system",- content: `Uploaded: ${file.name}, parsing...`,- });- };- reader.readAsDataURL(file);- } else {- // Use pre-parsed directory- ws.send(- JSON.stringify({- mode: "parsed",- paper_path: paperPath,- kb_name: kb,- max_questions: maxQuestions,- }),- );- addQuestionLog({- type: "system",- content: "Initializing Mimic Generator...",- });- }+ // Helper function to handle mimic WebSocket messages+ const handleMimicWsMessage = (data: any, ws: WebSocket) => {+ const stageMap: Record<string, string> = {+ init: "uploading",+ upload: "uploading",+ parsing: "parsing",+ processing: "extracting",};- ws.onmessage = (event) => {- const data = JSON.parse(event.data);-- if (data.type === "log") {+ switch (data.type) {+ case "log":addQuestionLog(data);- } else if (data.type === "status") {- // Status updates for mimic mode stages- const stageMap: Record<string, string> = {- init: "uploading",- upload: "uploading",- parsing: "parsing",- processing: "extracting",- };- const mappedStage = stageMap[data.stage] || data.stage;+ break;+ case "status": {+ const mappedStage = stageMap[data.stage] || data.stage;addQuestionLog({type: "system",content: data.content || data.message || `Stage: ${data.stage}`,});-- // Update progress stage based on status eventif (mappedStage) {setQuestionState((prev) => ({...prev,- progress: {- ...prev.progress,- stage: mappedStage,- },+ progress: { ...prev.progress, stage: mappedStage },}));}- } else if (data.type === "progress") {- // Progress updates for mimic mode (parsing, extracting, generating)- const stage = data.stage || "generating";- const message = data.message || "";-- addQuestionLog({- type: "system",- content: message,- });+ break;+ }+ case "progress": {+ const stage = data.stage || "generating";+ if (data.message) {+ addQuestionLog({ type: "system", content: data.message });+ }setQuestionState((prev) => ({...prev,progress: {@@ -1059,7 +1104,6 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {},},}));-// Store reference questions info when extracting is completeif (stage === "extracting" &&@@ -1077,42 +1121,39 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {},}));}- } else if (data.type === "question_update") {- // Individual question status update during generation+ break;+ }++ case "question_update": {const statusMessage =data.status === "generating"? `Generating mimic question ${data.index}...`: data.status === "failed"? `Question ${data.index} failed: ${data.error}`: `Question ${data.index}: ${data.status}`;-addQuestionLog({type: data.status === "failed" ? "warning" : "system",content: statusMessage,});-if (data.current !== undefined) {setQuestionState((prev) => ({...prev,progress: {...prev.progress,- progress: {- ...prev.progress.progress,- current: data.current,- },+ progress: { ...prev.progress.progress, current: data.current },},}));}- } else if (data.type === "result") {- // Single question result+ break;+ }++ case "result": {const isExtended =data.extended || data.validation?.decision === "extended";-addQuestionLog({type: "success",content: `✅ Question ${data.index || (data.current ?? 0)} generated successfully`,});-setQuestionState((prev) => ({...prev,results: [@@ -1137,32 +1178,31 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {(prev.progress.extendedQuestions || 0) + (isExtended ? 1 : 0),},}));- } else if (data.type === "summary") {- // Final summary for mimic mode+ break;+ }++ case "summary":addQuestionLog({type: "success",content: `Generation complete: ${data.successful}/${data.total_reference} succeeded`,});-setQuestionState((prev) => ({...prev,progress: {...prev.progress,stage: "generating",- progress: {- current: data.successful,- total: data.total_reference,- },+ progress: { current: data.successful, total: data.total_reference },completedQuestions: data.successful,failedQuestions: data.failed,},}));- } else if (data.type === "complete") {+ break;++ case "complete":addQuestionLog({type: "success",content: "✅ Mimic generation completed!",});-setQuestionState((prev) => ({...prev,step: "result",@@ -1173,7 +1213,9 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {},}));ws.close();- } else if (data.type === "error") {+ break;++ case "error":addQuestionLog({type: "error",content: `Error: ${data.content || data.message || "Unknown error"}`,@@ -1181,14 +1223,110 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {setQuestionState((prev) => ({...prev,step: "config",- progress: {- stage: null,- progress: {},- },+ progress: { stage: null, progress: {} },}));+ break;+ }+ };++ const startMimicQuestionGen = async (+ file: File | null,+ paperPath: string,+ kb: string,+ maxQuestions?: number,+ ) => {+ if (questionWs.current) questionWs.current.close();++ // Validate input+ const hasFile = file !== null;+ const hasParsedPath = paperPath && paperPath.trim() !== "";++ if (!hasFile && !hasParsedPath) {+ addQuestionLog({+ type: "error",+ content: "Please upload a PDF file or provide a parsed exam directory",+ });+ return;+ }++ // Initialize state+ setQuestionState((prev) => ({+ ...prev,+ step: "generating",+ mode: "mimic",+ logs: [],+ results: [],+ selectedKb: kb,+ uploadedFile: file,+ paperPath: paperPath,+ progress: {+ stage: hasFile ? "uploading" : "parsing",+ progress: { current: 0, total: maxQuestions || 1 },+ },+ agentStatus: {+ QuestionGenerationAgent: "pending",+ ValidationWorkflow: "pending",+ RetrievalTool: "pending",+ },+ tokenStats: {+ model: "Unknown",+ calls: 0,+ tokens: 0,+ input_tokens: 0,+ output_tokens: 0,+ cost: 0.0,+ },+ }));++ // Create WebSocket connection+ const ws = new WebSocket(wsUrl("/api/v1/question/mimic"));+ questionWs.current = ws;++ ws.onopen = async () => {+ if (hasFile && file) {+ addQuestionLog({+ type: "system",+ content: "Preparing to upload PDF file...",+ });+ const reader = new FileReader();+ reader.onload = () => {+ const base64Data = (reader.result as string).split(",")[1];+ ws.send(+ JSON.stringify({+ mode: "upload",+ pdf_data: base64Data,+ pdf_name: file.name,+ kb_name: kb,+ max_questions: maxQuestions,+ }),+ );+ addQuestionLog({+ type: "system",+ content: `Uploaded: ${file.name}, parsing...`,+ });+ };+ reader.readAsDataURL(file);+ } else {+ ws.send(+ JSON.stringify({+ mode: "parsed",+ paper_path: paperPath,+ kb_name: kb,+ max_questions: maxQuestions,+ }),+ );+ addQuestionLog({+ type: "system",+ content: "Initializing Mimic Generator...",+ });}};+ ws.onmessage = (event) => {+ const data = JSON.parse(event.data);+ handleMimicWsMessage(data, ws);+ };+ws.onerror = () => {addQuestionLog({ type: "error", content: "WebSocket connection error" });setQuestionState((prev) => ({ ...prev, step: "config" }));@@ -1692,11 +1830,17 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {newChatSession,uiSettings,refreshSettings,+ updateTheme,+ updateLanguage,sidebarWidth,setSidebarWidth,sidebarCollapsed,setSidebarCollapsed,toggleSidebar,+ sidebarDescription,+ setSidebarDescription,+ sidebarNavOrder,+ setSidebarNavOrder,}}>{children}diff --git a/web/lib/i18n.ts b/web/lib/i18n.tsindex db9ceeefe..a9d7b71eb 100644--- a/web/lib/i18n.ts+++ b/web/lib/i18n.ts@@ -122,6 +122,10 @@ export const translations = {"From Knowledge Base": "From Knowledge Base","From Web": "From Web","New Chat": "New Chat",+ "Save to Notebook": "Save to Notebook",+ "Click to edit": "Click to edit",+ "Expand sidebar": "Expand sidebar",+ "Collapse sidebar": "Collapse sidebar",// History Page"Chat History": "Chat History",@@ -250,6 +254,10 @@ export const translations = {"From Knowledge Base": "来自知识库","From Web": "来自网络","New Chat": "新对话",+ "Save to Notebook": "保存到笔记本",+ "Click to edit": "点击编辑",+ "Expand sidebar": "展开侧边栏",+ "Collapse sidebar": "收起侧边栏",// History Page"Chat History": "聊天历史",diff --git a/web/tests/e2e/compliance-and-ux.audit.ts b/web/tests/e2e/compliance-and-ux.audit.tsindex 9ef4366b0..45dfccba5 100644--- a/web/tests/e2e/compliance-and-ux.audit.ts+++ b/web/tests/e2e/compliance-and-ux.audit.ts@@ -4,9 +4,14 @@ import { test, expect } from "@playwright/test";// Focus on semantic landmarks, headings, alt text, link names, and basic error messaging.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";-async function expectAnyVisible(locators: import("@playwright/test").Locator[], message: string) {+async function expectAnyVisible(+ locators: import("@playwright/test").Locator[],+ message: string,+) {for (const loc of locators) {try {if (await loc.first().isVisible()) return;@@ -34,12 +39,16 @@ test.describe("Compliance :: Accessibility & Semantics", () => {imgs.filter((img) => {const alt = img.getAttribute("alt");return !alt || alt.trim().length === 0;- }).length+ }).length,+ );+ expect(missingAltCount, `Found ${missingAltCount} <img> without alt`).toBe(+ 0,);- expect(missingAltCount, `Found ${missingAltCount} <img> without alt`).toBe(0);});- test("links have accessible names (text/aria-label/title)", async ({ page }) => {+ test("links have accessible names (text/aria-label/title)", async ({+ page,+ }) => {await page.goto(`${BASE_URL}/`);const namelessLinks = await page.$$eval("a",@@ -49,9 +58,12 @@ test.describe("Compliance :: Accessibility & Semantics", () => {const aria = (a.getAttribute("aria-label") || "").trim();const title = (a.getAttribute("title") || "").trim();return text.length === 0 && aria.length === 0 && title.length === 0;- }).length+ }).length,);- expect(namelessLinks, `Found ${namelessLinks} <a> without accessible name`).toBe(0);+ expect(+ namelessLinks,+ `Found ${namelessLinks} <a> without accessible name`,+ ).toBe(0);});test("viewport meta present for responsive UX", async ({ page }) => {@@ -62,13 +74,15 @@ test.describe("Compliance :: Accessibility & Semantics", () => {});test.describe("Compliance :: Error Handling & UX Signals", () => {- test("api error surfaces user-friendly feedback (alert or message)", async ({ page }) => {+ test("api error surfaces user-friendly feedback (alert or message)", async ({+ page,+ }) => {await page.route("**/api/v1/notebook/list", (route) =>route.fulfill({status: 500,headers: { "content-type": "application/json" },body: JSON.stringify({ detail: "Simulated Backend Failure" }),- })+ }),);await page.goto(`${BASE_URL}/notebook`);@@ -78,9 +92,9 @@ test.describe("Compliance :: Error Handling & UX Signals", () => {page.locator('[role="alert"]'),page.locator('[data-test="notebooks-empty"]'),page.locator('[data-testid="notebooks-empty"]'),- page.locator('text=No notebooks'),+ page.locator("text=No notebooks"),],- "Expected error banner or empty state after simulated failure"+ "Expected error banner or empty state after simulated failure",);});});diff --git a/web/tsconfig.json b/web/tsconfig.jsonindex aefc06a77..60c6b1dec 100644--- a/web/tsconfig.json+++ b/web/tsconfig.json@@ -15,7 +15,7 @@"incremental": true,"plugins": [{ "name": "next" }],"paths": { "@/*": ["./*"] },- "types": ["node", "@playwright/test"]+ "types": ["node"]},"include": ["next-env.d.ts",