Skip to content

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

refactor: restructure project architecture with new services and logging modules

Pancakecf595bf5628e
diff --git a/scripts/start.py b/scripts/start.py
index b54ac4c2f..25af55211 100644
--- a/scripts/start.py
+++ b/scripts/start.py
@@ -31,8 +31,8 @@ sys.path.insert(0, str(project_root))
from src.agents.question import AgentCoordinator
from src.agents.solve import MainSolver
from src.api.utils.history import ActivityType, history_manager
-from src.core.core import get_llm_config
-from src.core.logging import get_logger
+from src.services.llm import get_llm_config
+from src.logging import get_logger
# Initialize logger for CLI
logger = get_logger("CLI", console_output=True, file_output=True)
@@ -45,7 +45,7 @@ class AITutorStarter:
"""Initialize launcher"""
# Initialize user data directories
try:
- from src.core.setup import init_user_directories
+ from src.services.setup import init_user_directories
init_user_directories(project_root)
except Exception as e:
@@ -54,8 +54,8 @@ class AITutorStarter:
try:
llm_config = get_llm_config()
- self.api_key = llm_config["api_key"]
- self.base_url = llm_config["base_url"]
+ self.api_key = llm_config.api_key
+ self.base_url = llm_config.base_url
except ValueError as e:
logger.error(str(e))
logger.error("Please configure LLM settings in .env or DeepTutor.env file")
@@ -446,7 +446,7 @@ class AITutorStarter:
try:
# Import research pipeline
from src.agents.research.research_pipeline import ResearchPipeline
- from src.core.core import load_config_with_main
+ from src.services.config import load_config_with_main
# Load configuration using unified config loader
config = load_config_with_main("main.yaml", project_root)
@@ -710,9 +710,9 @@ class AITutorStarter:
try:
llm_config = get_llm_config()
print("\n📦 LLM Configuration:")
- print(f" Model: {llm_config.get('model', 'N/A')}")
- print(f" API Endpoint: {llm_config.get('base_url', 'N/A')}")
- print(f" API Key: {'Configured' if llm_config.get('api_key') else 'Not configured'}")
+ print(f" Model: {llm_config.model or 'N/A'}")
+ print(f" API Endpoint: {llm_config.base_url or 'N/A'}")
+ print(f" API Key: {'Configured' if llm_config.api_key else 'Not configured'}")
except Exception as e:
print(f" ❌ Load failed: {e}")
@@ -797,7 +797,7 @@ def main():
if __name__ == "__main__":
# Initialize user data directories
try:
- from src.core.setup import init_user_directories
+ from src.services.setup import init_user_directories
init_user_directories(project_root)
except Exception as e:
diff --git a/scripts/start_web.py b/scripts/start_web.py
index 3cc9f9ee1..b21dad543 100644
--- a/scripts/start_web.py
+++ b/scripts/start_web.py
@@ -156,7 +156,7 @@ def start_backend():
# Get port from configuration
try:
- from src.core.setup import get_backend_port
+ from src.services.setup import get_backend_port
backend_port = get_backend_port(Path(project_root))
print_flush(f"✅ Backend port configured: {backend_port}")
@@ -165,7 +165,7 @@ def start_backend():
raise
except Exception as e:
print_flush(f"❌ Failed to get backend port: {e}")
- from src.core.setup import print_port_config_tutorial
+ from src.services.setup import print_port_config_tutorial
print_port_config_tutorial()
raise
@@ -250,7 +250,7 @@ def start_frontend():
try:
from pathlib import Path
- from src.core.setup import get_frontend_port
+ from src.services.setup import get_frontend_port
frontend_port = get_frontend_port(Path(project_root))
print_flush(f"✅ Frontend port configured: {frontend_port}")
@@ -259,7 +259,7 @@ def start_frontend():
raise
except Exception as e:
print_flush(f"❌ Failed to get frontend port: {e}")
- from src.core.setup import print_port_config_tutorial
+ from src.services.setup import print_port_config_tutorial
print_port_config_tutorial()
raise
@@ -319,7 +319,7 @@ def start_frontend():
# Get backend port for frontend API configuration
from pathlib import Path
- from src.core.setup import get_backend_port
+ from src.services.setup import get_backend_port
backend_port = get_backend_port(Path(project_root))
@@ -415,7 +415,7 @@ if __name__ == "__main__":
sys.path.insert(0, project_root)
from pathlib import Path
- from src.core.setup import init_user_directories
+ from src.services.setup import init_user_directories
init_user_directories(Path(project_root))
except Exception as e:
@@ -431,7 +431,7 @@ if __name__ == "__main__":
# Get backend port for health check
from pathlib import Path
- from src.core.setup import get_backend_port
+ from src.services.setup import get_backend_port
backend_port = get_backend_port(
Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -469,7 +469,7 @@ if __name__ == "__main__":
# Get ports for display
from pathlib import Path
- from src.core.setup import get_ports
+ from src.services.setup import get_ports
backend_port, frontend_port = get_ports(
Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
diff --git a/src/agents/__init__.py b/src/agents/__init__.py
index 5cc386831..7584316cb 100644
--- a/src/agents/__init__.py
+++ b/src/agents/__init__.py
@@ -8,6 +8,7 @@ This module provides a unified BaseAgent class and module-specific agents:
- ideagen: Idea generation agents (IdeaGenerationWorkflow, etc.)
- co_writer: Co-writing agents (EditAgent, NarratorAgent)
- question: Question generation agents (ReAct architecture, separate base)
+- chat: Lightweight conversational agent with session management
Usage:
from src.agents.base_agent import BaseAgent
@@ -18,6 +19,7 @@ Usage:
"""
from .base_agent import BaseAgent
+from .chat import ChatAgent, SessionManager
-__all__ = ["BaseAgent"]
+__all__ = ["BaseAgent", "ChatAgent", "SessionManager"]
diff --git a/src/agents/base_agent.py b/src/agents/base_agent.py
index 993f3d061..4abc19cc9 100644
--- a/src/agents/base_agent.py
+++ b/src/agents/base_agent.py
@@ -27,9 +27,10 @@ if str(_project_root) not in sys.path:
from lightrag.llm.openai import openai_complete_if_cache
-from src.core.core import get_agent_params, get_llm_config, get_token_limit_kwargs
-from src.core.logging import LLMStats, get_logger
-from src.core.prompt_manager import get_prompt_manager
+from src.services.config import get_agent_params
+from src.services.llm import get_llm_config, get_token_limit_kwargs
+from src.logging import LLMStats, get_logger
+from src.services.prompt import get_prompt_manager
class BaseAgent(ABC):
@@ -79,7 +80,15 @@ class BaseAgent(ABC):
self.module_name = module_name
self.agent_name = agent_name
self.language = language
- self.config = config or {}
+ # Ensure config is always a dict (not a dataclass like LLMConfig)
+ if config is None:
+ self.config = {}
+ elif isinstance(config, dict):
+ self.config = config
+ else:
+ # If config is a dataclass (like LLMConfig), convert to empty dict
+ # The actual LLM config should be loaded via get_llm_config()
+ self.config = {}
# Load agent parameters from unified config (agents.yaml)
self._agent_params = get_agent_params(module_name)
@@ -87,9 +96,9 @@ class BaseAgent(ABC):
# Load LLM configuration
try:
env_llm = get_llm_config()
- self.api_key = api_key or env_llm.get("api_key")
- self.base_url = base_url or env_llm.get("base_url")
- self.model = model or env_llm.get("model")
+ self.api_key = api_key or env_llm.api_key
+ self.base_url = base_url or env_llm.base_url
+ self.model = model or env_llm.model
except ValueError:
# Fallback if env config not available
self.api_key = api_key or os.getenv("LLM_BINDING_API_KEY")
@@ -98,7 +107,13 @@ class BaseAgent(ABC):
# Get Agent-specific configuration (if config provided)
self.agent_config = self.config.get("agents", {}).get(agent_name, {})
- self.llm_config = self.config.get("llm", {})
+ llm_cfg = self.config.get("llm", {})
+ # Ensure llm_config is always a dict (handle case where LLMConfig object is passed)
+ if hasattr(llm_cfg, '__dataclass_fields__'):
+ from dataclasses import asdict
+ self.llm_config = asdict(llm_cfg)
+ else:
+ self.llm_config = llm_cfg if isinstance(llm_cfg, dict) else {}
# Agent status
self.enabled = self.agent_config.get("enabled", True)
diff --git a/src/agents/chat/README.md b/src/agents/chat/README.md
new file mode 100644
index 000000000..e60eb4043
--- /dev/null
+++ b/src/agents/chat/README.md
@@ -0,0 +1,64 @@
+# Chat Module
+
+Lightweight conversational AI module with multi-turn dialogue support and session management.
+
+## Features
+
+- **Multi-turn Conversation**: Maintains conversation history as context for LLM
+- **Token Management**: Automatic truncation of history to fit within token limits
+- **RAG Integration**: Optional knowledge base retrieval
+- **Web Search**: Optional web search for up-to-date information
+- **Session Management**: Persistent storage of chat sessions
+- **Streaming Support**: Real-time response streaming via WebSocket
+
+## Components
+
+### ChatAgent
+
+The main conversational agent that:
+- Inherits from `BaseAgent` for unified LLM access
+- Supports RAG and Web Search augmentation
+- Manages conversation history with token limits
+- Provides streaming responses
+
+### SessionManager
+
+Manages chat sessions:
+- Create, update, retrieve, and delete sessions
+- Store sessions in `data/user/chat_sessions.json`
+- List recent sessions for history display
+
+## Usage
+
+```python
+from src.agents.chat import ChatAgent, SessionManager
+
+# Initialize agent
+agent = ChatAgent(language="en")
+
+# Process a message
+response = await agent.process(
+ message="What is backpropagation?",
+ history=[
+ {"role": "user", "content": "Hello"},
+ {"role": "assistant", "content": "Hi! How can I help?"}
+ ],
+ kb_name="ai_textbook",
+ enable_rag=True,
+ enable_web_search=False
+)
+
+# Session management
+session_mgr = SessionManager()
+session = session_mgr.create_session("First question")
+session_mgr.update_session(session["session_id"], messages)
+```
+
+## Configuration
+
+The agent uses prompts from:
+- `prompts/en/chat_agent.yaml` (English)
+- `prompts/zh/chat_agent.yaml` (Chinese)
+
+Token limits and other parameters are configured in `config/agents.yaml`.
+
diff --git a/src/agents/chat/__init__.py b/src/agents/chat/__init__.py
new file mode 100644
index 000000000..7cb881aa1
--- /dev/null
+++ b/src/agents/chat/__init__.py
@@ -0,0 +1,25 @@
+"""
+Chat Module - Lightweight conversational AI with session management.
+
+This module provides:
+- ChatAgent: Multi-turn conversational agent with RAG/Web Search support
+- SessionManager: Chat session persistence and management
+
+Usage:
+ from src.agents.chat import ChatAgent, SessionManager
+
+ agent = ChatAgent(language="en")
+ response = await agent.process(
+ message="What is machine learning?",
+ history=[],
+ kb_name="ai_textbook",
+ enable_rag=True,
+ enable_web_search=False
+ )
+"""
+
+from .chat_agent import ChatAgent
+from .session_manager import SessionManager
+
+__all__ = ["ChatAgent", "SessionManager"]
+
diff --git a/src/agents/chat/chat_agent.py b/src/agents/chat/chat_agent.py
new file mode 100644
index 000000000..71b828438
--- /dev/null
+++ b/src/agents/chat/chat_agent.py
@@ -0,0 +1,411 @@
+#!/usr/bin/env python
+"""
+ChatAgent - Lightweight conversational AI with multi-turn support.
+
+This agent provides:
+- Multi-turn conversation with history management
+- Token-based context truncation
+- Optional RAG and Web Search augmentation
+- Streaming response generation
+"""
+
+from pathlib import Path
+import sys
+from typing import Any, AsyncGenerator
+
+# Add project root to path
+_project_root = Path(__file__).parent.parent.parent.parent
+if str(_project_root) not in sys.path:
+ sys.path.insert(0, str(_project_root))
+
+from openai import AsyncOpenAI
+
+from src.agents.base_agent import BaseAgent
+from src.services.llm import get_llm_config
+from src.tools import rag_search, web_search
+
+
+class ChatAgent(BaseAgent):
+ """
+ Lightweight conversational agent with multi-turn support.
+
+ Features:
+ - Conversation history management with token limits
+ - RAG (Retrieval-Augmented Generation) support
+ - Web search integration
+ - Streaming response generation
+ """
+
+ # Default token limit for conversation history
+ DEFAULT_MAX_HISTORY_TOKENS = 4000
+
+ def __init__(
+ self,
+ language: str = "zh",
+ config: dict[str, Any] | None = None,
+ max_history_tokens: int | None = None,
+ **kwargs,
+ ):
+ """
+ Initialize ChatAgent.
+
+ Args:
+ language: Language setting ('zh' | 'en')
+ config: Optional configuration dictionary
+ max_history_tokens: Maximum tokens for conversation history
+ **kwargs: Additional arguments passed to BaseAgent
+ """
+ super().__init__(
+ module_name="chat",
+ agent_name="chat_agent",
+ language=language,
+ config=config,
+ **kwargs,
+ )
+
+ # Configure history token limit
+ self.max_history_tokens = max_history_tokens or self.agent_config.get(
+ "max_history_tokens", self.DEFAULT_MAX_HISTORY_TOKENS
+ )
+
+ # Initialize async OpenAI client for streaming
+ llm_config = get_llm_config()
+ self._async_client = AsyncOpenAI(
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ )
+
+ def count_tokens(self, text: str) -> int:
+ """
+ Count tokens in text using tiktoken.
+
+ Falls back to character-based estimation if tiktoken unavailable.
+
+ Args:
+ text: Text to count tokens for
+
+ Returns:
+ Estimated token count
+ """
+ try:
+ import tiktoken
+ # Use cl100k_base encoding (GPT-4, GPT-3.5-turbo)
+ encoding = tiktoken.get_encoding("cl100k_base")
+ return len(encoding.encode(text))
+ except ImportError:
+ # Fallback: rough estimate of 4 characters per token
+ return len(text) // 4
+
+ def truncate_history(
+ self,
+ history: list[dict[str, str]],
+ max_tokens: int | None = None,
+ ) -> list[dict[str, str]]:
+ """
+ Truncate conversation history to fit within token limit.
+
+ Keeps the most recent messages, discarding older ones first.
+
+ Args:
+ history: List of message dicts with 'role' and 'content'
+ max_tokens: Maximum tokens allowed (uses default if None)
+
+ Returns:
+ Truncated history list
+ """
+ max_tokens = max_tokens or self.max_history_tokens
+
+ if not history:
+ return []
+
+ # Calculate tokens for each message
+ message_tokens = []
+ for msg in history:
+ content = msg.get("content", "")
+ tokens = self.count_tokens(content)
+ message_tokens.append((msg, tokens))
+
+ # Build history from newest to oldest, stop when limit reached
+ truncated = []
+ total_tokens = 0
+
+ for msg, tokens in reversed(message_tokens):
+ if total_tokens + tokens > max_tokens:
+ break
+ truncated.insert(0, msg)
+ total_tokens += tokens
+
+ if len(truncated) < len(history):
+ self.logger.info(
+ f"Truncated history from {len(history)} to {len(truncated)} messages "
+ f"({total_tokens} tokens)"
+ )
+
+ return truncated
+
+ def format_history_for_prompt(self, history: list[dict[str, str]]) -> str:
+ """
+ Format conversation history as a string for the prompt.
+
+ Args:
+ history: List of message dicts
+
+ Returns:
+ Formatted history string
+ """
+ if not history:
+ return ""
+
+ lines = []
+ for msg in history:
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+ prefix = "User" if role == "user" else "Assistant"
+ lines.append(f"{prefix}: {content}")
+
+ return "\n\n".join(lines)
+
+ async def retrieve_context(
+ self,
+ message: str,
+ kb_name: str | None = None,
+ enable_rag: bool = False,
+ enable_web_search: bool = False,
+ ) -> tuple[str, dict[str, Any]]:
+ """
+ Retrieve context from RAG and/or Web Search.
+
+ Args:
+ message: User message to search for
+ kb_name: Knowledge base name for RAG
+ enable_rag: Whether to use RAG
+ enable_web_search: Whether to use Web Search
+
+ Returns:
+ Tuple of (context_string, sources_dict)
+ """
+ context_parts = []
+ sources = {"rag": [], "web": []}
+
+ # RAG retrieval
+ if enable_rag and kb_name:
+ try:
+ self.logger.info(f"RAG search: {message[:50]}...")
+ rag_result = await rag_search(
+ query=message,
+ kb_name=kb_name,
+ mode="hybrid",
+ )
+ rag_answer = rag_result.get("answer", "")
+ if rag_answer:
+ context_parts.append(f"[Knowledge Base: {kb_name}]\n{rag_answer}")
+ sources["rag"].append({
+ "kb_name": kb_name,
+ "content": rag_answer[:500] + "..." if len(rag_answer) > 500 else rag_answer,
+ })
+ self.logger.info(f"RAG retrieved {len(rag_answer)} chars")
+ except Exception as e:
+ self.logger.warning(f"RAG search failed: {e}")
+
+ # Web search
+ if enable_web_search:
+ try:
+ self.logger.info(f"Web search: {message[:50]}...")
+ web_result = web_search(query=message, verbose=False)
+ web_answer = web_result.get("answer", "")
+ web_citations = web_result.get("citations", [])
+
+ if web_answer:
+ context_parts.append(f"[Web Search Results]\n{web_answer}")
+ sources["web"] = web_citations[:5]
+ self.logger.info(
+ f"Web search returned {len(web_answer)} chars, "
+ f"{len(web_citations)} citations"
+ )
+ except Exception as e:
+ self.logger.warning(f"Web search failed: {e}")
+
+ context = "\n\n".join(context_parts)
+ return context, sources
+
+ def build_messages(
+ self,
+ message: str,
+ history: list[dict[str, str]],
+ context: str = "",
+ ) -> list[dict[str, str]]:
+ """
+ Build the messages array for the LLM API call.
+
+ Args:
+ message: Current user message
+ history: Truncated conversation history
+ context: Retrieved context (RAG/Web)
+
+ Returns:
+ List of message dicts for OpenAI API
+ """
+ messages = []
+
+ # System prompt
+ system_prompt = self.get_prompt("system", "You are a helpful AI assistant.")
+ messages.append({"role": "system", "content": system_prompt})
+
+ # Add context if available
+ if context:
+ context_template = self.get_prompt(
+ "context_template",
+ "Reference context:\n{context}"
+ )
+ context_msg = context_template.format(context=context)
+ messages.append({"role": "system", "content": context_msg})
+
+ # Add conversation history
+ for msg in history:
+ role = msg.get("role", "user")
+ content = msg.get("content", "")
+ if role in ("user", "assistant"):
+ messages.append({"role": role, "content": content})
+
+ # Add current message
+ messages.append({"role": "user", "content": message})
+
+ return messages
+
+ async def generate_stream(
+ self,
+ messages: list[dict[str, str]],
+ ) -> AsyncGenerator[str, None]:
+ """
+ Generate streaming response from LLM.
+
+ Args:
+ messages: Messages array for OpenAI API
+
+ Yields:
+ Response chunks as strings
+ """
+ try:
+ response = await self._async_client.chat.completions.create(
+ model=self.get_model(),
+ messages=messages,
+ temperature=self.get_temperature(),
+ stream=True,
+ )
+
+ async for chunk in response:
+ if chunk.choices[0].delta.content:
+ yield chunk.choices[0].delta.content
+
+ except Exception as e:
+ self.logger.error(f"Streaming generation failed: {e}")
+ raise
+
+ async def generate(self, messages: list[dict[str, str]]) -> str:
+ """
+ Generate complete response from LLM (non-streaming).
+
+ Args:
+ messages: Messages array for OpenAI API
+
+ Returns:
+ Complete response string
+ """
+ try:
+ response = await self._async_client.chat.completions.create(
+ model=self.get_model(),
+ messages=messages,
+ temperature=self.get_temperature(),
+ )
+
+ content = response.choices[0].message.content or ""
+
+ # Track token usage
+ self._track_tokens(
+ model=self.get_model(),
+ system_prompt=messages[0]["content"] if messages else "",
+ user_prompt=messages[-1]["content"] if messages else "",
+ response=content,
+ stage="chat",
+ )
+
+ return content
+
+ except Exception as e:
+ self.logger.error(f"Generation failed: {e}")
+ raise
+
+ async def process(
+ self,
+ message: str,
+ history: list[dict[str, str]] | None = None,
+ kb_name: str | None = None,
+ enable_rag: bool = False,
+ enable_web_search: bool = False,
+ stream: bool = False,
+ ) -> dict[str, Any] | AsyncGenerator[dict[str, Any], None]:
+ """
+ Process a chat message with optional context retrieval.
+
+ Args:
+ message: User message
+ history: Conversation history (will be truncated if needed)
+ kb_name: Knowledge base name for RAG
+ enable_rag: Whether to enable RAG retrieval
+ enable_web_search: Whether to enable web search
+ stream: Whether to stream the response
+
+ Returns:
+ If stream=False: Dict with 'response', 'sources', 'truncated_history'
+ If stream=True: AsyncGenerator yielding chunks
+ """
+ history = history or []
+
+ # Truncate history to fit token limit
+ truncated_history = self.truncate_history(history)
+
+ # Retrieve context if needed
+ context, sources = await self.retrieve_context(
+ message=message,
+ kb_name=kb_name,
+ enable_rag=enable_rag,
+ enable_web_search=enable_web_search,
+ )
+
+ # Build messages for LLM
+ messages = self.build_messages(
+ message=message,
+ history=truncated_history,
+ context=context,
+ )
+
+ if stream:
+ # Return async generator for streaming
+ async def stream_generator():
+ full_response = ""
+ async for chunk in self.generate_stream(messages):
+ full_response += chunk
+ yield {"type": "chunk", "content": chunk}
+
+ # Yield final result with sources
+ yield {
+ "type": "complete",
+ "response": full_response,
+ "sources": sources,
+ "truncated_history": truncated_history,
+ }
+
+ return stream_generator()
+ else:
+ # Generate complete response
+ response = await self.generate(messages)
+
+ return {
+ "response": response,
+ "sources": sources,
+ "truncated_history": truncated_history,
+ }
+
+
+__all__ = ["ChatAgent"]
+
diff --git a/src/agents/chat/prompts/en/chat_agent.yaml b/src/agents/chat/prompts/en/chat_agent.yaml
new file mode 100644
index 000000000..41a2899ac
--- /dev/null
+++ b/src/agents/chat/prompts/en/chat_agent.yaml
@@ -0,0 +1,36 @@
+# Chat Agent Prompts (English)
+
+system: |
+ You are DeepTutor, an intelligent AI learning assistant developed by the Data Intelligence Lab at HKU.
+
+ Your capabilities:
+ - Help students understand complex concepts across STEM subjects
+ - Answer questions clearly and accurately with proper explanations
+ - Provide step-by-step guidance when solving problems
+ - Cite sources when using provided reference context
+
+ Guidelines:
+ - Be clear, accurate, and engaging in your explanations
+ - Use examples and analogies to make concepts easier to understand
+ - If you're unsure about something, acknowledge it honestly
+ - When reference context is provided, use it to give more accurate answers
+ - Always maintain a helpful and encouraging tone
+
+context_template: |
+ Here is some reference context that may help answer the question:
+
+ <context>
+ {context}
+ </context>
+
+ Please use this context to provide an accurate and well-informed response.
+
+user_template: |
+ {message}
+
+history_format: |
+ Previous conversation:
+ {history}
+
+ Now continue the conversation:
+
diff --git a/src/agents/chat/prompts/zh/chat_agent.yaml b/src/agents/chat/prompts/zh/chat_agent.yaml
new file mode 100644
index 000000000..04ecab4ab
--- /dev/null
+++ b/src/agents/chat/prompts/zh/chat_agent.yaml
@@ -0,0 +1,36 @@
+# Chat Agent Prompts (中文)
+
+system: |
+ 你是 DeepTutor,一个由香港大学数据智能实验室开发的智能 AI 学习助手。
+
+ 你的能力:
+ - 帮助学生理解 STEM 领域的复杂概念
+ - 清晰准确地回答问题,并提供适当的解释
+ - 在解决问题时提供逐步指导
+ - 使用提供的参考上下文时注明来源
+
+ 指南:
+ - 解释要清晰、准确、有吸引力
+ - 使用例子和类比使概念更容易理解
+ - 如果对某些内容不确定,诚实地承认
+ - 当提供参考上下文时,使用它来给出更准确的答案
+ - 始终保持乐于助人和鼓励的语气
+
+context_template: |
+ 以下是一些可能有助于回答问题的参考上下文:
+
+ <context>
+ {context}
+ </context>
+
+ 请使用此上下文提供准确且有根据的回复。
+
+user_template: |
+ {message}
+
+history_format: |
+ 之前的对话:
+ {history}
+
+ 现在继续对话:
+
diff --git a/src/agents/chat/session_manager.py b/src/agents/chat/session_manager.py
new file mode 100644
index 000000000..dd128f9fe
--- /dev/null
+++ b/src/agents/chat/session_manager.py
@@ -0,0 +1,312 @@
+#!/usr/bin/env python
+"""
+SessionManager - Chat session persistence and management.
+
+This module handles:
+- Creating new chat sessions
+- Updating sessions with new messages
+- Retrieving session history
+- Listing recent sessions
+- Deleting sessions
+"""
+
+import json
+import time
+import uuid
+from pathlib import Path
+from typing import Any
+
+
+class SessionManager:
+ """
+ Manages persistent storage of chat sessions.
+
+ Sessions are stored in a JSON file at data/user/chat_sessions.json.
+ Each session contains:
+ - session_id: Unique identifier
+ - title: Session title (usually first user message)
+ - messages: List of messages with role, content, sources, timestamp
+ - settings: RAG/Web Search settings used
+ - created_at: Creation timestamp
+ - updated_at: Last update timestamp
+ """
+
+ def __init__(self, base_dir: str | None = None):
+ """
+ Initialize SessionManager.
+
+ Args:
+ base_dir: Base directory for session storage.
+ Defaults to project_root/data/user
+ """
+ if base_dir is None:
+ # Current file: src/agents/chat/session_manager.py
+ # Project root: 4 levels up
+ project_root = Path(__file__).resolve().parents[3]
+ base_dir_path = project_root / "data" / "user"
+ else:
+ base_dir_path = Path(base_dir)
+
+ self.base_dir = base_dir_path
+ self.base_dir.mkdir(parents=True, exist_ok=True)
+
+ self.sessions_file = self.base_dir / "chat_sessions.json"
+ self._ensure_file()
+
+ def _ensure_file(self):
+ """Ensure the sessions file exists with correct format."""
+ if not self.sessions_file.exists():
+ initial_data = {
+ "version": "1.0",
+ "sessions": [],
+ }
+ self._save_data(initial_data)
+
+ def _load_data(self) -> dict[str, Any]:
+ """Load sessions data from file."""
+ try:
+ with open(self.sessions_file, encoding="utf-8") as f:
+ return json.load(f)
+ except (json.JSONDecodeError, FileNotFoundError):
+ return {"version": "1.0", "sessions": []}
+
+ def _save_data(self, data: dict[str, Any]):
+ """Save sessions data to file."""
+ with open(self.sessions_file, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+
+ def _get_sessions(self) -> list[dict[str, Any]]:
+ """Get list of all sessions."""
+ data = self._load_data()
+ return data.get("sessions", [])
+
+ def _save_sessions(self, sessions: list[dict[str, Any]]):
+ """Save sessions list."""
+ data = self._load_data()
+ data["sessions"] = sessions
+ self._save_data(data)
+
+ def create_session(
+ self,
+ title: str = "New Chat",
+ settings: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """
+ Create a new chat session.
+
+ Args:
+ title: Session title
+ settings: Optional settings (kb_name, enable_rag, enable_web_search)
+
+ Returns:
+ New session dict with session_id
+ """
+ session_id = f"chat_{int(time.time() * 1000)}_{uuid.uuid4().hex[:8]}"
+ now = time.time()
+
+ session = {
+ "session_id": session_id,
+ "title": title[:100], # Limit title length
+ "messages": [],
+ "settings": settings or {},
+ "created_at": now,
+ "updated_at": now,
+ }
+
+ sessions = self._get_sessions()
+ sessions.insert(0, session) # Add to front (newest first)
+
+ # Limit total sessions to prevent file bloat
+ max_sessions = 100
+ if len(sessions) > max_sessions:
+ sessions = sessions[:max_sessions]
+
+ self._save_sessions(sessions)
+
+ return session
+
+ def get_session(self, session_id: str) -> dict[str, Any] | None:
+ """
+ Get a session by ID.
+
+ Args:
+ session_id: Session identifier
+
+ Returns:
+ Session dict or None if not found
+ """
+ sessions = self._get_sessions()
+ for session in sessions:
+ if session.get("session_id") == session_id:
+ return session
+ return None
+
+ def update_session(
+ self,
+ session_id: str,
+ messages: list[dict[str, Any]] | None = None,
+ title: str | None = None,
+ settings: dict[str, Any] | None = None,
+ ) -> dict[str, Any] | None:
+ """
+ Update a session with new data.
+
+ Args:
+ session_id: Session identifier
+ messages: New messages list (replaces existing)
+ title: New title (optional)
+ settings: New settings (optional)
+
+ Returns:
+ Updated session or None if not found
+ """
+ sessions = self._get_sessions()
+
+ for i, session in enumerate(sessions):
+ if session.get("session_id") == session_id:
+ if messages is not None:
+ session["messages"] = messages
+ if title is not None:
+ session["title"] = title[:100]
+ if settings is not None:
+ session["settings"] = settings
+
+ session["updated_at"] = time.time()
+
+ # Move to front (most recently updated)
+ sessions.pop(i)
+ sessions.insert(0, session)
+
+ self._save_sessions(sessions)
+ return session
+
+ return None
+
+ def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str,
+ sources: dict[str, Any] | None = None,
+ ) -> dict[str, Any] | None:
+ """
+ Add a single message to a session.
+
+ Args:
+ session_id: Session identifier
+ role: Message role ('user' or 'assistant')
+ content: Message content
+ sources: Optional sources dict (for assistant messages)
+
+ Returns:
+ Updated session or None if not found
+ """
+ session = self.get_session(session_id)
+ if not session:
+ return None
+
+ message = {
+ "role": role,
+ "content": content,
+ "timestamp": time.time(),
+ }
+ if sources:
+ message["sources"] = sources
+
+ messages = session.get("messages", [])
+ messages.append(message)
+
+ # Update title from first user message if still default
+ if session.get("title") == "New Chat" and role == "user":
+ new_title = content[:50] + ("..." if len(content) > 50 else "")
+ return self.update_session(session_id, messages=messages, title=new_title)
+
+ return self.update_session(session_id, messages=messages)
+
+ def list_sessions(
+ self,
+ limit: int = 20,
+ include_messages: bool = False,
+ ) -> list[dict[str, Any]]:
+ """
+ List recent sessions.
+
+ Args:
+ limit: Maximum number of sessions to return
+ include_messages: Whether to include full message history
+
+ Returns:
+ List of session dicts (newest first)
+ """
+ sessions = self._get_sessions()[:limit]
+
+ if not include_messages:
+ # Return summary only (without full messages)
+ return [
+ {
+ "session_id": s.get("session_id"),
+ "title": s.get("title"),
+ "message_count": len(s.get("messages", [])),
+ "settings": s.get("settings"),
+ "created_at": s.get("created_at"),
+ "updated_at": s.get("updated_at"),
+ # Include preview of last message
+ "last_message": (
+ s.get("messages", [])[-1].get("content", "")[:100]
+ if s.get("messages")
+ else ""
+ ),
+ }
+ for s in sessions
+ ]
+
+ return sessions
+
+ def delete_session(self, session_id: str) -> bool:
+ """
+ Delete a session.
+
+ Args:
+ session_id: Session identifier
+
+ Returns:
+ True if deleted, False if not found
+ """
+ sessions = self._get_sessions()
+ original_count = len(sessions)
+
+ sessions = [s for s in sessions if s.get("session_id") != session_id]
+
+ if len(sessions) < original_count:
+ self._save_sessions(sessions)
+ return True
+
+ return False
+
+ def clear_all_sessions(self) -> int:
+ """
+ Delete all sessions.
+
+ Returns:
+ Number of sessions deleted
+ """
+ sessions = self._get_sessions()
+ count = len(sessions)
+ self._save_sessions([])
+ return count
+
+
+# Singleton instance for convenience
+_session_manager: SessionManager | None = None
+
+
+def get_session_manager() -> SessionManager:
+ """Get or create the global SessionManager instance."""
+ global _session_manager
+ if _session_manager is None:
+ _session_manager = SessionManager()
+ return _session_manager
+
+
+__all__ = ["SessionManager", "get_session_manager"]
+
diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.py
index 1c8be1b8b..a9cb2d4e7 100644
--- a/src/agents/co_writer/edit_agent.py
+++ b/src/agents/co_writer/edit_agent.py
@@ -18,9 +18,10 @@ if str(_project_root) not in sys.path:
from lightrag.llm.openai import openai_complete_if_cache
-from src.core.core import get_agent_params, get_llm_config, load_config_with_main
-from src.core.logging import LLMStats, get_logger
-from src.core.prompt_manager import get_prompt_manager
+from src.services.config import get_agent_params, load_config_with_main
+from src.services.llm import get_llm_config
+from src.logging import LLMStats, get_logger
+from src.services.prompt import get_prompt_manager
from src.tools.rag_tool import rag_search
from src.tools.web_search import web_search
@@ -225,13 +226,13 @@ class EditAgent:
# 3. Call LLM
logger.info(f"Calling LLM for {action}...")
- model = self.llm_config["model"]
+ model = self.llm_config.model
response = await openai_complete_if_cache(
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config["api_key"],
- base_url=self.llm_config["base_url"],
+ api_key=self.llm_config.api_key,
+ base_url=self.llm_config.base_url,
temperature=self._agent_params["temperature"],
max_tokens=self._agent_params["max_tokens"],
)
@@ -253,7 +254,7 @@ class EditAgent:
"input": {"original_text": text, "instruction": instruction},
"output": {"edited_text": response},
"tool_call_file": tool_call_file,
- "model": self.llm_config["model"],
+ "model": self.llm_config.model,
}
history.append(operation_record)
save_history(history)
@@ -283,13 +284,13 @@ class EditAgent:
user_prompt = user_template.format(text=text)
logger.info("Calling LLM for auto-mark...")
- model = self.llm_config["model"]
+ model = self.llm_config.model
response = await openai_complete_if_cache(
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config["api_key"],
- base_url=self.llm_config["base_url"],
+ api_key=self.llm_config.api_key,
+ base_url=self.llm_config.base_url,
temperature=self._agent_params["temperature"],
max_tokens=self._agent_params["max_tokens"],
)
@@ -311,7 +312,7 @@ class EditAgent:
"input": {"original_text": text, "instruction": "AI Auto Mark"},
"output": {"edited_text": response},
"tool_call_file": None,
- "model": self.llm_config["model"],
+ "model": self.llm_config.model,
}
history.append(operation_record)
save_history(history)
diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py
index 7be457327..5629a7887 100644
--- a/src/agents/co_writer/narrator_agent.py
+++ b/src/agents/co_writer/narrator_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
NarratorAgent - Note narration agent.
Uses unified PromptManager for prompt loading.
@@ -23,9 +24,11 @@ if str(_project_root) not in sys.path:
from lightrag.llm.openai import openai_complete_if_cache
-from src.core.core import get_agent_params, get_llm_config, get_tts_config, load_config_with_main
-from src.core.logging import get_logger
-from src.core.prompt_manager import get_prompt_manager
+from src.services.config import get_agent_params, load_config_with_main
+from src.services.llm import get_llm_config
+from src.services.tts import get_tts_config
+from src.logging import get_logger
+from src.services.prompt import get_prompt_manager
# Initialize logger with config
try:
@@ -195,13 +198,13 @@ class NarratorAgent:
logger.info(f"Generating narration script with style: {style}")
- model = self.llm_config["model"]
+ model = self.llm_config.model
response = await openai_complete_if_cache(
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config["api_key"],
- base_url=self.llm_config["base_url"],
+ api_key=self.llm_config.api_key,
+ base_url=self.llm_config.base_url,
max_tokens=self._agent_params["max_tokens"],
temperature=self._agent_params["temperature"],
)
@@ -255,13 +258,13 @@ class NarratorAgent:
user_prompt = user_template.format(content=content[:4000])
try:
- model = self.llm_config["model"]
+ model = self.llm_config.model
response = await openai_complete_if_cache(
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config["api_key"],
- base_url=self.llm_config["base_url"],
+ api_key=self.llm_config.api_key,
+ base_url=self.llm_config.base_url,
max_tokens=self._agent_params["max_tokens"],
temperature=self._agent_params["temperature"],
)
diff --git a/src/agents/guide/agents/interactive_agent.py b/src/agents/guide/agents/interactive_agent.py
index 81eb2e81f..3d3c118f3 100644
--- a/src/agents/guide/agents/interactive_agent.py
+++ b/src/agents/guide/agents/interactive_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
InteractiveAgent - Agent for generating interactive HTML pages
Converts knowledge points into visual, interactive learning pages
diff --git a/src/agents/guide/agents/summary_agent.py b/src/agents/guide/agents/summary_agent.py
index 31f186019..a8ce726c9 100644
--- a/src/agents/guide/agents/summary_agent.py
+++ b/src/agents/guide/agents/summary_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
SummaryAgent - Learning Summary Generation Agent
Generates personalized learning summary reports after users complete learning
diff --git a/src/agents/guide/guide_manager.py b/src/agents/guide/guide_manager.py
index 7eb66c0ac..593c29023 100644
--- a/src/agents/guide/guide_manager.py
+++ b/src/agents/guide/guide_manager.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
GuideManager - Guided Learning Session Manager
Manages the complete lifecycle of learning sessions
@@ -13,8 +14,8 @@ import uuid
import yaml
-from src.core.core import load_config_with_main, parse_language
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main, parse_language
+from src.logging import get_logger
from .agents import ChatAgent, InteractiveAgent, LocateAgent, SummaryAgent
@@ -349,7 +350,7 @@ class GuideManager:
session.current_index = new_index
session.current_html = interactive_result.get("html", "")
- message = f"✅ Entering knowledge point {new_index + 1}: {current_knowledge.get('knowledge_title', '')}"
+ message = f"→ Entering knowledge point {new_index + 1}: {current_knowledge.get('knowledge_title', '')}"
session.chat_history.append(
{
diff --git a/src/agents/ideagen/idea_generation_workflow.py b/src/agents/ideagen/idea_generation_workflow.py
index 45d55df2c..3eb26fb05 100644
--- a/src/agents/ideagen/idea_generation_workflow.py
+++ b/src/agents/ideagen/idea_generation_workflow.py
@@ -16,7 +16,7 @@ _project_root = Path(__file__).parent.parent.parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
-from src.core.prompt_manager import get_prompt_manager
+from src.services.prompt import get_prompt_manager
from src.agents.base_agent import BaseAgent
diff --git a/src/agents/ideagen/material_organizer_agent.py b/src/agents/ideagen/material_organizer_agent.py
index 2949d51d7..89b476f98 100644
--- a/src/agents/ideagen/material_organizer_agent.py
+++ b/src/agents/ideagen/material_organizer_agent.py
@@ -13,7 +13,7 @@ _project_root = Path(__file__).parent.parent.parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
-from src.core.prompt_manager import get_prompt_manager
+from src.services.prompt import get_prompt_manager
from src.agents.base_agent import BaseAgent
diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.py
index 1dc493fd6..4b4462b15 100644
--- a/src/agents/question/agents/base_agent.py
+++ b/src/agents/question/agents/base_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Base Agent class - Implements the ReAct (Reasoning + Acting) paradigm.
"""
@@ -21,8 +22,8 @@ load_dotenv(override=False)
project_root = Path(__file__).parent.parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import get_agent_params
-from src.core.logging import get_logger
+from src.services.config import get_agent_params
+from src.logging import get_logger
# Module logger
_logger = get_logger("QuestionAgent")
@@ -164,7 +165,7 @@ class BaseAgent(ABC):
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"
+ status = "✓ Success" if (obs and obs.success) else "✗ Failed"
history_parts.append(f" [{i + 1}] Action: {action.name} → {status}")
if action.params:
@@ -211,7 +212,7 @@ class BaseAgent(ABC):
if i < len(self.observation_history):
obs = self.observation_history[i]
- status = "✅ Success" if obs.success else "❌ Failed"
+ status = "✓ Success" if obs.success else "✗ Failed"
history_parts.append(f"Observation: {status}")
if obs.message:
history_parts.append(f" Message: {obs.message}")
diff --git a/src/agents/question/agents/generation_agent.py b/src/agents/question/agents/generation_agent.py
index c8debf615..05ff5059b 100644
--- a/src/agents/question/agents/generation_agent.py
+++ b/src/agents/question/agents/generation_agent.py
@@ -13,9 +13,9 @@ from typing import Any
project_root = Path(__file__).parent.parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import load_config_with_main
-from src.core.logging import get_logger
-from src.core.prompt_manager import get_prompt_manager
+from src.services.config import load_config_with_main
+from src.logging import get_logger
+from src.services.prompt import get_prompt_manager
from src.tools.rag_tool import rag_search
from .base_agent import Action, BaseAgent, Message, Observation
diff --git a/src/agents/question/agents/validation_agent.py b/src/agents/question/agents/validation_agent.py
index 79dce3575..2f490e678 100644
--- a/src/agents/question/agents/validation_agent.py
+++ b/src/agents/question/agents/validation_agent.py
@@ -12,9 +12,9 @@ from typing import Any
project_root = Path(__file__).parent.parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import load_config_with_main
-from src.core.logging import get_logger
-from src.core.prompt_manager import get_prompt_manager
+from src.services.config import load_config_with_main
+from src.logging import get_logger
+from src.services.prompt import get_prompt_manager
from src.tools.rag_tool import rag_search
from .base_agent import Action, BaseAgent, Message, Observation
diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.py
index 8af2febca..67c1bd286 100644
--- a/src/agents/question/coordinator.py
+++ b/src/agents/question/coordinator.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Agent coordinator responsible for managing collaboration between the question-generation agent
and the validation workflow.
@@ -21,8 +22,8 @@ from .validation_workflow import QuestionValidationWorkflow
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import load_config_with_main
-from src.core.logging import Logger, get_logger
+from src.services.config import load_config_with_main
+from src.logging import Logger, get_logger
from src.tools.rag_tool import rag_search
@@ -330,13 +331,13 @@ class AgentCoordinator:
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"
+ "✓ 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"
+ "✗ 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.'
)
diff --git a/src/agents/question/example.py b/src/agents/question/example.py
index 534228a36..a71d6c5b0 100644
--- a/src/agents/question/example.py
+++ b/src/agents/question/example.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Example script that demonstrates how to use the Agent coordinator.
"""
@@ -48,7 +49,7 @@ async def run_single_example(coordinator: AgentCoordinator):
question = result["question"]
validation = result["validation"]
- print(f"\n✅ Success in {result['rounds']} round(s)")
+ print(f"\n✓ Success in {result['rounds']} round(s)")
print(f"\nType: {question.get('question_type')}")
print(f"\nQuestion:\n{question.get('question')}")
@@ -71,7 +72,7 @@ async def run_single_example(coordinator: AgentCoordinator):
"\n💡 Tip: try a different knowledge point or ensure the knowledge base contains supporting material."
)
else:
- print(f"\n❌ Failed: {error_type}")
+ print(f"\n✗ Failed: {error_type}")
if result.get("last_question"):
print("\nLast attempted question:")
print(json.dumps(result["last_question"], ensure_ascii=False, indent=2))
diff --git a/src/agents/question/tools/exam_mimic.py b/src/agents/question/tools/exam_mimic.py
index 56dd3e604..e3e003616 100644
--- a/src/agents/question/tools/exam_mimic.py
+++ b/src/agents/question/tools/exam_mimic.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Reference-based exam-question generation system
@@ -192,7 +193,7 @@ async def mimic_exam_questions(
"error": error_msg,
}
- print(f"✅ Exam directory detected: {latest_dir.name}")
+ print(f"✓ Exam directory detected: {latest_dir.name}")
print(f" Full path: {latest_dir}")
print()
@@ -248,7 +249,7 @@ async def mimic_exam_questions(
return {"success": False, "error": "No parsed outputs were found"}
latest_dir = subdirs[0]
- print(f"✅ Parsed folder: {latest_dir.name}")
+ print(f"✓ Parsed folder: {latest_dir.name}")
print()
await send_progress(
@@ -276,7 +277,7 @@ async def mimic_exam_questions(
json_files = list(latest_dir.glob("*_questions.json"))
if json_files:
- print(f"✅ Found existing question file: {json_files[0].name}")
+ print(f"✓ Found existing question file: {json_files[0].name}")
with open(json_files[0], encoding="utf-8") as f:
questions_data = json.load(f)
else:
@@ -302,7 +303,7 @@ async def mimic_exam_questions(
if max_questions:
reference_questions = reference_questions[:max_questions]
- print(f"✅ Loaded {len(reference_questions)} reference questions")
+ print(f"✓ Loaded {len(reference_questions)} reference questions")
print()
# Send reference questions info
@@ -344,7 +345,7 @@ async def mimic_exam_questions(
# Lazy import to avoid circular import
from src.agents.question import AgentCoordinator
- from src.core.core import load_config_with_main
+ from src.services.config import load_config_with_main
# Load config for parallel settings
config = load_config_with_main("question_config.yaml", project_root)
@@ -396,7 +397,7 @@ async def mimic_exam_questions(
current_completed = completed_count
if result.get("success"):
- print(f"✅ [{question_id}] Generated in {result['rounds']} round(s)")
+ print(f"✓ [{question_id}] Generated in {result['rounds']} round(s)")
result_data = {
"success": True,
@@ -426,7 +427,7 @@ async def mimic_exam_questions(
return result_data
else:
- print(f"❌ [{question_id}] Failed: {result.get('error', 'Unknown error')}")
+ print(f"✗ [{question_id}] Failed: {result.get('error', 'Unknown error')}")
error_data = {
"success": False,
@@ -451,7 +452,7 @@ async def mimic_exam_questions(
return error_data
except Exception as e:
- print(f"❌ [{question_id}] Exception: {e!s}")
+ print(f"✗ [{question_id}] Exception: {e!s}")
async with completed_lock:
completed_count += 1
@@ -603,10 +604,10 @@ Examples:
)
if result["success"]:
- print("✅ Completed!")
+ print("✓ Completed!")
sys.exit(0)
else:
- print(f"❌ Failed: {result.get('error')}")
+ print(f"✗ Failed: {result.get('error')}")
sys.exit(1)
diff --git a/src/agents/question/tools/pdf_parser.py b/src/agents/question/tools/pdf_parser.py
index 17d56aecb..6cf9c9c3a 100644
--- a/src/agents/question/tools/pdf_parser.py
+++ b/src/agents/question/tools/pdf_parser.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Parse PDF files using MinerU and save results to reference_papers directory
"""
@@ -47,7 +48,7 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
"""
mineru_cmd = check_mineru_installed()
if not mineru_cmd:
- print("❌ Error: MinerU installation not detected")
+ print("✗ Error: MinerU installation not detected")
print("Please install MinerU first:")
print(" pip install magic-pdf[full]")
print("or")
@@ -55,15 +56,15 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
print("or visit: https://github.com/opendatalab/MinerU")
return False
- print(f"✅ Detected MinerU command: {mineru_cmd}")
+ print(f"✓ Detected MinerU command: {mineru_cmd}")
pdf_path = Path(pdf_path).resolve()
if not pdf_path.exists():
- print(f"❌ Error: PDF file does not exist: {pdf_path}")
+ print(f"✗ Error: PDF file does not exist: {pdf_path}")
return False
if not pdf_path.suffix.lower() == ".pdf":
- print(f"❌ Error: File is not PDF format: {pdf_path}")
+ print(f"✗ Error: File is not PDF format: {pdf_path}")
return False
script_dir = Path(__file__).parent.parent.parent.parent.parent
@@ -85,7 +86,7 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
print(f"📄 PDF file: {pdf_path}")
print(f"📁 Output directory: {output_dir}")
- print("⏳ Starting parsing...")
+ print("→ Starting parsing...")
try:
temp_output = output_base_dir / "temp_mineru_output"
@@ -98,14 +99,14 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode != 0:
- print("❌ MinerU parsing failed:")
+ print("✗ MinerU parsing failed:")
print(f"Stdout: {result.stdout}")
print(f"Stderr: {result.stderr}")
if temp_output.exists():
shutil.rmtree(temp_output)
return False
- print("✅ MinerU parsing completed!")
+ print("✓ MinerU parsing completed!")
generated_folders = list(temp_output.iterdir())
@@ -150,7 +151,7 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):
return True
except Exception as e:
- print(f"❌ Error occurred during parsing: {e!s}")
+ print(f"✗ Error occurred during parsing: {e!s}")
import traceback
traceback.print_exc()
@@ -187,10 +188,10 @@ Examples:
success = parse_pdf_with_mineru(args.pdf_path, args.output)
if success:
- print("\n✅ Parsing completed!")
+ print("\n✓ Parsing completed!")
sys.exit(0)
else:
- print("\n❌ Parsing failed!")
+ print("\n✗ Parsing failed!")
sys.exit(1)
diff --git a/src/agents/question/tools/question_extractor.py b/src/agents/question/tools/question_extractor.py
index df1304495..5eb5a90c5 100644
--- a/src/agents/question/tools/question_extractor.py
+++ b/src/agents/question/tools/question_extractor.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Extract question information from MinerU-parsed exam papers
@@ -18,7 +19,8 @@ sys.path.insert(0, str(project_root))
from openai import OpenAI
-from src.core.core import get_agent_params, get_llm_config
+from src.services.config import get_agent_params
+from src.services.llm import get_llm_config
def load_parsed_paper(paper_dir: Path) -> tuple[str | None, list[dict] | None, Path]:
@@ -37,7 +39,7 @@ def load_parsed_paper(paper_dir: Path) -> tuple[str | None, list[dict] | None, P
md_files = list(auto_dir.glob("*.md"))
if not md_files:
- print(f"❌ Error: No markdown file found in {auto_dir}")
+ print(f"✗ Error: No markdown file found in {auto_dir}")
return None, None, auto_dir / "images"
md_file = md_files[0]
@@ -172,16 +174,16 @@ Please analyze the above exam paper content, extract all question information, a
result = json.loads(result_text)
questions = result.get("questions", [])
- print(f"✅ Successfully extracted {len(questions)} questions")
+ print(f"✓ Successfully extracted {len(questions)} questions")
return questions
except json.JSONDecodeError as e:
- print(f"❌ JSON parsing error: {e!s}")
+ print(f"✗ JSON parsing error: {e!s}")
print(f"LLM response content: {result_text[:500]}...")
return []
except Exception as e:
- print(f"❌ LLM call failed: {e!s}")
+ print(f"✗ LLM call failed: {e!s}")
import traceback
traceback.print_exc()
@@ -239,7 +241,7 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
"""
paper_dir = Path(paper_dir).resolve()
if not paper_dir.exists():
- print(f"❌ Error: Directory does not exist: {paper_dir}")
+ print(f"✗ Error: Directory does not exist: {paper_dir}")
return False
print(f"📁 Paper directory: {paper_dir}")
@@ -247,13 +249,13 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
markdown_content, content_list, images_dir = load_parsed_paper(paper_dir)
if not markdown_content:
- print("❌ Error: Unable to load paper content")
+ print("✗ Error: Unable to load paper content")
return False
try:
llm_config = get_llm_config()
except ValueError as e:
- print(f"❌ {e!s}")
+ print(f"✗ {e!s}")
print(
"Tip: Please create .env file in project root and configure LLM-related environment variables"
)
@@ -263,9 +265,9 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
markdown_content=markdown_content,
content_list=content_list,
images_dir=images_dir,
- api_key=llm_config["api_key"],
- base_url=llm_config["base_url"],
- model=llm_config["model"],
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ model=llm_config.model,
)
if not questions:
@@ -280,7 +282,7 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
paper_name = paper_dir.name
output_file = save_questions_json(questions, output_dir, paper_name)
- print("\n✅ Question extraction completed!")
+ print("\n✓ Question extraction completed!")
print(f"📄 View results: {output_file}")
return True
diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.py
index 6bc74677f..8263541c2 100644
--- a/src/agents/question/validation_workflow.py
+++ b/src/agents/question/validation_workflow.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Question Validation Workflow: retrieve -> validate -> return.
Uses unified PromptManager for prompt loading.
@@ -17,9 +18,9 @@ from openai import AsyncOpenAI
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import get_agent_params, load_config_with_main
-from src.core.logging import get_logger
-from src.core.prompt_manager import get_prompt_manager
+from src.services.config import get_agent_params, load_config_with_main
+from src.logging import get_logger
+from src.services.prompt import get_prompt_manager
from src.tools.rag_tool import rag_search
# Module logger
diff --git a/src/agents/research/agents/decompose_agent.py b/src/agents/research/agents/decompose_agent.py
index fe17f274c..9a10b888d 100644
--- a/src/agents/research/agents/decompose_agent.py
+++ b/src/agents/research/agents/decompose_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
DecomposeAgent - Topic decomposition Agent
Responsible for decomposing topics into multiple subtopics and generating overviews for each subtopic
@@ -180,7 +181,7 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics
except Exception:
sub_topics = []
- print(f"✅ Generated {len(sub_topics)} subtopics (without RAG)")
+ print(f"✓ Generated {len(sub_topics)} subtopics (without RAG)")
return {
"main_topic": topic,
@@ -197,7 +198,7 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics
# Step 1: Generate sub-queries
print("\n🔍 Step 1: Generating sub-queries...")
sub_queries = await self._generate_sub_queries(topic, num_subtopics)
- print(f"✅ Generated {len(sub_queries)} sub-queries")
+ print(f"✓ Generated {len(sub_queries)} sub-queries")
# Step 2: Execute RAG retrieval to get background knowledge
print("\n🔍 Step 2: Executing RAG retrieval...")
@@ -253,7 +254,7 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics
topic=topic, rag_context=combined_rag_context, num_subtopics=num_subtopics
)
- print(f"✅ Generated {len(sub_topics)} subtopics")
+ print(f"✓ Generated {len(sub_topics)} subtopics")
return {
"main_topic": topic,
@@ -314,7 +315,7 @@ Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics
topic=topic, rag_context=rag_context, max_subtopics=max_subtopics
)
- print(f"✅ Autonomously generated {len(sub_topics)} subtopics")
+ print(f"✓ Autonomously generated {len(sub_topics)} subtopics")
return {
"main_topic": topic,
diff --git a/src/agents/research/agents/manager_agent.py b/src/agents/research/agents/manager_agent.py
index 30dd7b83f..6af0de60b 100644
--- a/src/agents/research/agents/manager_agent.py
+++ b/src/agents/research/agents/manager_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ManagerAgent - Queue management Agent
Responsible for managing DynamicTopicQueue state and task distribution
@@ -76,7 +77,7 @@ class ManagerAgent(BaseAgent):
success = self.queue.mark_completed(block_id)
if success:
- print(f"✅ ManagerAgent: Task {block_id} completed")
+ print(f"✓ ManagerAgent: Task {block_id} completed")
return success
@@ -147,7 +148,7 @@ class ManagerAgent(BaseAgent):
success = self.queue.mark_failed(block_id)
if success:
- print(f"❌ ManagerAgent: Task {block_id} failed")
+ print(f"✗ ManagerAgent: Task {block_id} failed")
if reason:
print(f" Reason: {reason}")
@@ -175,7 +176,7 @@ class ManagerAgent(BaseAgent):
return None
block = self.queue.add_block(normalized, overview)
- print(f"➕ ManagerAgent: Added new topic {block.block_id}")
+ print(f"✓ ManagerAgent: Added new topic {block.block_id}")
print(f" Topic: {sub_topic}")
return block
diff --git a/src/agents/research/agents/note_agent.py b/src/agents/research/agents/note_agent.py
index abb4538e7..d4acf97fc 100644
--- a/src/agents/research/agents/note_agent.py
+++ b/src/agents/research/agents/note_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
NoteAgent - Recording Agent
Responsible for information compression and summary generation, converting raw data returned by tools into usable knowledge summaries
@@ -72,7 +73,7 @@ class NoteAgent(BaseAgent):
tool_type=tool_type, query=query, raw_answer=raw_answer, topic=topic, context=context
)
- print(f"✅ Summary generation completed ({len(summary)} characters)")
+ print(f"✓ Summary generation completed ({len(summary)} characters)")
# Create ToolTrace with the provided citation ID
tool_id = self._generate_tool_id()
diff --git a/src/agents/research/agents/rephrase_agent.py b/src/agents/research/agents/rephrase_agent.py
index d1e588a5d..5319f480f 100644
--- a/src/agents/research/agents/rephrase_agent.py
+++ b/src/agents/research/agents/rephrase_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
RephraseAgent - Topic rephrasing Agent
Responsible for rephrasing and optimizing user input
@@ -156,7 +157,7 @@ class RephraseAgent(BaseAgent):
}
)
- print("\n✅ Rephrasing Completed:")
+ print("\n✓ Rephrasing Completed:")
print(f" Optimized Research Topic: {result.get('topic', '')}")
return result
diff --git a/src/agents/research/agents/reporting_agent.py b/src/agents/research/agents/reporting_agent.py
index 3a8ee2f18..24b71cbac 100644
--- a/src/agents/research/agents/reporting_agent.py
+++ b/src/agents/research/agents/reporting_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ReportingAgent - Report generation Agent (DR-in-KG 2.0)
- Deduplication and cleaning
@@ -113,7 +114,7 @@ class ReportingAgent(BaseAgent):
# 1) Deduplication
print("🔄 Step 1: Deduplication and cleaning...")
cleaned_blocks = await self._deduplicate_blocks(queue.blocks)
- print(f"✅ Cleaning completed: {len(cleaned_blocks)} topic blocks")
+ print(f"✓ Cleaning completed: {len(cleaned_blocks)} topic blocks")
self._notify_progress(
progress_callback, "deduplicate_completed", kept_blocks=len(cleaned_blocks)
)
@@ -121,7 +122,7 @@ class ReportingAgent(BaseAgent):
# 2) Outline
print("\n📋 Step 2: Generating outline...")
outline = await self._generate_outline(topic, cleaned_blocks)
- print("✅ Outline generation completed")
+ print("✓ Outline generation completed")
self._notify_progress(
progress_callback, "outline_completed", sections=len(outline.get("sections", []))
)
@@ -132,7 +133,7 @@ class ReportingAgent(BaseAgent):
# 3) Writing
print("\n✍️ Step 3: Writing report...")
report_markdown = await self._write_report(topic, cleaned_blocks, outline)
- print("✅ Report writing completed")
+ print("✓ Report writing completed")
self._notify_progress(progress_callback, "writing_completed")
word_count = len(report_markdown)
diff --git a/src/agents/research/agents/research_agent.py b/src/agents/research/agents/research_agent.py
index c79510db9..499feba56 100644
--- a/src/agents/research/agents/research_agent.py
+++ b/src/agents/research/agents/research_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ResearchAgent - Research Agent
Responsible for executing research logic and tool call decisions
@@ -564,7 +565,7 @@ Tools already used: {", ".join(used_tools) if used_tools else "None"}
else:
added = manager_agent.add_new_topic(trimmed_topic, new_overview or "")
if added:
- print(f"{block_id_prefix} ➕ Added new topic《{trimmed_topic}》to queue")
+ print(f"{block_id_prefix} ✓ Added new topic《{trimmed_topic}》to queue")
send_progress(
"new_topic_added",
iteration=iteration,
diff --git a/src/agents/research/data_structures.py b/src/agents/research/data_structures.py
index b114bc689..a8fbe2924 100644
--- a/src/agents/research/data_structures.py
+++ b/src/agents/research/data_structures.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
DR-in-KG 2.0 Core Data Structures
Includes: TopicBlock, ToolTrace, DynamicTopicQueue
diff --git a/src/agents/research/main.py b/src/agents/research/main.py
index 07958d010..b6f9e891c 100644
--- a/src/agents/research/main.py
+++ b/src/agents/research/main.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
DR-in-KG 2.0 - Main Entry
Deep research system based on dynamic topic queue
@@ -16,7 +17,7 @@ from dotenv import load_dotenv
import yaml
from src.agents.research.research_pipeline import ResearchPipeline
-from src.core.core import get_llm_config
+from src.services.llm import get_llm_config
def load_config(config_path: str = None, preset: str = None) -> dict:
@@ -32,7 +33,7 @@ def load_config(config_path: str = None, preset: str = None) -> dict:
"""
if config_path is None:
project_root = Path(__file__).parent.parent.parent.parent
- from src.core.core import load_config_with_main
+ from src.services.config import load_config_with_main
config = load_config_with_main("research_config.yaml", project_root)
else:
@@ -129,7 +130,7 @@ Examples:
try:
llm_config = get_llm_config()
except ValueError as e:
- print(f"❌ Error: {e}")
+ print(f"✗ Error: {e}")
print("Please configure in .env or DeepTutor.env file:")
print(" LLM_MODEL=gpt-4o")
print(" LLM_BINDING_API_KEY=your_api_key_here")
@@ -140,7 +141,7 @@ Examples:
try:
config = load_config(args.config, args.preset)
except Exception as e:
- print(f"❌ Failed to load configuration: {e!s}")
+ print(f"✗ Failed to load configuration: {e!s}")
sys.exit(1)
# Override configuration (command line arguments take priority)
@@ -153,7 +154,7 @@ Examples:
# Create research pipeline
pipeline = ResearchPipeline(
- config=config, api_key=llm_config["api_key"], base_url=llm_config["base_url"]
+ config=config, api_key=llm_config.api_key, base_url=llm_config.base_url
)
# Execute research
@@ -161,7 +162,7 @@ Examples:
result = await pipeline.run(topic=args.topic)
print("\n" + "=" * 70)
- print("✅ Research completed!")
+ print("✓ Research completed!")
print("=" * 70)
print(f"Research ID: {result['research_id']}")
print(f"Topic: {result['topic']}")
@@ -172,7 +173,7 @@ Examples:
print("\n\n⚠️ Research interrupted by user")
sys.exit(0)
except Exception as e:
- print(f"\n\n❌ Research failed: {e!s}")
+ print(f"\n\n✗ Research failed: {e!s}")
import traceback
traceback.print_exc()
diff --git a/src/agents/research/research_pipeline.py b/src/agents/research/research_pipeline.py
index be1aabe2f..c15a98821 100644
--- a/src/agents/research/research_pipeline.py
+++ b/src/agents/research/research_pipeline.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ResearchPipeline 2.0 - Research workflow based on dynamic topic queue
Coordinates three stages: Planning -> Researching -> Reporting
@@ -54,7 +55,7 @@ from src.agents.research.agents import (
)
from src.agents.research.data_structures import DynamicTopicQueue
from src.agents.research.utils.citation_manager import CitationManager
-from src.core.logging import get_logger
+from src.logging import get_logger
from src.tools.code_executor import run_code
from src.tools.paper_search_tool import PaperSearchTool
from src.tools.query_item_tool import query_numbered_item
@@ -390,30 +391,30 @@ class ResearchPipeline:
try:
# ========== Phase 1: Planning (Planning and Initialization) ==========
- self.logger.info("\n" + "█" * 70)
- self.logger.info("█ Phase 1: Planning - Planning and Initialization")
- self.logger.info("█" * 70)
+ self.logger.info("\n" + "═" * 70)
+ self.logger.info("▶ Phase 1: Planning - Planning and Initialization")
+ self.logger.info("═" * 70)
optimized_topic = await self._phase1_planning(topic)
# ========== Phase 2: Researching (Dynamic Research Loop) ==========
- self.logger.info("\n" + "█" * 70)
- self.logger.info("█ Phase 2: Researching - Dynamic Research Loop")
- self.logger.info("█" * 70)
+ self.logger.info("\n" + "═" * 70)
+ self.logger.info("▶ Phase 2: Researching - Dynamic Research Loop")
+ self.logger.info("═" * 70)
await self._phase2_researching()
# ========== Phase 3: Reporting (Report Generation) ==========
- self.logger.info("\n" + "█" * 70)
- self.logger.info("█ Phase 3: Reporting - Report Generation")
- self.logger.info("█" * 70)
+ self.logger.info("\n" + "═" * 70)
+ self.logger.info("▶ Phase 3: Reporting - Report Generation")
+ self.logger.info("═" * 70)
report_result = await self._phase3_reporting(optimized_topic)
# ========== Save Results ==========
- self.logger.info("\n" + "█" * 70)
- self.logger.info("█ Save Results")
- self.logger.info("█" * 70 + "\n")
+ self.logger.info("\n" + "═" * 70)
+ self.logger.info("▶ Save Results")
+ self.logger.info("═" * 70 + "\n")
report_file = self.reports_dir / f"{self.research_id}.md"
with open(report_file, "w", encoding="utf-8") as f:
@@ -481,7 +482,7 @@ class ResearchPipeline:
self.logger.warning("\n\n⚠️ Research interrupted by user")
sys.exit(0)
except Exception as e:
- self.logger.error(f"\n\n❌ Research failed: {e!s}")
+ self.logger.error(f"\n\n✗ Research failed: {e!s}")
import traceback
self.logger.error(traceback.format_exc())
@@ -994,7 +995,7 @@ class ResearchPipeline:
)
if self.logger:
- self.logger.success(f"[{block.block_id}] ✅ Completed: {block.sub_topic}")
+ self.logger.success(f"[{block.block_id}] ✓ Completed: {block.sub_topic}")
return result
@@ -1007,7 +1008,7 @@ class ResearchPipeline:
await update_active_task(block.block_id, None)
if self.logger:
- self.logger.error(f"[{block.block_id}] ❌ Failed: {block.sub_topic} - {e}")
+ self.logger.error(f"[{block.block_id}] ✗ Failed: {block.sub_topic} - {e}")
self._log_researching_progress(
"block_failed",
@@ -1028,7 +1029,7 @@ class ResearchPipeline:
block = pending_blocks[i]
await manager.fail_task_async(block.block_id, str(result))
if self.logger:
- self.logger.error(f"[{block.block_id}] ❌ Exception: {result}")
+ self.logger.error(f"[{block.block_id}] ✗ Exception: {result}")
# Wait for any dynamically added topics (if manager adds new topics during research)
# Continue until all tasks are processed (completed or failed)
@@ -1232,7 +1233,7 @@ async def main():
from dotenv import load_dotenv
import yaml
- from src.core.core import get_llm_config
+ from src.services.llm import get_llm_config
# Load environment variables
load_dotenv()
@@ -1270,7 +1271,7 @@ async def main():
# Create research pipeline
pipeline = ResearchPipeline(
- config=config, api_key=llm_config["api_key"], base_url=llm_config["base_url"]
+ config=config, api_key=llm_config.api_key, base_url=llm_config.base_url
)
# Execute research
diff --git a/src/agents/research/utils/__init__.py b/src/agents/research/utils/__init__.py
index ee5050717..c6b5c3e48 100644
--- a/src/agents/research/utils/__init__.py
+++ b/src/agents/research/utils/__init__.py
@@ -14,7 +14,7 @@ if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
# Import from unified logging system
-from src.core.logging import Logger, get_logger
+from src.logging import Logger, get_logger
from .json_utils import (
ensure_json_dict,
@@ -38,7 +38,7 @@ def get_llm_logger(research_id: str = None, log_dir: str = None, agent_name: str
def reset_llm_logger():
"""Reset LLM logger (backwards compatibility)"""
- from src.core.logging import reset_logger
+ from src.logging import reset_logger
reset_logger()
diff --git a/src/agents/research/utils/citation_manager.py b/src/agents/research/utils/citation_manager.py
index 333414b5f..4d19dae02 100644
--- a/src/agents/research/utils/citation_manager.py
+++ b/src/agents/research/utils/citation_manager.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
CitationManager - Citation management system
Responsible for extracting citation information from tool calls and managing citation JSON files
diff --git a/src/agents/research/utils/token_tracker.py b/src/agents/research/utils/token_tracker.py
index 752f38832..1952d886e 100644
--- a/src/agents/research/utils/token_tracker.py
+++ b/src/agents/research/utils/token_tracker.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Token Tracker - LLM Token usage and cost tracking system (DR-in-KG version)
References student_TA/solve_agents/utils/token_tracker.py, with minor trimming and added global singleton getter method.
diff --git a/src/agents/solve/__init__.py b/src/agents/solve/__init__.py
index 1d07d1314..a9e5c3ef3 100644
--- a/src/agents/solve/__init__.py
+++ b/src/agents/solve/__init__.py
@@ -13,7 +13,7 @@ if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
# Infrastructure
-from src.core.logging import Logger, get_logger
+from src.logging import Logger, get_logger
from src.agents.base_agent import BaseAgent
from .utils import (
diff --git a/src/agents/solve/analysis_loop/note_agent.py b/src/agents/solve/analysis_loop/note_agent.py
index be277b167..1fda7a374 100644
--- a/src/agents/solve/analysis_loop/note_agent.py
+++ b/src/agents/solve/analysis_loop/note_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
NoteAgent - Note taker
Based on new knowledge, generates or updates notes, annotates covered pain points and missing points
diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.py
index d573b1741..826ae5f13 100644
--- a/src/agents/solve/main_solver.py
+++ b/src/agents/solve/main_solver.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Main Solver - Problem-Solving System Controller
@@ -21,7 +22,8 @@ import yaml
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import get_llm_config, load_config_with_main, parse_language
+from src.services.config import load_config_with_main, parse_language
+from src.services.llm import get_llm_config
from .analysis_loop import InvestigateAgent, NoteAgent
@@ -123,16 +125,17 @@ class MainSolver:
try:
llm_config = get_llm_config()
if api_key is None:
- api_key = llm_config["api_key"]
+ api_key = llm_config.api_key
if base_url is None:
- base_url = llm_config["base_url"]
+ base_url = llm_config.base_url
# Ensure LLM config is populated in self.config for agents
if "llm" not in self.config:
self.config["llm"] = {}
# Update config with complete details (binding, model, etc.)
- self.config["llm"].update(llm_config)
+ from dataclasses import asdict
+ self.config["llm"].update(asdict(llm_config))
except ValueError as e:
raise ValueError(f"LLM config error: {e!s}")
diff --git a/src/agents/solve/solve_loop/manager_agent.py b/src/agents/solve/solve_loop/manager_agent.py
index 7892c8a47..082089f71 100644
--- a/src/agents/solve/solve_loop/manager_agent.py
+++ b/src/agents/solve/solve_loop/manager_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ManagerAgent - Manager (Refactored: directly plans step-level solution steps)
Based on user question and knowledge chain, plans solution steps
diff --git a/src/agents/solve/solve_loop/response_agent.py b/src/agents/solve/solve_loop/response_agent.py
index 54c147ea3..317316963 100644
--- a/src/agents/solve/solve_loop/response_agent.py
+++ b/src/agents/solve/solve_loop/response_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ResponseAgent - Step response generator
Based on materials in solve-chain, generates formal response for current step
diff --git a/src/agents/solve/solve_loop/tool_agent.py b/src/agents/solve/solve_loop/tool_agent.py
index 7954668c7..ab710451b 100644
--- a/src/agents/solve/solve_loop/tool_agent.py
+++ b/src/agents/solve/solve_loop/tool_agent.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
ToolAgent - Tool executor
Responsible for reading tool calls in solve-chain, actually executing tools and producing summary
diff --git a/src/agents/solve/utils/__init__.py b/src/agents/solve/utils/__init__.py
index 533d7df0f..4a1ef836a 100644
--- a/src/agents/solve/utils/__init__.py
+++ b/src/agents/solve/utils/__init__.py
@@ -13,7 +13,7 @@ project_root = Path(__file__).parent.parent.parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
-from src.core.logging import Logger, LogLevel, get_logger, reset_logger
+from src.logging import Logger, LogLevel, get_logger, reset_logger
# Backwards compatibility alias
SolveAgentLogger = Logger
diff --git a/src/agents/solve/utils/config_validator.py b/src/agents/solve/utils/config_validator.py
index 80981dee5..2397b04b3 100644
--- a/src/agents/solve/utils/config_validator.py
+++ b/src/agents/solve/utils/config_validator.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Config Validator - Configuration validator
Validates the completeness and correctness of config.yaml
@@ -276,9 +277,9 @@ def print_validation_result(is_valid: bool, errors: list[str], warnings: list[st
print("=" * 60)
if is_valid:
- print("✅ Configuration validation passed")
+ print("✓ Configuration validation passed")
else:
- print("❌ Configuration validation failed")
+ print("✗ Configuration validation failed")
print()
diff --git a/src/agents/solve/utils/display_manager.py b/src/agents/solve/utils/display_manager.py
index 19521b742..65847b1f8 100644
--- a/src/agents/solve/utils/display_manager.py
+++ b/src/agents/solve/utils/display_manager.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Display Manager - Terminal display manager
Uses rich library to implement beautiful terminal interface, including fixed header (status/statistics) and scrolling log area
@@ -119,7 +120,7 @@ class DisplayManager:
icon = "✓"
style = "green"
elif status == "running":
- icon = "…"
+ icon = "●"
style = "yellow"
elif status == "error":
icon = "✗"
diff --git a/src/agents/solve/utils/error_handler.py b/src/agents/solve/utils/error_handler.py
index ec9a7a5a6..85c62beee 100644
--- a/src/agents/solve/utils/error_handler.py
+++ b/src/agents/solve/utils/error_handler.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Error Handler - Error handling and retry mechanism
"""
@@ -238,15 +239,15 @@ if __name__ == "__main__":
try:
validate_investigate_output(test_investigate_output)
- print("✅ InvestigateAgent output validation passed")
+ print("✓ InvestigateAgent output validation passed")
except ParseError as e:
- print(f"❌ InvestigateAgent output validation failed: {e}")
+ print(f"✗ InvestigateAgent output validation failed: {e}")
# Test missing required fields
test_invalid_output = {"actions": []}
try:
validate_investigate_output(test_invalid_output)
- print("❌ Invalid output validation passed (should not happen)")
+ print("✓ Invalid output validation passed (should not happen)")
except ParseError as e:
- print(f"✅ Invalid output validation failed (expected): {e}")
+ print(f"✗ Invalid output validation failed (expected): {e}")
diff --git a/src/agents/solve/utils/json_utils.py b/src/agents/solve/utils/json_utils.py
index b7dc97f93..ec3809db4 100644
--- a/src/agents/solve/utils/json_utils.py
+++ b/src/agents/solve/utils/json_utils.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
JSON Utils - JSON parsing utilities
Specifically for extracting and parsing JSON data from LLM output,
diff --git a/src/agents/solve/utils/token_tracker.py b/src/agents/solve/utils/token_tracker.py
index 7a16b1e97..1c7d42b83 100644
--- a/src/agents/solve/utils/token_tracker.py
+++ b/src/agents/solve/utils/token_tracker.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Token Tracker - LLM Token usage and cost tracking system (Advanced)
Uses tiktoken for precise token counting, supports multiple models and more accurate cost calculation
diff --git a/src/api/README.md b/src/api/README.md
index 2cb431ccc..01163cd78 100644
--- a/src/api/README.md
+++ b/src/api/README.md
@@ -11,7 +11,7 @@ The API module is built on FastAPI and provides:
- CORS middleware for cross-origin requests
- Unified error handling and logging
-## 🏗️ Architecture
+## 🏗�?Architecture
```
api/
@@ -19,17 +19,17 @@ api/
├── main.py # FastAPI application setup
├── run_server.py # Server startup script
├── routers/ # API route modules
-│ ├── solve.py # Problem solving endpoints
-│ ├── question.py # Question generation endpoints
-│ ├── research.py # Research endpoints
-│ ├── knowledge.py # Knowledge base endpoints
-│ ├── guide.py # Guided learning endpoints
-│ ├── co_writer.py # Co-Writer endpoints
-│ ├── notebook.py # Notebook endpoints
-│ ├── ideagen.py # Idea generation endpoints
-│ ├── dashboard.py # Dashboard endpoints
-│ ├── settings.py # Settings endpoints
-│ └── system.py # System endpoints
+�? ├── solve.py # Problem solving endpoints
+�? ├── question.py # Question generation endpoints
+�? ├── research.py # Research endpoints
+�? ├── knowledge.py # Knowledge base endpoints
+�? ├── guide.py # Guided learning endpoints
+�? ├── co_writer.py # Co-Writer endpoints
+�? ├── notebook.py # Notebook endpoints
+�? ├── ideagen.py # Idea generation endpoints
+�? ├── dashboard.py # Dashboard endpoints
+�? ├── settings.py # Settings endpoints
+�? └── system.py # System endpoints
└── utils/ # API utilities
├── history.py # Activity history management
├── log_interceptor.py # Log interception for streaming
@@ -218,7 +218,7 @@ python src/api/main.py
- **Tools**: `src/tools/` - Tool implementations
- **Frontend**: `web/` - Next.js frontend
-## 🛠️ Development
+## 🛠�?Development
### Adding a New Endpoint
@@ -263,7 +263,7 @@ except Exception as e:
API endpoints use the core logging system:
```python
-from src.core.logging import get_logger
+from src.logging import get_logger
logger = get_logger("MyAPI")
```
diff --git a/src/api/main.py b/src/api/main.py
index 449495623..43d77b28e 100644
--- a/src/api/main.py
+++ b/src/api/main.py
@@ -7,6 +7,7 @@ from fastapi.staticfiles import StaticFiles
from src.api.routers import (
agent_config,
+ chat,
co_writer,
dashboard,
guide,
@@ -20,7 +21,7 @@ from src.api.routers import (
solve,
system,
)
-from src.core.logging import get_logger
+from src.logging import get_logger
logger = get_logger("API")
@@ -58,7 +59,7 @@ user_dir = project_root / "data" / "user"
# Initialize user directories on startup
try:
- from src.core.setup import init_user_directories
+ from src.services.setup import init_user_directories
init_user_directories(project_root)
except Exception:
@@ -70,6 +71,7 @@ app.mount("/api/outputs", StaticFiles(directory=str(user_dir)), name="outputs")
# Include routers
app.include_router(solve.router, prefix="/api/v1", tags=["solve"])
+app.include_router(chat.router, prefix="/api/v1", tags=["chat"])
app.include_router(question.router, prefix="/api/v1/question", tags=["question"])
app.include_router(research.router, prefix="/api/v1/research", tags=["research"])
app.include_router(knowledge.router, prefix="/api/v1/knowledge", tags=["knowledge"])
@@ -104,7 +106,7 @@ if __name__ == "__main__":
sys.path.insert(0, str(project_root))
# Get port from configuration
- from src.core.setup import get_backend_port
+ from src.services.setup import get_backend_port
backend_port = get_backend_port(project_root)
diff --git a/src/api/routers/chat.py b/src/api/routers/chat.py
new file mode 100644
index 000000000..bf978f1a0
--- /dev/null
+++ b/src/api/routers/chat.py
@@ -0,0 +1,271 @@
+"""
+Chat API Router
+================
+
+WebSocket endpoint for lightweight chat with session management.
+REST endpoints for session operations.
+"""
+
+from pathlib import Path
+import sys
+
+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+
+_project_root = Path(__file__).parent.parent.parent.parent
+sys.path.insert(0, str(_project_root))
+
+from src.agents.chat import ChatAgent, SessionManager
+from src.services.config import load_config_with_main
+from src.logging import get_logger
+
+# Initialize logger
+project_root = Path(__file__).parent.parent.parent.parent
+config = load_config_with_main("solve_config.yaml", project_root)
+log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
+ "log_dir"
+)
+logger = get_logger("ChatAPI", level="INFO", log_dir=log_dir)
+
+router = APIRouter()
+
+# Initialize session manager
+session_manager = SessionManager()
+
+
+# =============================================================================
+# REST Endpoints for Session Management
+# =============================================================================
+
+
[email protected]("/chat/sessions")
+async def list_sessions(limit: int = 20):
+ """
+ List recent chat sessions.
+
+ Args:
+ limit: Maximum number of sessions to return
+
+ Returns:
+ List of session summaries
+ """
+ return session_manager.list_sessions(limit=limit, include_messages=False)
+
+
[email protected]("/chat/sessions/{session_id}")
+async def get_session(session_id: str):
+ """
+ Get a specific chat session with full message history.
+
+ Args:
+ session_id: Session identifier
+
+ Returns:
+ Complete session data including messages
+ """
+ session = session_manager.get_session(session_id)
+ if not session:
+ raise HTTPException(status_code=404, detail="Session not found")
+ return session
+
+
[email protected]("/chat/sessions/{session_id}")
+async def delete_session(session_id: str):
+ """
+ Delete a chat session.
+
+ Args:
+ session_id: Session identifier
+
+ Returns:
+ Success message
+ """
+ if session_manager.delete_session(session_id):
+ return {"status": "deleted", "session_id": session_id}
+ raise HTTPException(status_code=404, detail="Session not found")
+
+
+# =============================================================================
+# WebSocket Endpoint for Chat
+# =============================================================================
+
+
+async def websocket_chat(websocket: WebSocket):
+ """
+ WebSocket endpoint for chat with session and context management.
+
+ Message format:
+ {
+ "message": str, # User message
+ "session_id": str | null, # Session ID (null for new session)
+ "history": [...] | null, # Optional: explicit history override
+ "kb_name": str, # Knowledge base name (for RAG)
+ "enable_rag": bool, # Enable RAG retrieval
+ "enable_web_search": bool # Enable Web Search
+ }
+
+ Response format:
+ - {"type": "session", "session_id": str} # Session ID (new or existing)
+ - {"type": "status", "stage": str, "message": str} # Status updates
+ - {"type": "stream", "content": str} # Streaming response chunks
+ - {"type": "sources", "rag": list, "web": list} # Source citations
+ - {"type": "result", "content": str} # Final complete response
+ - {"type": "error", "message": str} # Error message
+ """
+ await websocket.accept()
+
+ # Get system language for agent
+ language = config.get("system", {}).get("language", "en")
+
+ try:
+ while True:
+ # Receive message
+ data = await websocket.receive_json()
+ message = data.get("message", "").strip()
+ session_id = data.get("session_id")
+ explicit_history = data.get("history") # Optional override
+ kb_name = data.get("kb_name", "")
+ enable_rag = data.get("enable_rag", False)
+ enable_web_search = data.get("enable_web_search", False)
+
+ if not message:
+ await websocket.send_json(
+ {"type": "error", "message": "Message is required"}
+ )
+ continue
+
+ logger.info(
+ f"Chat request: session={session_id}, "
+ f"message={message[:50]}..., rag={enable_rag}, web={enable_web_search}"
+ )
+
+ try:
+ # Get or create session
+ if session_id:
+ session = session_manager.get_session(session_id)
+ if not session:
+ # Session not found, create new one
+ session = session_manager.create_session(
+ title=message[:50] + ("..." if len(message) > 50 else ""),
+ settings={
+ "kb_name": kb_name,
+ "enable_rag": enable_rag,
+ "enable_web_search": enable_web_search,
+ },
+ )
+ session_id = session["session_id"]
+ else:
+ # Create new session
+ session = session_manager.create_session(
+ title=message[:50] + ("..." if len(message) > 50 else ""),
+ settings={
+ "kb_name": kb_name,
+ "enable_rag": enable_rag,
+ "enable_web_search": enable_web_search,
+ },
+ )
+ session_id = session["session_id"]
+
+ # Send session ID to frontend
+ await websocket.send_json({
+ "type": "session",
+ "session_id": session_id,
+ })
+
+ # Build history from session or explicit override
+ if explicit_history is not None:
+ history = explicit_history
+ else:
+ # Get history from session messages
+ history = [
+ {"role": msg["role"], "content": msg["content"]}
+ for msg in session.get("messages", [])
+ ]
+
+ # Add user message to session
+ session_manager.add_message(
+ session_id=session_id,
+ role="user",
+ content=message,
+ )
+
+ # Initialize ChatAgent
+ agent = ChatAgent(language=language, config=config)
+
+ # Send status updates
+ if enable_rag and kb_name:
+ await websocket.send_json({
+ "type": "status",
+ "stage": "rag",
+ "message": f"Searching knowledge base: {kb_name}...",
+ })
+
+ if enable_web_search:
+ await websocket.send_json({
+ "type": "status",
+ "stage": "web",
+ "message": "Searching the web...",
+ })
+
+ await websocket.send_json({
+ "type": "status",
+ "stage": "generating",
+ "message": "Generating response...",
+ })
+
+ # Process with streaming
+ full_response = ""
+ sources = {"rag": [], "web": []}
+
+ stream_generator = await agent.process(
+ message=message,
+ history=history,
+ kb_name=kb_name,
+ enable_rag=enable_rag,
+ enable_web_search=enable_web_search,
+ stream=True,
+ )
+
+ async for chunk_data in stream_generator:
+ if chunk_data["type"] == "chunk":
+ await websocket.send_json({
+ "type": "stream",
+ "content": chunk_data["content"],
+ })
+ full_response += chunk_data["content"]
+ elif chunk_data["type"] == "complete":
+ full_response = chunk_data["response"]
+ sources = chunk_data.get("sources", {"rag": [], "web": []})
+
+ # Send sources if any
+ if sources.get("rag") or sources.get("web"):
+ await websocket.send_json({"type": "sources", **sources})
+
+ # Send final result
+ await websocket.send_json({
+ "type": "result",
+ "content": full_response,
+ })
+
+ # Save assistant message to session
+ session_manager.add_message(
+ session_id=session_id,
+ role="assistant",
+ content=full_response,
+ sources=sources if (sources.get("rag") or sources.get("web")) else None,
+ )
+
+ logger.info(f"Chat completed: session={session_id}, {len(full_response)} chars")
+
+ except Exception as e:
+ logger.error(f"Chat processing error: {e}")
+ await websocket.send_json({"type": "error", "message": str(e)})
+
+ except WebSocketDisconnect:
+ logger.debug("Client disconnected from chat")
+ except Exception as e:
+ logger.error(f"WebSocket error: {e}")
+ try:
+ await websocket.send_json({"type": "error", "message": str(e)})
+ except Exception:
+ pass
diff --git a/src/api/routers/co_writer.py b/src/api/routers/co_writer.py
index fbf51a004..d1ce86a4b 100644
--- a/src/api/routers/co_writer.py
+++ b/src/api/routers/co_writer.py
@@ -21,8 +21,9 @@ from src.agents.co_writer.edit_agent import (
print_stats,
)
from src.agents.co_writer.narrator_agent import NarratorAgent
-from src.core.core import get_tts_config, load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.services.tts import get_tts_config
+from src.logging import get_logger
router = APIRouter()
diff --git a/src/api/routers/guide.py b/src/api/routers/guide.py
index 830e4440a..480e12a7a 100644
--- a/src/api/routers/guide.py
+++ b/src/api/routers/guide.py
@@ -19,8 +19,9 @@ from src.agents.base_agent import BaseAgent
from src.agents.guide.guide_manager import GuideManager
from src.api.utils.notebook_manager import notebook_manager
from src.api.utils.task_id_manager import TaskIDManager
-from src.core.core import get_llm_config, load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.services.llm import get_llm_config
+from src.logging import get_logger
router = APIRouter()
@@ -68,8 +69,8 @@ def get_guide_manager():
"""Get GuideManager instance"""
try:
llm_config = get_llm_config()
- api_key = llm_config["api_key"]
- base_url = llm_config["base_url"]
+ api_key = llm_config.api_key
+ base_url = llm_config.base_url
except Exception as e:
raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
diff --git a/src/api/routers/ideagen.py b/src/api/routers/ideagen.py
index 36221a2e7..69efbfe96 100644
--- a/src/api/routers/ideagen.py
+++ b/src/api/routers/ideagen.py
@@ -20,8 +20,9 @@ from src.agents.ideagen.idea_generation_workflow import IdeaGenerationWorkflow
from src.agents.ideagen.material_organizer_agent import MaterialOrganizerAgent
from src.api.utils.notebook_manager import NotebookManager
from src.api.utils.task_id_manager import TaskIDManager
-from src.core.core import get_llm_config, load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.services.llm import get_llm_config
+from src.logging import get_logger
router = APIRouter()
@@ -190,9 +191,9 @@ async def websocket_ideagen(websocket: WebSocket):
)
organizer = MaterialOrganizerAgent(
- api_key=llm_config["api_key"],
- base_url=llm_config["base_url"],
- model=llm_config["model"],
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ model=llm_config.model,
)
knowledge_points = await organizer.process(
@@ -230,9 +231,9 @@ async def websocket_ideagen(websocket: WebSocket):
)
workflow = IdeaGenerationWorkflow(
- api_key=llm_config["api_key"],
- base_url=llm_config["base_url"],
- model=llm_config["model"],
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ model=llm_config.model,
progress_callback=None, # We manually manage status here
)
diff --git a/src/api/routers/knowledge.py b/src/api/routers/knowledge.py
index 4cd33807d..98fd8ea4b 100644
--- a/src/api/routers/knowledge.py
+++ b/src/api/routers/knowledge.py
@@ -33,8 +33,9 @@ from src.knowledge.progress_tracker import ProgressStage, ProgressTracker
_project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(_project_root))
-from src.core.core import get_llm_config, load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.services.llm import get_llm_config
+from src.logging import get_logger
# Initialize logger with config
project_root = Path(__file__).parent.parent.parent.parent
@@ -293,8 +294,8 @@ async def upload_files(
try:
llm_config = get_llm_config()
- api_key = llm_config["api_key"]
- base_url = llm_config["base_url"]
+ api_key = llm_config.api_key
+ base_url = llm_config.base_url
except ValueError as e:
raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
@@ -340,8 +341,8 @@ async def create_knowledge_base(
try:
llm_config = get_llm_config()
- api_key = llm_config["api_key"]
- base_url = llm_config["base_url"]
+ api_key = llm_config.api_key
+ base_url = llm_config.base_url
except ValueError as e:
raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
diff --git a/src/api/routers/llm_provider.py b/src/api/routers/llm_provider.py
index 8926d8d3d..8563eb1fe 100644
--- a/src/api/routers/llm_provider.py
+++ b/src/api/routers/llm_provider.py
@@ -4,7 +4,7 @@ from fastapi import APIRouter, HTTPException
from lightrag.llm.openai import openai_complete_if_cache
from pydantic import BaseModel
-from src.core.llm_provider import LLMProvider, provider_manager
+from src.services.llm.provider import LLMProvider, provider_manager
router = APIRouter()
diff --git a/src/api/routers/question.py b/src/api/routers/question.py
index 4514bdf6b..5d7f80575 100644
--- a/src/api/routers/question.py
+++ b/src/api/routers/question.py
@@ -18,8 +18,8 @@ from src.api.utils.task_id_manager import TaskIDManager
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.core import load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.logging import get_logger
# Setup module logger with unified logging system (from config)
project_root = Path(__file__).parent.parent.parent.parent
diff --git a/src/api/routers/research.py b/src/api/routers/research.py
index 25233266a..c8ff8ce80 100644
--- a/src/api/routers/research.py
+++ b/src/api/routers/research.py
@@ -12,8 +12,9 @@ from src.agents.research.agents import RephraseAgent
from src.agents.research.research_pipeline import ResearchPipeline
from src.api.utils.history import ActivityType, history_manager
from src.api.utils.task_id_manager import TaskIDManager
-from src.core.core import get_llm_config, load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.services.llm import get_llm_config
+from src.logging import get_logger
# Force stdout to use utf-8 to prevent encoding errors with emojis on Windows
if sys.platform == "win32":
@@ -49,8 +50,8 @@ async def optimize_topic(request: OptimizeRequest):
# Inject API keys
try:
llm_config = get_llm_config()
- api_key = llm_config["api_key"]
- base_url = llm_config["base_url"]
+ api_key = llm_config.api_key
+ base_url = llm_config.base_url
except Exception as e:
return {"error": f"LLM config error: {e!s}"}
@@ -248,8 +249,8 @@ async def websocket_research_run(websocket: WebSocket):
# Inject API keys from env if not in config
try:
llm_config = get_llm_config()
- api_key = llm_config["api_key"]
- base_url = llm_config["base_url"]
+ api_key = llm_config.api_key
+ base_url = llm_config.base_url
except ValueError as e:
await websocket.send_json({"error": f"LLM configuration error: {e!s}"})
await websocket.close()
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.py
index 9bb44fa04..c768e0377 100644
--- a/src/api/routers/settings.py
+++ b/src/api/routers/settings.py
@@ -11,7 +11,9 @@ from typing import Any, Dict, Literal
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
-from src.core.core import get_embedding_config, get_llm_config, get_tts_config
+from src.services.llm import get_llm_config
+from src.services.embedding import get_embedding_config
+from src.services.tts import get_tts_config
from src.utils.config_manager import ConfigManager
router = APIRouter()
@@ -606,7 +608,7 @@ async def test_env_config():
# Test LLM configuration
try:
llm_config = get_llm_config()
- results["llm"]["model"] = llm_config.get("model")
+ results["llm"]["model"] = llm_config.model
results["llm"]["status"] = "configured"
except ValueError as e:
results["llm"]["status"] = "not_configured"
@@ -618,7 +620,7 @@ async def test_env_config():
# Test Embedding configuration
try:
embedding_config = get_embedding_config()
- results["embedding"]["model"] = embedding_config.get("model")
+ results["embedding"]["model"] = embedding_config.model
results["embedding"]["status"] = "configured"
except ValueError as e:
results["embedding"]["status"] = "not_configured"
diff --git a/src/api/routers/solve.py b/src/api/routers/solve.py
index c39ff6be1..1700330d8 100644
--- a/src/api/routers/solve.py
+++ b/src/api/routers/solve.py
@@ -20,8 +20,8 @@ from src.api.utils.task_id_manager import TaskIDManager
_project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(_project_root))
-from src.core.core import load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.logging import get_logger
# Initialize logger with config
project_root = Path(__file__).parent.parent.parent.parent
diff --git a/src/api/routers/system.py b/src/api/routers/system.py
index baaea2b6d..cbe5d6bfc 100644
--- a/src/api/routers/system.py
+++ b/src/api/routers/system.py
@@ -10,12 +10,9 @@ from fastapi import APIRouter
from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from pydantic import BaseModel
-from src.core.core import (
- get_embedding_config,
- get_llm_config,
- get_token_limit_kwargs,
- get_tts_config,
-)
+from src.services.llm import get_llm_config, get_token_limit_kwargs
+from src.services.embedding import get_embedding_config
+from src.services.tts import get_tts_config
router = APIRouter()
@@ -49,7 +46,7 @@ async def get_system_status():
# Check LLM configuration
try:
llm_config = get_llm_config()
- result["llm"]["model"] = llm_config.get("model")
+ result["llm"]["model"] = llm_config.model
result["llm"]["status"] = "configured"
except ValueError as e:
result["llm"]["status"] = "not_configured"
@@ -61,7 +58,7 @@ async def get_system_status():
# Check Embeddings configuration
try:
embedding_config = get_embedding_config()
- result["embeddings"]["model"] = embedding_config.get("model")
+ result["embeddings"]["model"] = embedding_config.model
result["embeddings"]["status"] = "configured"
except ValueError as e:
result["embeddings"]["status"] = "not_configured"
@@ -97,8 +94,8 @@ async def test_llm_connection():
try:
llm_config = get_llm_config()
- model = llm_config["model"]
- base_url = llm_config["base_url"].rstrip("/")
+ model = llm_config.model
+ base_url = llm_config.base_url.rstrip("/")
# Sanitize Base URL (remove /chat/completions suffix if present)
for suffix in ["/chat/completions", "/completions"]:
@@ -106,7 +103,7 @@ async def test_llm_connection():
base_url = base_url[: -len(suffix)]
# Handle API Key (inject dummy if missing for local LLMs)
- api_key = llm_config["api_key"]
+ api_key = llm_config.api_key
if not api_key:
api_key = "sk-no-key-required"
@@ -163,14 +160,14 @@ async def test_embeddings_connection():
try:
embedding_config = get_embedding_config()
- model = embedding_config["model"]
- base_url = embedding_config["base_url"].rstrip("/")
+ model = embedding_config.model
+ base_url = embedding_config.base_url.rstrip("/")
# Sanitize Base URL (remove /embeddings suffix if present, though less common)
# OpenAI client handles /embeddings automatically
# Handle API Key
- api_key = embedding_config["api_key"]
+ api_key = embedding_config.api_key
if not api_key:
api_key = "sk-no-key-required"
diff --git a/src/api/run_server.py b/src/api/run_server.py
index c1d44afdc..23e3770a9 100644
--- a/src/api/run_server.py
+++ b/src/api/run_server.py
@@ -30,7 +30,7 @@ if __name__ == "__main__":
sys.path.insert(0, str(project_root))
# Get port from configuration
- from src.core.setup import get_backend_port
+ from src.services.setup import get_backend_port
backend_port = get_backend_port(project_root)
diff --git a/src/api/utils/history.py b/src/api/utils/history.py
index d56c2a7a3..f011e897e 100644
--- a/src/api/utils/history.py
+++ b/src/api/utils/history.py
@@ -8,6 +8,7 @@ class ActivityType(str, Enum):
SOLVE = "solve"
QUESTION = "question"
RESEARCH = "research"
+ CHAT = "chat"
class HistoryManager:
diff --git a/src/api/utils/log_interceptor.py b/src/api/utils/log_interceptor.py
index 6380b9cd2..0cb7df4f4 100644
--- a/src/api/utils/log_interceptor.py
+++ b/src/api/utils/log_interceptor.py
@@ -6,16 +6,7 @@ Re-exports handlers from the unified logging system.
Kept for backwards compatibility.
"""
-from pathlib import Path
-import sys
-
-# Add project root to path
-project_root = Path(__file__).parent.parent.parent.parent
-if str(project_root) not in sys.path:
- sys.path.insert(0, str(project_root))
-
-# Re-export from unified logging system
-from src.core.logging.handlers import (
+from src.logging.handlers import (
JSONFileHandler,
LogInterceptor,
WebSocketLogHandler,
diff --git a/src/core/README.md b/src/core/README.md
deleted file mode 100644
index a7164a1a0..000000000
--- a/src/core/README.md
+++ /dev/null
@@ -1,293 +0,0 @@
-# Core Module
-
-The Core module provides essential system services including configuration management, logging, and system initialization.
-
-## 📋 Overview
-
-The Core module is the foundation of the DeepTutor system, providing:
-- Unified configuration management (environment variables + YAML)
-- Comprehensive logging system
-- System initialization and setup
-- Path management utilities
-
-## 🏗️ Architecture
-
-```
-core/
-├── __init__.py
-├── core.py # Configuration management
-├── setup.py # System initialization
-└── logging/ # Logging system
- ├── __init__.py
- ├── logger.py # Logger implementation
- ├── handlers.py # Log handlers
- ├── llm_stats.py # LLM usage statistics
- ├── log_forwarder.py # Log forwarding
- ├── lightrag_forward.py # LightRAG log forwarding
- └── terminal_display.py # Terminal display utilities
-```
-
-## 🔧 Components
-
-### core.py
-
-**Configuration Management**
-
-Provides unified configuration loading from environment variables and YAML files.
-
-**Key Functions**:
-
-#### `get_llm_config() -> dict`
-Returns LLM configuration from environment variables:
-```python
-{
- "binding": "openai",
- "model": "gpt-4o",
- "api_key": "...",
- "base_url": "https://api.openai.com/v1"
-}
-```
-
-#### `get_tts_config() -> dict`
-Returns TTS configuration from environment variables:
-```python
-{
- "model": "sambert-zhichu-v1",
- "api_key": "...",
- "base_url": "https://dashscope.aliyuncs.com/api/v1",
- "voice": "Cherry"
-}
-```
-
-#### `get_embedding_config() -> dict`
-Returns embedding model configuration from environment variables.
-
-#### `load_config_with_main(config_file: str, project_root: Path) -> dict`
-Loads configuration from `main.yaml`:
-1. Loads `config/main.yaml` as configuration
-2. Returns the configuration dictionary
-
-**Usage**:
-```python
-from src.core.core import load_config_with_main
-from pathlib import Path
-
-config = load_config_with_main("main.yaml", Path(__file__).parent.parent.parent)
-```
-
-#### `get_agent_params(module_name: str) -> dict`
-Gets agent parameters (temperature, max_tokens) from `agents.yaml`:
-
-**Usage**:
-```python
-from src.core.core import get_agent_params
-
-params = get_agent_params("solve")
-# Returns: {"temperature": 0.3, "max_tokens": 8192}
-```
-
-### setup.py
-
-**System Initialization**
-
-Handles system setup and initialization tasks.
-
-**Key Functions**:
-
-#### `init_user_directories(project_root: Optional[Path] = None) -> None`
-Initializes all required user data directories:
-- `data/user/solve/`
-- `data/user/question/`
-- `data/user/research/`
-- `data/user/guide/`
-- `data/user/notebook/`
-- `data/user/co-writer/`
-- `data/user/logs/`
-- `data/user/run_code_workspace/`
-
-#### `get_backend_port(project_root: Optional[Path] = None) -> int`
-Gets backend port from configuration.
-
-#### `get_frontend_port(project_root: Optional[Path] = None) -> int`
-Gets frontend port from configuration.
-
-### logging/
-
-**Comprehensive Logging System**
-
-#### logger.py
-
-**Main Logger Implementation**
-
-Provides `get_logger()` function for creating loggers:
-
-```python
-from src.core.logging import get_logger
-
-logger = get_logger("MyModule", level="INFO", log_dir="./logs")
-```
-
-**Features**:
-- File and console output
-- Configurable log levels
-- Automatic log rotation
-- Module-specific loggers
-
-#### llm_stats.py
-
-**LLM Usage Statistics**
-
-Tracks LLM API usage:
-- Token counts (input/output)
-- API calls
-- Cost estimation
-
-**Usage**:
-```python
-from src.core.logging import LLMStats
-
-stats = LLMStats(module_name="MyModule")
-stats.add_call(model="gpt-4o", system_prompt="...", user_prompt="...", response="...")
-stats.print_summary()
-```
-
-#### log_forwarder.py
-
-**Log Forwarding**
-
-Forwards logs from external libraries (e.g., LightRAG) to the main logging system.
-
-#### handlers.py
-
-**Custom Log Handlers**
-
-Custom handlers for file and console output.
-
-## ⚙️ Configuration
-
-### Environment Variables
-
-Required in `.env` or `DeepTutor.env`:
-
-```bash
-# LLM Configuration
-LLM_BINDING_API_KEY=your_api_key
-LLM_BINDING_HOST=https://api.openai.com/v1
-LLM_MODEL=gpt-4o
-
-# TTS Configuration (optional)
-TTS_API_KEY=your_tts_key
-TTS_URL=https://dashscope.aliyuncs.com/api/v1
-TTS_MODEL=sambert-zhichu-v1
-
-# Embedding Configuration (optional)
-EMBEDDING_BINDING_API_KEY=your_embedding_key
-EMBEDDING_BINDING_HOST=https://api.openai.com/v1
-EMBEDDING_MODEL=text-embedding-3-large
-```
-
-### YAML Configuration
-
-Configuration files in `config/`:
-- `main.yaml` - Main system configuration
-- `solve_config.yaml` - Solve module configuration
-- `research_config.yaml` - Research module configuration
-- etc.
-
-## 📝 Usage Examples
-
-### Loading Configuration
-
-```python
-from src.core.core import load_config_with_main
-from pathlib import Path
-
-project_root = Path(__file__).parent.parent.parent
-config = load_config_with_main("solve_config.yaml", project_root)
-
-# Access configuration
-output_dir = config.get('paths', {}).get('user_data_dir')
-max_iterations = config.get('system', {}).get('max_analysis_iterations', 5)
-```
-
-### Getting LLM Config
-
-```python
-from src.core.core import get_llm_config
-
-llm_config = get_llm_config()
-api_key = llm_config["api_key"]
-base_url = llm_config["base_url"]
-model = llm_config["model"]
-```
-
-### Using Logger
-
-```python
-from src.core.logging import get_logger
-
-logger = get_logger("MyModule", level="DEBUG")
-logger.info("Information message")
-logger.error("Error message")
-```
-
-### Tracking LLM Usage
-
-```python
-from src.core.logging import LLMStats
-
-stats = LLMStats(module_name="MyModule")
-# After LLM call
-stats.add_call(
- model="gpt-4o",
- system_prompt="You are a helpful assistant.",
- user_prompt="What is AI?",
- response="AI is..."
-)
-# Print summary
-stats.print_summary()
-```
-
-### Initializing System
-
-```python
-from src.core.setup import init_user_directories
-from pathlib import Path
-
-project_root = Path(__file__).parent.parent.parent
-init_user_directories(project_root)
-```
-
-## 🔗 Related Modules
-
-- **Config Files**: `config/` - YAML configuration files
-- **API**: `src/api/` - Uses core for configuration
-- **Agents**: `src/agents/` - Use core for logging and config
-
-## 🛠️ Development
-
-### Adding New Configuration
-
-1. Add to environment variables if it's a secret or API key
-2. Add to `main.yaml` if it's a system-wide setting
-3. Add to module config if it's module-specific
-4. Update `core.py` if needed for loading
-
-### Adding New Logger
-
-```python
-from src.core.logging import get_logger
-
-logger = get_logger("NewModule", level="INFO", log_dir="./logs")
-```
-
-### Custom Log Handler
-
-Extend `handlers.py` to add custom handlers.
-
-## ⚠️ Notes
-
-1. **Configuration Priority**: Environment variables override YAML config
-2. **Path Resolution**: Always use `load_config_with_main()` for proper path resolution
-3. **Logging**: Use module-specific loggers for better organization
-4. **Statistics**: LLM stats are tracked per module
diff --git a/src/core/__init__.py b/src/core/__init__.py
deleted file mode 100644
index f1a27bb75..000000000
--- a/src/core/__init__.py
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/usr/bin/env python
-"""
-Core module - provides unified configuration, logging, and prompt management.
-"""
-
-from .core import (
- PROJECT_ROOT,
- get_agent_params,
- get_embedding_config,
- get_llm_config,
- get_path_from_config,
- get_tts_config,
- load_config_with_main,
- parse_language,
-)
-from .prompt_manager import PromptManager, get_prompt_manager
-
-__all__ = [
- # Project root
- "PROJECT_ROOT",
- # Environment configuration
- "get_llm_config",
- "get_embedding_config",
- "get_tts_config",
- # Agent parameters
- "get_agent_params",
- # YAML configuration
- "load_config_with_main",
- "get_path_from_config",
- # Language utilities
- "parse_language",
- # Prompt management
- "PromptManager",
- "get_prompt_manager",
-]
diff --git a/src/core/core.py b/src/core/core.py
deleted file mode 100644
index f606b8c61..000000000
--- a/src/core/core.py
+++ /dev/null
@@ -1,459 +0,0 @@
-#!/usr/bin/env python
-"""
-Unified Configuration Management
-Combines environment variable configuration and YAML configuration loading.
-"""
-
-import os
-from pathlib import Path
-import re
-from typing import Any
-
-from dotenv import load_dotenv
-import yaml
-
-# PROJECT_ROOT points to the actual project root directory (DeepTutor/)
-# Path(__file__) = src/core/core.py
-# .parent = src/core/
-# .parent.parent = src/
-# .parent.parent.parent = DeepTutor/ (project root)
-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
-
-# Load .env from project root directory
-# DeepTutor.env takes precedence, then fallback to .env
-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)
-load_dotenv(PROJECT_ROOT / ".env", override=False)
-
-
-# ============================================================================
-# Environment Variable Configuration (from config.py)
-# ============================================================================
-
-
-def _to_int(value: str | None, default: int) -> int:
- """Convert environment variable to int, fallback to default value on failure."""
- try:
- return int(value) if value is not None else default
- except (TypeError, ValueError):
- return default
-
-
-def _strip_value(value: str | None) -> str | None:
- """Remove leading/trailing whitespace and quotes from string."""
- if value is None:
- return None
- return value.strip().strip("\"'")
-
-
-def get_llm_config() -> dict:
- """
- Return complete environment configuration for LLM.
-
- Priority:
- 1. Active provider from llm_providers.json
- 2. Environment variables (.env)
-
- Returns:
- dict: Dictionary containing the following keys:
- - binding: LLM service provider
- - model: LLM model name
- - api_key: LLM API key
- - base_url: LLM API endpoint URL
-
- Raises:
- ValueError: If required configuration is missing
- """
- # 1. Try to get active provider from new system
- try:
- from src.core.llm_provider import provider_manager
-
- active_provider = provider_manager.get_active_provider()
-
- if active_provider:
- # Map provider fields to config format
- return {
- "binding": active_provider.binding,
- "model": active_provider.model,
- "api_key": active_provider.api_key,
- "base_url": active_provider.base_url,
- }
- except Exception as e:
- print(f"⚠️ Failed to load active provider: {e}")
-
- # 2. Fallback to environment variables
- binding = _strip_value(os.getenv("LLM_BINDING", "openai"))
- model = _strip_value(os.getenv("LLM_MODEL"))
- api_key = _strip_value(os.getenv("LLM_BINDING_API_KEY"))
- base_url = _strip_value(os.getenv("LLM_BINDING_HOST"))
-
- # Validate required configuration
- if not model:
- raise ValueError(
- "Error: LLM_MODEL not set, please configure it in .env file or activate a provider"
- )
-
- # Check if API key is required (default to true for security/backward compatibility)
- requires_key = os.getenv("LLM_API_KEY_REQUIRED", "true").lower() == "true"
-
- if requires_key and not api_key:
- raise ValueError(
- "Error: LLM_BINDING_API_KEY not set, please configure it in .env file or activate a provider"
- )
- if not base_url:
- raise ValueError(
- "Error: LLM_BINDING_HOST not set, please configure it in .env file or activate a provider"
- )
-
- return {
- "binding": binding,
- "model": model,
- "api_key": api_key,
- "base_url": base_url,
- }
-
-
-def get_tts_config() -> dict:
- """
- Return complete environment configuration for TTS (Text-to-Speech).
-
- Returns:
- dict: Dictionary containing the following keys:
- - model: TTS model name
- - api_key: TTS API key
- - base_url: TTS API endpoint URL
- - voice: Default voice character
-
- Raises:
- ValueError: If required configuration is missing
- """
- model = _strip_value(os.getenv("TTS_MODEL"))
- api_key = _strip_value(os.getenv("TTS_API_KEY"))
- base_url = _strip_value(os.getenv("TTS_URL"))
- voice = _strip_value(os.getenv("TTS_VOICE", "alloy"))
-
- # Validate required configuration
- if not model:
- raise ValueError(
- "Error: TTS_MODEL not set, please configure it in .env file (e.g., tts-1 or tts-1-hd)"
- )
- if not api_key:
- raise ValueError("Error: TTS_API_KEY not set, please configure it in .env file")
- if not base_url:
- raise ValueError(
- "Error: TTS_URL not set, please configure it in .env file (e.g., https://api.openai.com/v1)"
- )
-
- return {
- "model": model,
- "api_key": api_key,
- "base_url": base_url,
- "voice": voice,
- }
-
-
-def get_agent_params(module_name: str) -> dict:
- """
- Get agent parameters (temperature, max_tokens) for a specific module.
-
- This function loads parameters from config/agents.yaml which serves as the
- SINGLE source of truth for all agent temperature and max_tokens settings.
-
- Args:
- module_name: Module name, one of:
- - "guide": Guide module agents
- - "solve": Solve module agents
- - "research": Research module agents
- - "question": Question module agents
- - "ideagen": IdeaGen module agents
- - "co_writer": CoWriter module agents
- - "narrator": Narrator agent (independent, for TTS)
-
- Returns:
- dict: Dictionary containing:
- - temperature: float, default 0.5
- - max_tokens: int, default 4096
-
- Example:
- >>> params = get_agent_params("guide")
- >>> params["temperature"] # 0.5
- >>> params["max_tokens"] # 8192
- """
- # Default values
- defaults = {
- "temperature": 0.5,
- "max_tokens": 4096,
- }
-
- # Try to load from agents.yaml
- try:
- # PROJECT_ROOT is the project root directory, so config is at PROJECT_ROOT/config/
- config_path = PROJECT_ROOT / "config" / "agents.yaml"
-
- if config_path.exists():
- with open(config_path, encoding="utf-8") as f:
- agents_config = yaml.safe_load(f) or {}
-
- if module_name in agents_config:
- module_config = agents_config[module_name]
- return {
- "temperature": module_config.get("temperature", defaults["temperature"]),
- "max_tokens": module_config.get("max_tokens", defaults["max_tokens"]),
- }
- except Exception as e:
- print(f"⚠️ Failed to load agents.yaml: {e}, using defaults")
-
- return defaults
-
-
-def uses_max_completion_tokens(model: str) -> bool:
- """
- Check if the model uses max_completion_tokens instead of max_tokens.
-
- Newer OpenAI models (o1, o3, gpt-4o, gpt-5.x, etc.) require max_completion_tokens
- while older models use max_tokens.
-
- Args:
- model: The model name
-
- Returns:
- True if the model requires max_completion_tokens, False otherwise
- """
- model_lower = model.lower()
-
- # Models that require max_completion_tokens:
- # - o1, o3 series (reasoning models)
- # - gpt-4o series
- # - gpt-5.x and later
- patterns = [
- r"^o[13]", # o1, o3 models
- r"^gpt-4o", # gpt-4o models
- r"^gpt-[5-9]", # gpt-5.x and later
- r"^gpt-\d{2,}", # gpt-10+ (future proofing)
- ]
-
- for pattern in patterns:
- if re.match(pattern, model_lower):
- return True
-
- return False
-
-
-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 name
- max_tokens: The desired token limit
-
- Returns:
- 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}
- return {"max_tokens": max_tokens}
-
-
-def get_embedding_config() -> dict:
- """
- Return complete environment configuration for embedding models.
-
- Returns:
- dict: Dictionary containing the following keys:
- - binding: Embedding service provider
- - model: Embedding model name
- - api_key: Embedding API key
- - base_url: Embedding API endpoint URL
- - dim: Embedding dimension
- - max_tokens: Maximum tokens for embedding
-
- Raises:
- ValueError: If required configuration is missing
- """
- binding = _strip_value(os.getenv("EMBEDDING_BINDING", "openai"))
- model = _strip_value(os.getenv("EMBEDDING_MODEL"))
- api_key = _strip_value(os.getenv("EMBEDDING_BINDING_API_KEY"))
- base_url = _strip_value(os.getenv("EMBEDDING_BINDING_HOST"))
-
- # Strict mode: All model configuration must come from .env, no automatic fallback or default inference
- if not model:
- raise ValueError("Error: EMBEDDING_MODEL not set, please configure it in .env file")
-
- # Check if API key is required (default to true for security/backward compatibility)
- requires_key = os.getenv("EMBEDDING_API_KEY_REQUIRED", "true").lower() == "true"
-
- if requires_key and not api_key:
- raise ValueError(
- "Error: EMBEDDING_BINDING_API_KEY not set, please configure it in .env file"
- )
- if not base_url:
- raise ValueError("Error: EMBEDDING_BINDING_HOST not set, please configure it in .env file")
-
- # Get optional configuration
- dim = _to_int(_strip_value(os.getenv("EMBEDDING_DIM")), 3072)
- max_tokens = _to_int(_strip_value(os.getenv("EMBEDDING_MAX_TOKENS")), 8192)
-
- return {
- "binding": binding,
- "model": model,
- "api_key": api_key,
- "base_url": base_url,
- "dim": dim,
- "max_tokens": max_tokens,
- }
-
-
-# ============================================================================
-# YAML Configuration Loading (from config_loader.py)
-# ============================================================================
-
-
-def load_config_with_main(config_file: str, project_root: Path | None = None) -> dict[str, Any]:
- """
- Load configuration file, automatically merge with main.yaml common configuration
-
- Args:
- config_file: Sub-module configuration file name (e.g., "solve_config.yaml")
- project_root: Project root directory (if None, will try to auto-detect)
-
- Returns:
- Merged configuration dictionary
- """
- if project_root is None:
- # Try to infer project root from current file location
- # From src/core/core.py -> project root
- project_root = Path(__file__).parent.parent.parent
-
- config_dir = project_root / "config"
-
- # 1. Load main.yaml (common configuration)
- main_config = {}
- main_config_path = config_dir / "main.yaml"
- if main_config_path.exists():
- try:
- with open(main_config_path, encoding="utf-8") as f:
- main_config = yaml.safe_load(f) or {}
- except Exception as e:
- print(f"⚠️ Failed to load main.yaml: {e}")
-
- # 2. Load sub-module configuration file
- module_config = {}
- module_config_path = config_dir / config_file
- if module_config_path.exists():
- try:
- with open(module_config_path, encoding="utf-8") as f:
- module_config = yaml.safe_load(f) or {}
- except Exception as e:
- print(f"⚠️ Failed to load {config_file}: {e}")
-
- # 3. Merge configurations: main.yaml as base, sub-module config overrides
- merged_config = _deep_merge(main_config, module_config)
-
- return merged_config
-
-
-def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
- """
- Deep merge two dictionaries, values in override will override values in base
-
- Args:
- base: Base configuration
- override: Override configuration
-
- Returns:
- Merged configuration
- """
- result = base.copy()
-
- for key, value in override.items():
- if key in result and isinstance(result[key], dict) and isinstance(value, dict):
- # Recursively merge dictionaries
- result[key] = _deep_merge(result[key], value)
- else:
- # Direct override
- result[key] = value
-
- return result
-
-
-def get_path_from_config(config: dict[str, Any], path_key: str, default: str = None) -> str:
- """
- Get path from configuration, supports searching in paths and system
-
- Args:
- config: Configuration dictionary
- path_key: Path key name (e.g., "log_dir", "workspace")
- default: Default value
-
- Returns:
- Path string
- """
- # Priority: search in paths
- if "paths" in config and path_key in config["paths"]:
- return config["paths"][path_key]
-
- # Search in system (backward compatibility)
- if "system" in config and path_key in config["system"]:
- return config["system"][path_key]
-
- # Search in tools (e.g., run_code.workspace)
- if "tools" in config:
- if path_key == "workspace" and "run_code" in config["tools"]:
- return config["tools"]["run_code"].get("workspace", default)
-
- return default
-
-
-def parse_language(language: Any) -> str:
- """
- Unified language configuration parser, supports multiple input formats
-
- Supported language representations:
- - English: "en", "english", "English"
- - Chinese: "zh", "chinese", "Chinese"
-
- Args:
- language: Language configuration value (can be "zh"/"en"/"Chinese"/"English" etc.)
-
- Returns:
- Standardized language code: 'zh' or 'en', defaults to 'zh'
- """
- if not language:
- return "zh"
-
- if isinstance(language, str):
- lang_lower = language.lower()
- if lang_lower in ["en", "english"]:
- return "en"
- if lang_lower in ["zh", "chinese"]:
- return "zh"
-
- return "zh" # Default Chinese
-
-
-__all__ = [
- # Environment variable configuration
- "get_llm_config",
- "get_embedding_config",
- "get_tts_config",
- # Agent parameters
- "get_agent_params",
- # Token limit utilities (for newer OpenAI models)
- "uses_max_completion_tokens",
- "get_token_limit_kwargs",
- # YAML configuration loading
- "load_config_with_main",
- "get_path_from_config",
- "_deep_merge",
- # Language parsing
- "parse_language",
-]
diff --git a/src/core/logging/__init__.py b/src/core/logging/__init__.py
deleted file mode 100644
index c3c80270d..000000000
--- a/src/core/logging/__init__.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""
-Unified Logging System for DeepTutor
-=====================================
-
-A clean, consistent logging system with:
-- Unified format: [Module] Symbol Message
-- English-only output
-- File output to ../user/logs/
-- WebSocket streaming support
-- Color-coded console output
-
-Usage:
- from src.core.logging import get_logger
-
- logger = get_logger("Solver")
- logger.info("Processing started")
- logger.success("Task completed in 2.3s")
- logger.error("Something went wrong")
-"""
-
-from .handlers import (
- LogInterceptor,
- WebSocketLogHandler,
-)
-from .lightrag_forward import (
- LightRAGLogContext,
-)
-from .llm_stats import (
- LLMStats,
-)
-from .logger import (
- Logger,
- LogLevel,
- get_logger,
- reset_logger,
-)
-
-__all__ = [
- "LLMStats",
- "LightRAGLogContext",
- "LogInterceptor",
- "LogLevel",
- "Logger",
- "WebSocketLogHandler",
- "get_logger",
- "reset_logger",
-]
diff --git a/src/core/logging/log_forwarder.py b/src/core/logging/log_forwarder.py
deleted file mode 100644
index 5b4835f9f..000000000
--- a/src/core/logging/log_forwarder.py
+++ /dev/null
@@ -1,133 +0,0 @@
-"""
-Log Forwarder - Forward logs from question generation and problem solving to unified system log file
-"""
-
-from datetime import datetime
-import logging
-from logging.handlers import RotatingFileHandler
-from pathlib import Path
-
-
-class SystemLogForwarder(logging.Handler):
- """
- Forward logs to unified system log file
- Used for question generation and problem solving modules, keeping their own logging systems while also writing to unified log
- """
-
- _system_logger: logging.Logger | None = None
- _initialized = False
-
- @classmethod
- def get_system_logger(cls) -> logging.Logger:
- """Get unified system logger"""
- if cls._system_logger is None:
- # Get log directory from config (same logic as logger.py)
- try:
- from src.core.core import get_path_from_config, load_config_with_main
-
- # Use resolve() to get absolute path, ensuring correct project root regardless of working directory
- project_root = Path(__file__).resolve().parent.parent.parent.parent
- config = load_config_with_main("solve_config.yaml", project_root)
- log_dir = get_path_from_config(config, "user_log_dir") or config.get(
- "paths", {}
- ).get("user_log_dir")
- if log_dir:
- # Convert relative path to absolute based on project root
- log_dir_path = Path(log_dir)
- if not log_dir_path.is_absolute():
- # Remove leading ./ if present
- log_dir_str = str(log_dir_path).lstrip("./")
- log_dir = project_root / log_dir_str
- else:
- log_dir = log_dir_path
- else:
- # Fallback to default: data/user/logs
- log_dir = project_root / "data" / "user" / "logs"
- except Exception:
- # Fallback to default: data/user/logs
- # Use resolve() to get absolute path
- project_root = Path(__file__).resolve().parent.parent.parent.parent
- log_dir = project_root / "data" / "user" / "logs"
-
- # Ensure log directory exists
- log_dir.mkdir(parents=True, exist_ok=True)
-
- today = datetime.now().strftime("%Y%m%d")
- log_file = log_dir / f"ai_tutor_system_{today}.log"
-
- # Create system logger
- cls._system_logger = logging.getLogger("ai_tutor.system")
- cls._system_logger.setLevel(logging.DEBUG)
-
- # Only add file handler, don't add console handler (avoid duplicate output)
- if not cls._system_logger.handlers:
- file_handler = RotatingFileHandler(
- log_file,
- maxBytes=10 * 1024 * 1024,
- backupCount=5,
- encoding="utf-8", # 10MB
- )
- file_handler.setLevel(logging.DEBUG)
-
- # Custom formatter supporting module_name field
- class SystemLogFormatter(logging.Formatter):
- def format(self, record):
- # If no module_name, use default value
- if not hasattr(record, "module_name"):
- record.module_name = "system"
- return super().format(record)
-
- file_format = SystemLogFormatter(
- "%(asctime)s | [%(module_name)s] | %(levelname)-8s | %(message)s",
- datefmt="%Y-%m-%d %H:%M:%S",
- )
- file_handler.setFormatter(file_format)
- cls._system_logger.addHandler(file_handler)
-
- cls._initialized = True
-
- return cls._system_logger
-
- def __init__(self, module_name: str):
- """
- Initialize log forwarder
-
- Args:
- module_name: Module name (e.g., 'question', 'solve')
- """
- super().__init__()
- self.module_name = module_name
- self.setLevel(logging.DEBUG)
-
- def emit(self, record: logging.LogRecord):
- """Forward log to unified system log file"""
- try:
- # Get system logger
- system_logger = self.get_system_logger()
-
- # Add module name to record
- record.module_name = self.module_name
-
- # Forward log (using same level)
- system_logger.handle(record)
- except Exception:
- # Forward failure should not affect original log
- self.handleError(record)
-
-
-def attach_system_log_forwarder(logger: logging.Logger, module_name: str):
- """
- Attach system log forwarder to specified logger
-
- Args:
- logger: Logger to attach forwarder to
- module_name: Module name (e.g., 'question', 'solve')
- """
- # Check if already attached
- for handler in logger.handlers:
- if isinstance(handler, SystemLogForwarder) and handler.module_name == module_name:
- return # Already attached
-
- # Add forwarder
- forwarder = SystemLogForwarder(module_name)
- logger.addHandler(forwarder)
diff --git a/src/core/logging/terminal_display.py b/src/core/logging/terminal_display.py
deleted file mode 100644
index aded5c5a7..000000000
--- a/src/core/logging/terminal_display.py
+++ /dev/null
@@ -1,323 +0,0 @@
-"""
-Unified Terminal Output Management System
-Reference solve_agents display design, providing unified terminal visualization for all modules
-"""
-
-from dataclasses import dataclass
-from datetime import datetime
-from enum import Enum
-import sys
-import time
-
-
-class AgentStatus(Enum):
- PENDING = "pending"
- RUNNING = "running"
- DONE = "done"
- ERROR = "error"
-
-
-@dataclass
-class TokenUsage:
- """Token usage statistics"""
-
- model: str = ""
- input_tokens: int = 0
- output_tokens: int = 0
- cost: float = 0.0
-
- @property
- def total_tokens(self) -> int:
- return self.input_tokens + self.output_tokens
-
-
-@dataclass
-class AgentInfo:
- """Agent information"""
-
- name: str
- status: AgentStatus = AgentStatus.PENDING
- message: str = ""
- start_time: float | None = None
- end_time: float | None = None
-
-
-class TerminalDisplay:
- """
- Unified terminal display manager
- Provides visualization of workflow progress, Agent status, Token consumption, etc.
- """
-
- def __init__(
- self,
- module_name: str,
- agents: list[str] | None = None,
- show_tokens: bool = True,
- show_time: bool = True,
- ):
- """
- Initialize terminal display manager
-
- Args:
- module_name: Module name
- agents: Agent name list
- show_tokens: Whether to show token statistics
- show_time: Whether to show time information
- """
- self.module_name = module_name
- self.show_tokens = show_tokens
- self.show_time = show_time
- self.start_time = time.time()
-
- # Agent status tracking
- self.agents: dict[str, AgentInfo] = {}
- if agents:
- for agent in agents:
- self.agents[agent] = AgentInfo(name=agent)
-
- # Token statistics
- self.token_usage: dict[str, TokenUsage] = {}
- self.total_tokens = TokenUsage()
-
- # Log buffer
- self.log_buffer: list[str] = []
- self.max_log_lines = 10
-
- def _get_status_symbol(self, status: AgentStatus) -> str:
- """Get status symbol"""
- symbols = {
- AgentStatus.PENDING: "○",
- AgentStatus.RUNNING: "●",
- AgentStatus.DONE: "✓",
- AgentStatus.ERROR: "✗",
- }
- return symbols.get(status, "?")
-
- def _get_status_color(self, status: AgentStatus) -> str:
- """Get status color ANSI code"""
- colors = {
- AgentStatus.PENDING: "\033[90m", # Gray
- AgentStatus.RUNNING: "\033[33m", # Yellow
- AgentStatus.DONE: "\033[32m", # Green
- AgentStatus.ERROR: "\033[31m", # Red
- }
- return colors.get(status, "\033[0m")
-
- def _reset_color(self) -> str:
- """Reset color"""
- return "\033[0m"
-
- def set_agent_status(self, agent_name: str, status: str, message: str = ""):
- """
- Set Agent status
-
- Args:
- agent_name: Agent name
- status: Status (pending, running, done, error)
- message: Status message
- """
- status_enum = AgentStatus(status) if isinstance(status, str) else status
-
- if agent_name not in self.agents:
- self.agents[agent_name] = AgentInfo(name=agent_name)
-
- agent = self.agents[agent_name]
- old_status = agent.status
- agent.status = status_enum
- agent.message = message
-
- if status_enum == AgentStatus.RUNNING and agent.start_time is None:
- agent.start_time = time.time()
- elif status_enum in (AgentStatus.DONE, AgentStatus.ERROR):
- agent.end_time = time.time()
-
- self._refresh_display()
-
- def add_token_usage(self, model: str, input_tokens: int, output_tokens: int, cost: float = 0.0):
- """
- Add token usage record
-
- Args:
- model: Model name
- input_tokens: Input token count
- output_tokens: Output token count
- cost: Cost (USD)
- """
- if model not in self.token_usage:
- self.token_usage[model] = TokenUsage(model=model)
-
- usage = self.token_usage[model]
- usage.input_tokens += input_tokens
- usage.output_tokens += output_tokens
- usage.cost += cost
-
- # Update total
- self.total_tokens.input_tokens += input_tokens
- self.total_tokens.output_tokens += output_tokens
- self.total_tokens.cost += cost
-
- self._refresh_display()
-
- def log(self, message: str):
- """Add log message"""
- timestamp = datetime.now().strftime("%H:%M:%S")
- log_line = f"[{timestamp}] {message}"
- self.log_buffer.append(log_line)
-
- # Maintain log buffer size
- if len(self.log_buffer) > self.max_log_lines:
- self.log_buffer = self.log_buffer[-self.max_log_lines :]
-
- self._refresh_display()
-
- def _refresh_display(self):
- """Refresh terminal display"""
- # Clear screen and move to top
- print("\033[2J\033[H", end="")
-
- # Title
- elapsed = time.time() - self.start_time
- print("\033[1;34m╔══════════════════════════════════════════════════════════════╗\033[0m")
- print(f"\033[1;34m║\033[0m \033[1m{self.module_name:^56}\033[0m \033[1;34m║\033[0m")
- if self.show_time:
- time_str = f"Running: {elapsed:.1f}s"
- print(f"\033[1;34m║\033[0m {time_str:^56} \033[1;34m║\033[0m")
- print("\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m")
-
- # Agent status
- if self.agents:
- print(f"\033[1;34m║\033[0m \033[1mAgent Status\033[0m{'':43} \033[1;34m║\033[0m")
- for agent in self.agents.values():
- symbol = self._get_status_symbol(agent.status)
- color = self._get_status_color(agent.status)
- reset = self._reset_color()
-
- status_str = f"{color}{symbol} {agent.name}{reset}"
- if agent.message:
- status_str += f" - {agent.message[:30]}"
-
- # Calculate display time
- if agent.start_time and agent.end_time:
- duration = agent.end_time - agent.start_time
- status_str += f" ({duration:.1f}s)"
- elif agent.start_time:
- duration = time.time() - agent.start_time
- status_str += f" ({duration:.1f}s...)"
-
- # Need to handle ANSI escape sequence length when printing
- print(f"\033[1;34m║\033[0m {status_str:56} \033[1;34m║\033[0m")
-
- print(
- "\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m"
- )
-
- # Token statistics
- if self.show_tokens and self.token_usage:
- print(f"\033[1;34m║\033[0m \033[1mToken Usage\033[0m{'':44} \033[1;34m║\033[0m")
- for model, usage in self.token_usage.items():
- model_short = model[:20] + "..." if len(model) > 20 else model
- tokens_str = f"{model_short}: {usage.total_tokens:,} tokens"
- if usage.cost > 0:
- tokens_str += f" (${usage.cost:.4f})"
- print(f"\033[1;34m║\033[0m {tokens_str:54} \033[1;34m║\033[0m")
-
- # Total
- total_str = f"Total: {self.total_tokens.total_tokens:,} tokens"
- if self.total_tokens.cost > 0:
- total_str += f" (${self.total_tokens.cost:.4f})"
- print(f"\033[1;34m║\033[0m \033[1m{total_str:54}\033[0m \033[1;34m║\033[0m")
-
- print(
- "\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m"
- )
-
- # Logs
- if self.log_buffer:
- print(f"\033[1;34m║\033[0m \033[1mRecent Logs\033[0m{'':44} \033[1;34m║\033[0m")
- for log_line in self.log_buffer[-5:]: # Only show last 5
- log_short = log_line[:52] + "..." if len(log_line) > 52 else log_line
- print(f"\033[1;34m║\033[0m \033[90m{log_short:54}\033[0m \033[1;34m║\033[0m")
- print(
- "\033[1;34m╠══════════════════════════════════════════════════════════════╣\033[0m"
- )
-
- # Bottom
- print("\033[1;34m╚══════════════════════════════════════════════════════════════╝\033[0m")
-
- sys.stdout.flush()
-
- def complete(self, message: str = "Complete"):
- """Mark task as complete"""
- elapsed = time.time() - self.start_time
- self.log(f"✓ {message} ({elapsed:.1f}s)")
- self._refresh_display()
-
- def error(self, message: str):
- """Mark task as error"""
- self.log(f"✗ Error: {message}")
- self._refresh_display()
-
-
-class SimpleProgress:
- """
- Simple progress displayer (no screen clearing)
- Suitable for scenarios that don't need full TUI
- """
-
- def __init__(self, module_name: str):
- self.module_name = module_name
- self.start_time = time.time()
-
- def log(self, message: str, level: str = "INFO"):
- """Output log"""
- timestamp = datetime.now().strftime("%H:%M:%S")
- elapsed = time.time() - self.start_time
-
- color = {
- "INFO": "\033[0m",
- "SUCCESS": "\033[32m",
- "WARNING": "\033[33m",
- "ERROR": "\033[31m",
- }.get(level, "\033[0m")
-
- reset = "\033[0m"
- print(f"[{timestamp}] [{self.module_name}] {color}{message}{reset} ({elapsed:.1f}s)")
-
- def progress(self, current: int, total: int, message: str = ""):
- """Display progress bar"""
- percentage = (current / total) * 100 if total > 0 else 0
- bar_length = 30
- filled = int(bar_length * current / total) if total > 0 else 0
- bar = "█" * filled + "░" * (bar_length - filled)
-
- print(f"\r[{bar}] {percentage:5.1f}% ({current}/{total}) {message}", end="", flush=True)
- if current >= total:
- print() # New line
-
- def complete(self, message: str = "Complete"):
- """Complete"""
- self.log(f"✓ {message}", "SUCCESS")
-
- def error(self, message: str):
- """Error"""
- self.log(f"✗ {message}", "ERROR")
-
-
-# Convenience functions
-def create_display(
- module_name: str, agents: list[str] | None = None, use_tui: bool = True
-) -> TerminalDisplay | SimpleProgress:
- """
- Create terminal displayer
-
- Args:
- module_name: Module name
- agents: Agent list
- use_tui: Whether to use full TUI
-
- Returns:
- Displayer instance
- """
- if use_tui:
- return TerminalDisplay(module_name, agents)
- return SimpleProgress(module_name)
diff --git a/src/knowledge/add_documents.py b/src/knowledge/add_documents.py
index 0465480c8..916e499fa 100644
--- a/src/knowledge/add_documents.py
+++ b/src/knowledge/add_documents.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Incrementally add documents to existing knowledge base
@@ -28,12 +29,13 @@ from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.utils import EmbeddingFunc
from raganything import RAGAnything, RAGAnythingConfig
-from src.core.core import get_embedding_config, get_llm_config
+from src.services.llm import get_llm_config
+from src.services.embedding import get_embedding_config
load_dotenv(dotenv_path=".env", override=False)
# Use unified logging system
-from src.core.logging import LightRAGLogContext, get_logger
+from src.logging import LightRAGLogContext, get_logger
logger = get_logger("KnowledgeInit")
@@ -106,13 +108,13 @@ class DocumentAdder:
for source in source_files:
source_path = Path(source)
if not source_path.exists():
- logger.warning(f" ✗ Source file does not exist: {source}")
+ logger.warning(f" ⚠ Source file does not exist: {source}")
continue
# Check if already exists
if source_path.name in existing_files:
if skip_duplicates:
- logger.info(f" ⊗ Skipped (already exists): {source_path.name}")
+ logger.info(f" → Skipped (already exists): {source_path.name}")
skipped_files.append(source_path.name)
continue
logger.warning(f" ⚠ Overwriting existing file: {source_path.name}")
@@ -151,7 +153,7 @@ class DocumentAdder:
# Get model configuration
llm_cfg = get_llm_config()
- model = llm_cfg["model"]
+ model = llm_cfg.model
# Define LLM model function
def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
@@ -233,14 +235,14 @@ class DocumentAdder:
# Define embedding function
embedding_cfg = self.embedding_cfg
- embedding_api_key = embedding_cfg["api_key"] or self.api_key
- embedding_base_url = embedding_cfg["base_url"] or self.base_url
+ embedding_api_key = embedding_cfg.api_key or self.api_key
+ embedding_base_url = embedding_cfg.base_url or self.base_url
embedding_func = EmbeddingFunc(
- embedding_dim=embedding_cfg["dim"],
- max_token_size=embedding_cfg["max_tokens"],
+ embedding_dim=embedding_cfg.dim,
+ max_token_size=embedding_cfg.max_tokens,
func=lambda texts: openai_embed(
texts,
- model=embedding_cfg["model"],
+ model=embedding_cfg.model,
api_key=embedding_api_key,
base_url=embedding_base_url,
),
diff --git a/src/knowledge/config.py b/src/knowledge/config.py
index b0531f6d7..4e3b1522c 100644
--- a/src/knowledge/config.py
+++ b/src/knowledge/config.py
@@ -26,12 +26,12 @@ def check_raganything():
def get_env_config():
"""Get environment variable configuration (unified read from env_config)"""
try:
- from src.core.core import get_llm_config
+ from src.services.llm import get_llm_config
cfg = get_llm_config()
return {
- "api_key": cfg.get("api_key"),
- "base_url": cfg.get("base_url"),
+ "api_key": cfg.api_key,
+ "base_url": cfg.base_url,
}
except Exception:
# Compatibility fallback: directly read environment variables
diff --git a/src/knowledge/example_add_documents.py b/src/knowledge/example_add_documents.py
index 5855259a1..952976cf6 100644
--- a/src/knowledge/example_add_documents.py
+++ b/src/knowledge/example_add_documents.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Incremental Document Addition Usage Example
@@ -46,7 +47,7 @@ async def example_add_single_document():
# Update metadata
adder.update_metadata(len(new_files))
- print("\n✅ Completed!")
+ print("\n✓ Completed!")
async def example_add_multiple_documents():
@@ -85,7 +86,7 @@ async def example_add_multiple_documents():
# Update metadata
adder.update_metadata(len(new_files))
- print("\n✅ Completed!")
+ print("\n✓ Completed!")
async def example_add_from_directory():
@@ -123,7 +124,7 @@ async def example_add_from_directory():
# Update metadata
adder.update_metadata(len(new_files))
- print("\n✅ Completed!")
+ print("\n✓ Completed!")
async def example_add_only_no_processing():
@@ -181,7 +182,7 @@ def example_with_error_handling():
# Check if file exists
source_file = Path("./new_chapter.pdf")
if not source_file.exists():
- print(f"❌ Error: Source file does not exist: {source_file}")
+ print(f"✗ Error: Source file does not exist: {source_file}")
return
# Add documents
@@ -199,14 +200,14 @@ def example_with_error_handling():
asyncio.run(process())
- print("\n✅ Successfully added documents!")
+ print("\n✓ Successfully added documents!")
except ValueError as e:
- print(f"❌ Configuration error: {e}")
+ print(f"✗ Configuration error: {e}")
except FileNotFoundError as e:
- print(f"❌ File error: {e}")
+ print(f"✗ File error: {e}")
except Exception as e:
- print(f"❌ Unknown error: {e}")
+ print(f"✗ Unknown error: {e}")
import traceback
traceback.print_exc()
diff --git a/src/knowledge/extract_numbered_items.py b/src/knowledge/extract_numbered_items.py
index d322ab4b1..2fbea2476 100644
--- a/src/knowledge/extract_numbered_items.py
+++ b/src/knowledge/extract_numbered_items.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Extract numbered important content from knowledge base content_list
Such as: Definition 1.5., Proposition 1.3., Theorem x.x., Equation x.x., Formula x.x., etc.
@@ -20,7 +21,7 @@ sys.path.append(str(Path(__file__).parent.parent.parent))
from dotenv import load_dotenv
from lightrag.llm.openai import openai_complete_if_cache
-from src.core.core import get_llm_config
+from src.services.llm import get_llm_config
load_dotenv(dotenv_path=".env", override=False)
@@ -28,8 +29,8 @@ load_dotenv(dotenv_path=".env", override=False)
try:
from pathlib import Path
- from src.core.core import load_config_with_main
- from src.core.logging import get_logger
+ from src.services.config import load_config_with_main
+ from src.logging import get_logger
project_root = Path(__file__).parent.parent.parent.parent
config = load_config_with_main(
@@ -62,7 +63,7 @@ async def _call_llm_async(
# If model not specified, get from env_config
if model is None:
llm_cfg = get_llm_config()
- model = llm_cfg["model"]
+ model = llm_cfg.model
result = openai_complete_if_cache(
model,
@@ -160,7 +161,7 @@ Answer with ONLY "YES" or "NO"."""
base_url,
max_tokens=10,
temperature=0.0,
- model=llm_cfg["model"],
+ model=llm_cfg.model,
)
answer = response.strip().upper()
return answer == "YES"
@@ -436,7 +437,7 @@ Return ONLY the JSON array, no other text. Ensure it is valid JSON."""
base_url,
max_tokens=4000,
temperature=0.1,
- model=llm_cfg["model"],
+ model=llm_cfg.model,
)
# Parse response
diff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.py
index 6ffa0bd86..de5e70f57 100644
--- a/src/knowledge/initializer.py
+++ b/src/knowledge/initializer.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Knowledge Base Initialization Script
@@ -30,12 +31,13 @@ from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.utils import EmbeddingFunc
from raganything import RAGAnything, RAGAnythingConfig
-from src.core.core import get_embedding_config, get_llm_config
+from src.services.llm import get_llm_config
+from src.services.embedding import get_embedding_config
load_dotenv(dotenv_path=".env", override=False)
# Use unified logging system
-from src.core.logging import LightRAGLogContext, get_logger
+from src.logging import LightRAGLogContext, get_logger
logger = get_logger("KnowledgeInit")
@@ -147,7 +149,7 @@ class KnowledgeBaseInitializer:
for source in source_files:
source_path = Path(source)
if not source_path.exists():
- logger.warning(f" ✗ Source file not found: {source}")
+ logger.warning(f" ⚠ Source file not found: {source}")
continue
dest_path = self.raw_dir / source_path.name
@@ -197,7 +199,7 @@ class KnowledgeBaseInitializer:
# Get LLM configuration from env_config
llm_cfg = get_llm_config()
- llm_model = llm_cfg["model"]
+ llm_model = llm_cfg.model
# Define LLM model function
def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
@@ -279,14 +281,14 @@ class KnowledgeBaseInitializer:
# Define embedding function
embedding_cfg = self.embedding_cfg
- embedding_api_key = embedding_cfg["api_key"] or self.api_key
- embedding_base_url = embedding_cfg["base_url"] or self.base_url
+ embedding_api_key = embedding_cfg.api_key or self.api_key
+ embedding_base_url = embedding_cfg.base_url or self.base_url
embedding_func = EmbeddingFunc(
- embedding_dim=embedding_cfg["dim"],
- max_token_size=embedding_cfg["max_tokens"],
+ embedding_dim=embedding_cfg.dim,
+ max_token_size=embedding_cfg.max_tokens,
func=lambda texts: openai_embed(
texts,
- model=embedding_cfg["model"],
+ model=embedding_cfg.model,
api_key=embedding_api_key,
base_url=embedding_base_url,
),
diff --git a/src/knowledge/manager.py b/src/knowledge/manager.py
index c11a5970c..c7538ef5e 100644
--- a/src/knowledge/manager.py
+++ b/src/knowledge/manager.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Knowledge Base Manager
diff --git a/src/knowledge/progress_tracker.py b/src/knowledge/progress_tracker.py
index b0a3961db..a635b12eb 100644
--- a/src/knowledge/progress_tracker.py
+++ b/src/knowledge/progress_tracker.py
@@ -15,7 +15,7 @@ project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))
# Use unified logging system
-from src.core.logging import get_logger
+from src.logging import get_logger
_logger = get_logger("KnowledgeInit")
diff --git a/src/knowledge/start_kb.py b/src/knowledge/start_kb.py
index be6176e77..071f99cfb 100644
--- a/src/knowledge/start_kb.py
+++ b/src/knowledge/start_kb.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Knowledge Base Management Startup Script - Unified Entry Point
Provides knowledge base initialization, management, querying, and other functions
@@ -44,7 +45,7 @@ def list_knowledge_bases():
print("\nTip: Use 'init' command to create a new knowledge base")
else:
for kb_name in kb_list:
- default_marker = " ⭐ (default)" if kb_name == default_kb else ""
+ default_marker = " ★(default)" if kb_name == default_kb else ""
print(f" • {kb_name}{default_marker}")
# Display statistics
@@ -95,7 +96,7 @@ def show_kb_info(kb_name=None):
print("=" * 60 + "\n")
except Exception as e:
- print(f"❌ Error: {e!s}\n")
+ print(f"✗ Error: {e!s}\n")
def set_default_kb(kb_name):
@@ -104,9 +105,9 @@ def set_default_kb(kb_name):
try:
manager.set_default(kb_name)
- print(f"✅ Set '{kb_name}' as default knowledge base\n")
+ print(f"✓ Set '{kb_name}' as default knowledge base\n")
except Exception as e:
- print(f"❌ Error: {e!s}\n")
+ print(f"✗ Error: {e!s}\n")
async def init_knowledge_base(args):
@@ -117,7 +118,7 @@ async def init_knowledge_base(args):
base_url = args.base_url or env_config["base_url"]
if not api_key and not args.skip_processing:
- print("❌ Error: API Key not set")
+ print("✗ Error: API Key not set")
print("Please set environment variable LLM_BINDING_API_KEY or use --api-key parameter\n")
return
@@ -132,11 +133,11 @@ async def init_knowledge_base(args):
for ext in ["*.pdf", "*.docx", "*.doc", "*.txt", "*.md"]:
doc_files.extend([str(f) for f in docs_dir.glob(ext)])
else:
- print(f"❌ Error: Document directory does not exist: {args.docs_dir}\n")
+ print(f"✗ Error: Document directory does not exist: {args.docs_dir}\n")
return
if not args.skip_processing and not doc_files:
- print("❌ Error: No documents specified")
+ print("✗ Error: No documents specified")
print("Use --docs or --docs-dir to specify documents\n")
return
@@ -155,7 +156,7 @@ async def init_knowledge_base(args):
# Copy documents
if doc_files:
copied_files = initializer.copy_documents(doc_files)
- print(f"✅ Copied {len(copied_files)} files\n")
+ print(f"✓ Copied {len(copied_files)} files\n")
# Process documents
if not args.skip_processing:
@@ -170,7 +171,7 @@ async def init_knowledge_base(args):
print("⏭️ Skipping numbered items extraction\n")
print("\n" + "=" * 60)
- print(f"✅ Knowledge base '{args.name}' initialization complete!")
+ print(f"✓ Knowledge base '{args.name}' initialization complete!")
print(f"Location: {initializer.kb_dir}")
print("=" * 60 + "\n")
@@ -183,7 +184,7 @@ def extract_items(args):
base_url = args.base_url or env_config["base_url"]
if not api_key:
- print("❌ Error: API Key not set")
+ print("✗ Error: API Key not set")
print("Please set environment variable LLM_BINDING_API_KEY or use --api-key parameter\n")
return
@@ -192,19 +193,19 @@ def extract_items(args):
content_list_dir = kb_dir / "content_list"
if not content_list_dir.exists():
- print(f"❌ Error: content_list directory does not exist: {content_list_dir}\n")
+ print(f"✗ Error: content_list directory does not exist: {content_list_dir}\n")
return
# Get files to process
if args.content_file:
content_list_files = [content_list_dir / args.content_file]
if not content_list_files[0].exists():
- print(f"❌ Error: content_list file does not exist: {content_list_files[0]}\n")
+ print(f"✗ Error: content_list file does not exist: {content_list_files[0]}\n")
return
else:
content_list_files = sorted(content_list_dir.glob("*.json"))
if not content_list_files:
- print(f"❌ Error: No JSON files found in {content_list_dir}\n")
+ print(f"✗ Error: No JSON files found in {content_list_dir}\n")
return
if args.debug:
@@ -235,12 +236,12 @@ def extract_items(args):
)
print("\n" + "=" * 60)
- print("✅ Extraction complete!")
+ print("✓ Extraction complete!")
print(f"Output file: {output_file}")
print("=" * 60 + "\n")
except Exception as e:
- print(f"\n❌ Extraction failed: {e}\n")
+ print(f"\n✗ Extraction failed: {e}\n")
def delete_knowledge_base(args):
@@ -250,9 +251,9 @@ def delete_knowledge_base(args):
try:
success = manager.delete_knowledge_base(args.name, confirm=args.force)
if success:
- print(f"\n✅ Deleted knowledge base '{args.name}'\n")
+ print(f"\n✓ Deleted knowledge base '{args.name}'\n")
except Exception as e:
- print(f"\n❌ Error: {e}\n")
+ print(f"\n✗ Error: {e}\n")
def clean_rag_storage(args):
@@ -266,11 +267,11 @@ def clean_rag_storage(args):
try:
manager.clean_rag_storage(args.name, backup=not args.no_backup)
print("\n" + "=" * 60)
- print("✅ RAG storage cleaned!")
+ print("✓ RAG storage cleaned!")
print("💡 Tip: Use 'add_documents.py' to reprocess documents to rebuild RAG")
print("=" * 60 + "\n")
except Exception as e:
- print(f"\n❌ Error: {e}\n")
+ print(f"\n✗ Error: {e}\n")
async def refresh_knowledge_base(args):
@@ -283,7 +284,7 @@ async def refresh_knowledge_base(args):
base_url = args.base_url or env_config["base_url"]
if not api_key:
- print("❌ Error: API Key not set")
+ print("✗ Error: API Key not set")
print("Please set environment variable LLM_BINDING_API_KEY or use --api-key parameter\n")
return
@@ -293,7 +294,7 @@ async def refresh_knowledge_base(args):
raw_dir = kb_dir / "raw"
if not raw_dir.exists() or not list(raw_dir.glob("*")):
- print(f"❌ Error: No raw documents found in knowledge base '{kb_name}'\n")
+ print(f"✗ Error: No raw documents found in knowledge base '{kb_name}'\n")
return
print("\n" + "=" * 60)
@@ -346,11 +347,11 @@ async def refresh_knowledge_base(args):
initializer.extract_numbered_items(batch_size=args.batch_size)
print("\n" + "=" * 60)
- print(f"✅ Knowledge base '{kb_name}' refresh complete!")
+ print(f"✓ Knowledge base '{kb_name}' refresh complete!")
print("=" * 60 + "\n")
except Exception as e:
- print(f"\n❌ Refresh failed: {e}\n")
+ print(f"\n✗ Refresh failed: {e}\n")
raise
@@ -501,7 +502,7 @@ Usage Examples:
if "pop from an empty deque" not in str(e):
raise
except Exception as e:
- print(f"\n❌ Error: {e}")
+ print(f"\n✗ Error: {e}")
raise
elif args.command == "extract":
@@ -523,7 +524,7 @@ Usage Examples:
if "pop from an empty deque" not in str(e):
raise
except Exception as e:
- print(f"\n❌ Error: {e}")
+ print(f"\n✗ Error: {e}")
raise
else:
diff --git a/src/logging/__init__.py b/src/logging/__init__.py
new file mode 100644
index 000000000..50e9201c2
--- /dev/null
+++ b/src/logging/__init__.py
@@ -0,0 +1,106 @@
+"""
+Unified Logging System for DeepTutor
+=====================================
+
+A clean, consistent logging system with:
+- Unified format: [Module] Symbol Message
+- English-only output
+- File output to data/user/logs/
+- WebSocket streaming support
+- Color-coded console output
+- LLM usage statistics tracking
+- External library log forwarding (LightRAG, LlamaIndex)
+
+Usage:
+ from src.logging import get_logger, LLMStats
+
+ logger = get_logger("Solver")
+ logger.info("Processing started")
+ logger.success("Task completed in 2.3s")
+ logger.error("Something went wrong")
+
+ # Track LLM usage
+ stats = LLMStats("Solver")
+ stats.add_call(model="gpt-4o", prompt_tokens=100, completion_tokens=50)
+ stats.print_summary()
+"""
+
+# Core logging
+from .logger import (
+ Logger,
+ LogLevel,
+ get_logger,
+ reset_logger,
+ ConsoleFormatter,
+ FileFormatter,
+)
+
+# Handlers
+from .handlers import (
+ ConsoleHandler,
+ FileHandler,
+ JSONFileHandler,
+ RotatingFileHandler,
+ WebSocketLogHandler,
+ LogInterceptor,
+)
+
+# Adapters for external libraries
+from .adapters import (
+ LightRAGLogContext,
+ LightRAGLogForwarder,
+ get_lightrag_forwarding_config,
+ LlamaIndexLogContext,
+ LlamaIndexLogForwarder,
+)
+
+# Statistics tracking
+from .stats import (
+ LLMStats,
+ LLMCall,
+ get_pricing,
+ estimate_tokens,
+ MODEL_PRICING,
+)
+
+# Configuration
+from .config import (
+ LoggingConfig,
+ load_logging_config,
+ get_default_log_dir,
+)
+
+
+__all__ = [
+ # Core
+ "Logger",
+ "LogLevel",
+ "get_logger",
+ "reset_logger",
+ "ConsoleFormatter",
+ "FileFormatter",
+ # Handlers
+ "ConsoleHandler",
+ "FileHandler",
+ "JSONFileHandler",
+ "RotatingFileHandler",
+ "WebSocketLogHandler",
+ "LogInterceptor",
+ # Adapters
+ "LightRAGLogContext",
+ "LightRAGLogForwarder",
+ "get_lightrag_forwarding_config",
+ "LlamaIndexLogContext",
+ "LlamaIndexLogForwarder",
+ # Stats
+ "LLMStats",
+ "LLMCall",
+ "get_pricing",
+ "estimate_tokens",
+ "MODEL_PRICING",
+ # Config
+ "LoggingConfig",
+ "load_logging_config",
+ "get_default_log_dir",
+]
+
diff --git a/src/logging/adapters/__init__.py b/src/logging/adapters/__init__.py
new file mode 100644
index 000000000..57a403f82
--- /dev/null
+++ b/src/logging/adapters/__init__.py
@@ -0,0 +1,18 @@
+"""
+Log Adapters
+============
+
+Adapters for forwarding logs from external libraries to the unified logging system.
+"""
+
+from .lightrag import LightRAGLogContext, LightRAGLogForwarder, get_lightrag_forwarding_config
+from .llamaindex import LlamaIndexLogContext, LlamaIndexLogForwarder
+
+__all__ = [
+ "LightRAGLogContext",
+ "LightRAGLogForwarder",
+ "get_lightrag_forwarding_config",
+ "LlamaIndexLogContext",
+ "LlamaIndexLogForwarder",
+]
+
diff --git a/src/core/logging/lightrag_forward.py b/src/logging/adapters/lightrag.py
similarity index 95%
rename from src/core/logging/lightrag_forward.py
rename to src/logging/adapters/lightrag.py
index 74d6e8825..e704ff0aa 100644
--- a/src/core/logging/lightrag_forward.py
+++ b/src/logging/adapters/lightrag.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
"""
LightRAG Log Forwarder
+======================
Forwards LightRAG and RAG-Anything logs to DeepTutor's unified logging system.
"""
@@ -8,10 +9,7 @@ Forwards LightRAG and RAG-Anything logs to DeepTutor's unified logging system.
from contextlib import contextmanager
import logging
from pathlib import Path
-
-from src.core.core import load_config_with_main
-
-from .logger import get_logger
+from typing import Optional
class LightRAGLogForwarder(logging.Handler):
@@ -50,7 +48,7 @@ class LightRAGLogForwarder(logging.Handler):
self.handleError(record)
-def get_lightrag_forwarding_config():
+def get_lightrag_forwarding_config() -> dict:
"""
Load LightRAG forwarding configuration from main.yaml.
@@ -58,6 +56,8 @@ def get_lightrag_forwarding_config():
dict: Configuration dictionary with defaults if not found
"""
try:
+ from src.services.config import load_config_with_main
+
# Use resolve() to get absolute path, ensuring correct project root regardless of working directory
project_root = Path(__file__).resolve().parent.parent.parent.parent
config = load_config_with_main("solve_config.yaml", project_root)
@@ -83,7 +83,7 @@ def get_lightrag_forwarding_config():
@contextmanager
-def LightRAGLogContext(logger_name: str | None = None, scene: str | None = None):
+def LightRAGLogContext(logger_name: Optional[str] = None, scene: Optional[str] = None):
"""
Context manager for LightRAG log forwarding.
@@ -98,6 +98,8 @@ def LightRAGLogContext(logger_name: str | None = None, scene: str | None = None)
# RAG operations
rag = RAGAnything(...)
"""
+ from ..logger import get_logger
+
# Get configuration
config = get_lightrag_forwarding_config()
@@ -180,3 +182,4 @@ def LightRAGLogContext(logger_name: str | None = None, scene: str | None = None)
for handler in console_handlers_to_remove:
if handler not in lightrag_logger.handlers:
lightrag_logger.addHandler(handler)
+
diff --git a/src/logging/adapters/llamaindex.py b/src/logging/adapters/llamaindex.py
new file mode 100644
index 000000000..1959862d2
--- /dev/null
+++ b/src/logging/adapters/llamaindex.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python
+"""
+LlamaIndex Log Forwarder
+========================
+
+Forwards LlamaIndex logs to DeepTutor's unified logging system.
+"""
+
+from contextlib import contextmanager
+import logging
+from typing import Optional
+
+
+class LlamaIndexLogForwarder(logging.Handler):
+ """
+ Handler that forwards LlamaIndex logger messages to DeepTutor logger.
+ """
+
+ def __init__(self, ai_tutor_logger, add_prefix: bool = True):
+ """
+ Args:
+ ai_tutor_logger: DeepTutor Logger instance
+ add_prefix: Whether to add prefix to messages
+ """
+ super().__init__()
+ self.ai_tutor_logger = ai_tutor_logger
+ self.add_prefix = add_prefix
+ # Capture all log levels
+ self.setLevel(logging.DEBUG)
+
+ def emit(self, record: logging.LogRecord):
+ """
+ Forward log record to DeepTutor logger.
+ """
+ try:
+ message = record.getMessage()
+
+ # Map log levels
+ level = record.levelno
+ if level >= logging.ERROR:
+ self.ai_tutor_logger.error(message)
+ elif level >= logging.WARNING:
+ self.ai_tutor_logger.warning(message)
+ elif level >= logging.INFO:
+ self.ai_tutor_logger.info(message)
+ else:
+ self.ai_tutor_logger.debug(message)
+
+ except Exception:
+ self.handleError(record)
+
+
+@contextmanager
+def LlamaIndexLogContext(
+ logger_name: Optional[str] = None,
+ scene: str = "llamaindex",
+ min_level: str = "INFO",
+):
+ """
+ Context manager for LlamaIndex log forwarding.
+
+ Automatically sets up and tears down log forwarding.
+
+ Args:
+ logger_name: Explicit logger name (defaults to scene name)
+ scene: Scene name for logger identification
+ min_level: Minimum log level to forward
+
+ Usage:
+ with LlamaIndexLogContext("VectorSearch"):
+ # LlamaIndex operations
+ index.query(query)
+ """
+ from ..logger import get_logger
+
+ # Determine logger name
+ if logger_name is None:
+ logger_name = scene.title().replace("_", "")
+
+ # Get DeepTutor logger
+ ai_tutor_logger = get_logger(logger_name)
+
+ # Get LlamaIndex loggers
+ llama_loggers = [
+ logging.getLogger("llama_index"),
+ logging.getLogger("llama_index.core"),
+ logging.getLogger("llama_index.vector_stores"),
+ logging.getLogger("llama_index.embeddings"),
+ ]
+
+ # Parse min level
+ min_level_int = getattr(logging, min_level.upper(), logging.INFO)
+
+ # Store original state
+ original_states = []
+ forwarders = []
+
+ for llama_logger in llama_loggers:
+ original_states.append({
+ "logger": llama_logger,
+ "handlers": llama_logger.handlers[:],
+ "level": llama_logger.level,
+ })
+
+ # Temporarily remove console handlers
+ console_handlers_to_remove = []
+ for handler in llama_logger.handlers:
+ if isinstance(handler, logging.StreamHandler):
+ console_handlers_to_remove.append(handler)
+
+ for handler in console_handlers_to_remove:
+ llama_logger.removeHandler(handler)
+
+ # Set level
+ if llama_logger.level > logging.DEBUG:
+ llama_logger.setLevel(logging.DEBUG)
+
+ # Add forwarder
+ forwarder = LlamaIndexLogForwarder(ai_tutor_logger)
+ forwarder.setLevel(min_level_int)
+ llama_logger.addHandler(forwarder)
+ forwarders.append((llama_logger, forwarder))
+
+ try:
+ yield
+ finally:
+ # Clean up forwarders
+ for llama_logger, forwarder in forwarders:
+ if forwarder in llama_logger.handlers:
+ llama_logger.removeHandler(forwarder)
+ forwarder.close()
+
+ # Restore original state
+ for state in original_states:
+ llama_logger = state["logger"]
+ # Restore handlers that were removed
+ for handler in state["handlers"]:
+ if handler not in llama_logger.handlers:
+ llama_logger.addHandler(handler)
+
diff --git a/src/logging/config.py b/src/logging/config.py
new file mode 100644
index 000000000..a0d49a700
--- /dev/null
+++ b/src/logging/config.py
@@ -0,0 +1,75 @@
+"""
+Logging Configuration
+=====================
+
+Configuration settings for the logging system.
+"""
+
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Optional
+
+
+@dataclass
+class LoggingConfig:
+ """Configuration for the logging system."""
+
+ # Output settings
+ console_output: bool = True
+ file_output: bool = True
+
+ # Log levels
+ console_level: str = "INFO"
+ file_level: str = "DEBUG"
+
+ # Log directory (relative to project root or absolute)
+ log_dir: Optional[str] = None
+
+ # File rotation settings
+ max_bytes: int = 10 * 1024 * 1024 # 10MB
+ backup_count: int = 5
+
+ # WebSocket streaming
+ websocket_enabled: bool = True
+ websocket_queue_size: int = 1000
+
+ # LightRAG forwarding
+ lightrag_forwarding_enabled: bool = True
+ lightrag_min_level: str = "INFO"
+ lightrag_add_prefix: bool = True
+
+
+def get_default_log_dir() -> Path:
+ """Get the default log directory."""
+ project_root = Path(__file__).resolve().parent.parent.parent
+ return project_root / "data" / "user" / "logs"
+
+
+def load_logging_config() -> LoggingConfig:
+ """
+ Load logging configuration from config files.
+
+ Returns:
+ LoggingConfig instance with loaded or default values.
+ """
+ try:
+ from src.services.config import load_config_with_main, get_path_from_config
+
+ project_root = Path(__file__).resolve().parent.parent.parent
+ config = load_config_with_main("solve_config.yaml", project_root)
+
+ logging_config = config.get("logging", {})
+
+ return LoggingConfig(
+ console_output=logging_config.get("console_output", True),
+ file_output=logging_config.get("file_output", True),
+ console_level=logging_config.get("console_level", "INFO"),
+ file_level=logging_config.get("file_level", "DEBUG"),
+ log_dir=get_path_from_config(config, "user_log_dir"),
+ lightrag_forwarding_enabled=logging_config.get("lightrag_forwarding", {}).get("enabled", True),
+ lightrag_min_level=logging_config.get("lightrag_forwarding", {}).get("min_level", "INFO"),
+ lightrag_add_prefix=logging_config.get("lightrag_forwarding", {}).get("add_prefix", True),
+ )
+ except Exception:
+ return LoggingConfig()
+
diff --git a/src/logging/handlers/__init__.py b/src/logging/handlers/__init__.py
new file mode 100644
index 000000000..ba26e83cf
--- /dev/null
+++ b/src/logging/handlers/__init__.py
@@ -0,0 +1,21 @@
+"""
+Log Handlers
+============
+
+Custom logging handlers for various output destinations.
+"""
+
+from .console import ConsoleHandler
+from .file import FileHandler, JSONFileHandler, RotatingFileHandler, create_task_logger
+from .websocket import WebSocketLogHandler, LogInterceptor
+
+__all__ = [
+ "ConsoleHandler",
+ "FileHandler",
+ "JSONFileHandler",
+ "RotatingFileHandler",
+ "WebSocketLogHandler",
+ "LogInterceptor",
+ "create_task_logger",
+]
+
diff --git a/src/logging/handlers/console.py b/src/logging/handlers/console.py
new file mode 100644
index 000000000..40d0f28d9
--- /dev/null
+++ b/src/logging/handlers/console.py
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+"""
+Console Log Handler
+===================
+
+Color-coded console output with symbols.
+"""
+
+import logging
+import sys
+
+
+class ConsoleFormatter(logging.Formatter):
+ """
+ Clean console formatter with colors and symbols.
+ Format: [Module] Symbol Message
+ """
+
+ # ANSI color codes
+ COLORS = {
+ "DEBUG": "\033[90m", # Gray
+ "INFO": "\033[37m", # White
+ "SUCCESS": "\033[32m", # Green
+ "WARNING": "\033[33m", # Yellow
+ "ERROR": "\033[31m", # Red
+ "CRITICAL": "\033[35m", # Magenta
+ }
+ RESET = "\033[0m"
+ BOLD = "\033[1m"
+ DIM = "\033[2m"
+
+ # Symbols for different log types
+ SYMBOLS = {
+ "DEBUG": "·",
+ "INFO": "●",
+ "SUCCESS": "✓",
+ "WARNING": "⚠",
+ "ERROR": "✗",
+ "CRITICAL": "✗",
+ }
+
+ def format(self, record: logging.LogRecord) -> str:
+ # Get module name (padded to 12 chars for alignment)
+ module = getattr(record, "module_name", record.name)
+ module_padded = f"[{module}]".ljust(14)
+
+ # Get symbol (can be overridden via record.symbol)
+ symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "●"))
+
+ # Get color
+ level = getattr(record, "display_level", record.levelname)
+ color = self.COLORS.get(level, self.COLORS["INFO"])
+
+ # Format message
+ message = record.getMessage()
+
+ # Build output: [Module] ● Message
+ return f"{self.DIM}{module_padded}{self.RESET} {color}{symbol}{self.RESET} {message}"
+
+
+class ConsoleHandler(logging.StreamHandler):
+ """
+ Console handler with color-coded output.
+ """
+
+ def __init__(self, level: int = logging.INFO):
+ """
+ Initialize console handler.
+
+ Args:
+ level: Minimum log level to display
+ """
+ super().__init__(sys.stdout)
+ self.setLevel(level)
+ self.setFormatter(ConsoleFormatter())
+
diff --git a/src/logging/handlers/file.py b/src/logging/handlers/file.py
new file mode 100644
index 000000000..2135748da
--- /dev/null
+++ b/src/logging/handlers/file.py
@@ -0,0 +1,202 @@
+"""
+File Log Handlers
+=================
+
+File-based logging with rotation support.
+"""
+
+from datetime import datetime
+import json
+import logging
+from logging.handlers import RotatingFileHandler as BaseRotatingFileHandler
+from pathlib import Path
+from typing import Optional
+
+
+class FileFormatter(logging.Formatter):
+ """
+ Detailed file formatter for log files.
+ Format: TIMESTAMP [LEVEL] [Module] Message
+ """
+
+ def __init__(self):
+ super().__init__(
+ fmt="%(asctime)s [%(levelname)-8s] [%(module_name)-12s] %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ )
+
+ def format(self, record: logging.LogRecord) -> str:
+ # Ensure module_name exists
+ if not hasattr(record, "module_name"):
+ record.module_name = record.name
+ return super().format(record)
+
+
+class FileHandler(logging.FileHandler):
+ """
+ File handler with detailed formatting.
+ """
+
+ def __init__(
+ self,
+ filename: str,
+ level: int = logging.DEBUG,
+ encoding: str = "utf-8",
+ ):
+ """
+ Initialize file handler.
+
+ Args:
+ filename: Path to log file
+ level: Minimum log level
+ encoding: File encoding
+ """
+ # Ensure directory exists
+ Path(filename).parent.mkdir(parents=True, exist_ok=True)
+
+ super().__init__(filename, encoding=encoding)
+ self.setLevel(level)
+ self.setFormatter(FileFormatter())
+
+
+class RotatingFileHandler(BaseRotatingFileHandler):
+ """
+ Rotating file handler with size-based rotation.
+ """
+
+ def __init__(
+ self,
+ filename: str,
+ level: int = logging.DEBUG,
+ max_bytes: int = 10 * 1024 * 1024, # 10MB
+ backup_count: int = 5,
+ encoding: str = "utf-8",
+ ):
+ """
+ Initialize rotating file handler.
+
+ Args:
+ filename: Path to log file
+ level: Minimum log level
+ max_bytes: Maximum file size before rotation
+ backup_count: Number of backup files to keep
+ encoding: File encoding
+ """
+ # Ensure directory exists
+ Path(filename).parent.mkdir(parents=True, exist_ok=True)
+
+ super().__init__(
+ filename,
+ maxBytes=max_bytes,
+ backupCount=backup_count,
+ encoding=encoding,
+ )
+ self.setLevel(level)
+ self.setFormatter(FileFormatter())
+
+
+class JSONFileHandler(logging.Handler):
+ """
+ A logging handler that writes structured JSON logs to a file.
+ Each line is a valid JSON object (JSONL format).
+
+ Useful for:
+ - LLM call logging
+ - Structured analysis
+ - Log parsing and analysis
+ """
+
+ def __init__(
+ self,
+ filepath: str,
+ level: int = logging.DEBUG,
+ encoding: str = "utf-8",
+ ):
+ """
+ Initialize JSON file handler.
+
+ Args:
+ filepath: Path to log file
+ level: Minimum log level
+ encoding: File encoding
+ """
+ super().__init__()
+
+ # Ensure directory exists
+ Path(filepath).parent.mkdir(parents=True, exist_ok=True)
+
+ self.filepath = filepath
+ self.encoding = encoding
+ self.setLevel(level)
+ self.setFormatter(logging.Formatter("%(message)s"))
+
+ def emit(self, record: logging.LogRecord):
+ """Emit a log record as JSON."""
+ try:
+ # Build JSON entry
+ entry = {
+ "timestamp": datetime.fromtimestamp(record.created).isoformat(),
+ "level": record.levelname,
+ "module": getattr(record, "module_name", record.name),
+ "message": self.format(record),
+ }
+
+ # Add extra fields if present
+ for key in ["symbol", "display_level", "tool_name", "elapsed_ms", "tokens"]:
+ if hasattr(record, key):
+ entry[key] = getattr(record, key)
+
+ # Write to file
+ with open(self.filepath, "a", encoding=self.encoding) as f:
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
+
+ except Exception:
+ self.handleError(record)
+
+
+def create_task_logger(
+ task_id: str,
+ module_name: str,
+ log_dir: str,
+ queue: Optional["asyncio.Queue"] = None,
+) -> logging.Logger:
+ """
+ Create a logger for a specific task with file and optional WebSocket output.
+
+ Args:
+ task_id: Unique task identifier
+ module_name: Module name (e.g., "Solver", "Research")
+ log_dir: Directory for log files
+ queue: Optional asyncio.Queue for WebSocket streaming
+
+ Returns:
+ Configured logger
+ """
+ import asyncio
+ from .websocket import WebSocketLogHandler
+
+ # Create log directory
+ log_path = Path(log_dir)
+ log_path.mkdir(parents=True, exist_ok=True)
+
+ # Create logger
+ logger = logging.getLogger(f"ai_tutor.{module_name}.{task_id}")
+ logger.setLevel(logging.DEBUG)
+ logger.handlers.clear()
+ logger.propagate = False
+
+ # File handler
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ log_file = log_path / f"{module_name}_{task_id}_{timestamp}.log"
+
+ file_handler = FileHandler(str(log_file))
+ logger.addHandler(file_handler)
+
+ # WebSocket handler if queue provided
+ if queue is not None:
+ ws_handler = WebSocketLogHandler(queue)
+ ws_handler.setLevel(logging.INFO)
+ logger.addHandler(ws_handler)
+
+ return logger
+
diff --git a/src/core/logging/handlers.py b/src/logging/handlers/websocket.py
similarity index 50%
rename from src/core/logging/handlers.py
rename to src/logging/handlers/websocket.py
index 1bd73d766..4119599ca 100644
--- a/src/core/logging/handlers.py
+++ b/src/logging/handlers/websocket.py
@@ -1,14 +1,14 @@
+# -*- coding: utf-8 -*-
"""
-Custom Log Handlers
-===================
+WebSocket Log Handler
+=====================
-Handlers for streaming logs to WebSocket, file, etc.
+Handlers for streaming logs to WebSocket clients.
"""
import asyncio
-from datetime import datetime
-import json
import logging
+from typing import Optional
class WebSocketLogHandler(logging.Handler):
@@ -29,7 +29,7 @@ class WebSocketLogHandler(logging.Handler):
# Symbols for different log types (matching ConsoleFormatter)
SYMBOLS = {
"DEBUG": "·",
- "INFO": "○",
+ "INFO": "●",
"SUCCESS": "✓",
"WARNING": "⚠",
"ERROR": "✗",
@@ -56,7 +56,7 @@ class WebSocketLogHandler(logging.Handler):
# Get symbol
display_level = getattr(record, "display_level", record.levelname)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(display_level, "○"))
+ symbol = getattr(record, "symbol", self.SYMBOLS.get(display_level, "●"))
# Get module name
module_name = getattr(record, "module_name", record.name)
@@ -101,7 +101,12 @@ class LogInterceptor:
solver.solve(problem)
"""
- def __init__(self, logger: logging.Logger, queue: asyncio.Queue, include_module: bool = True):
+ def __init__(
+ self,
+ logger: logging.Logger,
+ queue: asyncio.Queue,
+ include_module: bool = True,
+ ):
"""
Initialize log interceptor.
@@ -122,97 +127,3 @@ class LogInterceptor:
"""Remove handler on context exit."""
self.logger.removeHandler(self.handler)
-
-class JSONFileHandler(logging.Handler):
- """
- A logging handler that writes structured JSON logs to a file.
- Each line is a valid JSON object (JSONL format).
-
- Useful for:
- - LLM call logging
- - Structured analysis
- - Log parsing and analysis
- """
-
- def __init__(self, filepath: str, encoding: str = "utf-8"):
- """
- Initialize JSON file handler.
-
- Args:
- filepath: Path to log file
- encoding: File encoding
- """
- super().__init__()
- self.filepath = filepath
- self.encoding = encoding
- self.setFormatter(logging.Formatter("%(message)s"))
-
- def emit(self, record: logging.LogRecord):
- """Emit a log record as JSON."""
- try:
- # Build JSON entry
- entry = {
- "timestamp": datetime.fromtimestamp(record.created).isoformat(),
- "level": record.levelname,
- "module": getattr(record, "module_name", record.name),
- "message": self.format(record),
- }
-
- # Add extra fields if present
- for key in ["symbol", "display_level", "tool_name", "elapsed_ms", "tokens"]:
- if hasattr(record, key):
- entry[key] = getattr(record, key)
-
- # Write to file
- with open(self.filepath, "a", encoding=self.encoding) as f:
- f.write(json.dumps(entry, ensure_ascii=False) + "\n")
-
- except Exception:
- self.handleError(record)
-
-
-def create_task_logger(
- task_id: str, module_name: str, log_dir: str, queue: asyncio.Queue | None = None
-) -> logging.Logger:
- """
- Create a logger for a specific task with file and optional WebSocket output.
-
- Args:
- task_id: Unique task identifier
- module_name: Module name (e.g., "Solver", "Research")
- log_dir: Directory for log files
- queue: Optional asyncio.Queue for WebSocket streaming
-
- Returns:
- Configured logger
- """
- from pathlib import Path
-
- # Create log directory
- log_path = Path(log_dir)
- log_path.mkdir(parents=True, exist_ok=True)
-
- # Create logger
- logger = logging.getLogger(f"ai_tutor.{module_name}.{task_id}")
- logger.setLevel(logging.DEBUG)
- logger.handlers.clear()
- logger.propagate = False
-
- # File handler
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- log_file = log_path / f"{module_name}_{task_id}_{timestamp}.log"
-
- file_handler = logging.FileHandler(log_file, encoding="utf-8")
- file_handler.setLevel(logging.DEBUG)
- file_handler.setFormatter(
- logging.Formatter("%(asctime)s [%(levelname)-8s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
- )
- logger.addHandler(file_handler)
-
- # WebSocket handler if queue provided
- if queue is not None:
- ws_handler = WebSocketLogHandler(queue)
- ws_handler.setLevel(logging.INFO)
- logger.addHandler(ws_handler)
-
- return logger
diff --git a/src/core/logging/logger.py b/src/logging/logger.py
similarity index 88%
rename from src/core/logging/logger.py
rename to src/logging/logger.py
index c312e0625..743971e55 100644
--- a/src/core/logging/logger.py
+++ b/src/logging/logger.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
Core Logger Implementation
==========================
@@ -8,7 +9,7 @@ Format: [Module] Symbol Message
Example outputs:
[Solver] ✓ Ready in 2.3s
[Research] → Starting deep research...
- [Guide] ○ Compiling knowledge points
+ [Guide] → Compiling knowledge points
[Knowledge] ✓ Indexed 150 documents
"""
@@ -18,14 +19,14 @@ import json
import logging
from pathlib import Path
import sys
-from typing import Any
+from typing import Any, Optional
class LogLevel(Enum):
"""Log levels with associated symbols"""
DEBUG = ("DEBUG", "·") # Dot for debug
- INFO = ("INFO", "○") # Circle for info
+ INFO = ("INFO", "●") # Circle for info
SUCCESS = ("SUCCESS", "✓") # Checkmark for success
WARNING = ("WARNING", "⚠") # Warning sign
ERROR = ("ERROR", "✗") # X for error
@@ -56,7 +57,7 @@ class ConsoleFormatter(logging.Formatter):
# Symbols for different log types
SYMBOLS = {
"DEBUG": "·",
- "INFO": "○",
+ "INFO": "●",
"SUCCESS": "✓",
"WARNING": "⚠",
"ERROR": "✗",
@@ -69,7 +70,7 @@ class ConsoleFormatter(logging.Formatter):
module_padded = f"[{module}]".ljust(14)
# Get symbol (can be overridden via record.symbol)
- symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "○"))
+ symbol = getattr(record, "symbol", self.SYMBOLS.get(record.levelname, "●"))
# Get color
level = getattr(record, "display_level", record.levelname)
@@ -78,7 +79,7 @@ class ConsoleFormatter(logging.Formatter):
# Format message
message = record.getMessage()
- # Build output: [Module] ✓ Message
+ # Build output: [Module] ● Message
return f"{self.DIM}{module_padded}{self.RESET} {color}{symbol}{self.RESET} {message}"
@@ -125,7 +126,7 @@ class Logger:
level: str = "INFO",
console_output: bool = True,
file_output: bool = True,
- log_dir: str | None = None,
+ log_dir: Optional[str] = None,
):
"""
Initialize logger.
@@ -150,13 +151,13 @@ class Logger:
if log_dir is None:
# Default: DeepTutor/data/user/logs/
# Use resolve() to get absolute path, ensuring correct project root regardless of working directory
- project_root = Path(__file__).resolve().parent.parent.parent.parent
+ project_root = Path(__file__).resolve().parent.parent.parent
log_dir = project_root / "data" / "user" / "logs"
else:
log_dir = Path(log_dir)
# If relative path, resolve it relative to project root
if not log_dir.is_absolute():
- project_root = Path(__file__).resolve().parent.parent.parent.parent
+ project_root = Path(__file__).resolve().parent.parent.parent
log_dir = project_root / log_dir
log_dir.mkdir(parents=True, exist_ok=True)
@@ -199,8 +200,6 @@ class Logger:
capture_stdout: Ignored (kept for API compatibility)
capture_stderr: Ignored (kept for API compatibility)
"""
- from pathlib import Path
-
task_path = Path(task_log_file)
task_path.parent.mkdir(parents=True, exist_ok=True)
@@ -217,7 +216,7 @@ class Logger:
handler.close()
self._task_handlers.clear()
- def log_stage_progress(self, stage: str, status: str, detail: str | None = None):
+ def log_stage_progress(self, stage: str, status: str, detail: Optional[str] = None):
"""Backwards compatibility alias for stage()"""
self.stage(stage, status, detail)
@@ -231,8 +230,8 @@ class Logger:
self,
level: int,
message: str,
- symbol: str | None = None,
- display_level: str | None = None,
+ symbol: Optional[str] = None,
+ display_level: Optional[str] = None,
**kwargs,
):
"""Internal logging method with extra attributes."""
@@ -256,8 +255,8 @@ class Logger:
self._log(logging.DEBUG, message, symbol="·", **kwargs)
def info(self, message: str, **kwargs):
- """Info level log (○)"""
- self._log(logging.INFO, message, symbol="○", **kwargs)
+ """Info level log (●)"""
+ self._log(logging.INFO, message, symbol="●", **kwargs)
def warning(self, message: str, **kwargs):
"""Warning level log (⚠)"""
@@ -278,7 +277,7 @@ class Logger:
)
# Convenience methods
- def success(self, message: str, elapsed: float | None = None, **kwargs):
+ def success(self, message: str, elapsed: Optional[float] = None, **kwargs):
"""Success log with checkmark (✓)"""
if elapsed is not None:
message = f"{message} in {elapsed:.1f}s"
@@ -292,7 +291,7 @@ class Logger:
"""Completion log with checkmark (✓)"""
self._log(logging.INFO, message, symbol="✓", display_level="SUCCESS", **kwargs)
- def stage(self, stage_name: str, status: str = "start", detail: str | None = None):
+ def stage(self, stage_name: str, status: str = "start", detail: Optional[str] = None):
"""
Log stage progress.
@@ -303,13 +302,13 @@ class Logger:
"""
symbols = {
"start": "▶",
- "running": "○",
+ "running": "●",
"complete": "✓",
- "skip": "↷",
+ "skip": "○",
"error": "✗",
"warning": "⚠",
}
- symbol = symbols.get(status, "○")
+ symbol = symbols.get(status, "●")
message = f"{stage_name}"
if status == "complete":
@@ -333,7 +332,7 @@ class Logger:
self._log(level, message, symbol=symbol, display_level=display_level)
def tool_call(
- self, tool_name: str, status: str = "success", elapsed_ms: float | None = None, **kwargs
+ self, tool_name: str, status: str = "success", elapsed_ms: Optional[float] = None, **kwargs
):
"""
Log tool call.
@@ -343,7 +342,7 @@ class Logger:
status: "success", "error", or "running"
elapsed_ms: Execution time in milliseconds
"""
- symbol = "✓" if status == "success" else ("✗" if status == "error" else "→")
+ symbol = "✓" if status == "success" else ("✗" if status == "error" else "●")
display_level = (
"SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
)
@@ -364,10 +363,10 @@ class Logger:
def llm_call(
self,
model: str,
- agent: str | None = None,
- tokens_in: int | None = None,
- tokens_out: int | None = None,
- elapsed: float | None = None,
+ agent: Optional[str] = None,
+ tokens_in: Optional[int] = None,
+ tokens_out: Optional[int] = None,
+ elapsed: Optional[float] = None,
**kwargs,
):
"""
@@ -391,7 +390,7 @@ class Logger:
parts.append(f"{elapsed:.2f}s")
message = " | ".join(parts)
- self._log(logging.DEBUG, message, symbol="◇")
+ self._log(logging.DEBUG, message, symbol="◆")
def separator(self, char: str = "─", length: int = 50):
"""Print a separator line"""
@@ -403,7 +402,7 @@ class Logger:
tool_input: Any = None,
tool_output: Any = None,
status: str = "success",
- elapsed_ms: float | None = None,
+ elapsed_ms: Optional[float] = None,
**kwargs,
):
"""
@@ -417,7 +416,7 @@ class Logger:
status: "success", "error", or "running"
elapsed_ms: Execution time in milliseconds
"""
- symbol = "✓" if status == "success" else ("✗" if status == "error" else "→")
+ symbol = "✓" if status == "success" else ("✗" if status == "error" else "●")
display_level = (
"SUCCESS" if status == "success" else ("ERROR" if status == "error" else "INFO")
)
@@ -464,7 +463,7 @@ class Logger:
stage: str,
system_prompt: str,
user_prompt: str,
- metadata: dict[str, Any] | None = None,
+ metadata: Optional[dict[str, Any]] = None,
):
"""Log LLM input (debug level, file only)"""
self.debug(
@@ -472,7 +471,7 @@ class Logger:
)
def log_llm_output(
- self, agent_name: str, stage: str, response: str, metadata: dict[str, Any] | None = None
+ self, agent_name: str, stage: str, response: str, metadata: Optional[dict[str, Any]] = None
):
"""Log LLM output (debug level, file only)"""
self.debug(f"LLM Output [{agent_name}:{stage}] response={len(response)}chars")
@@ -484,10 +483,10 @@ class Logger:
system_prompt: str,
user_prompt: str,
response: str,
- agent_name: str | None = None,
- input_tokens: int | None = None,
- output_tokens: int | None = None,
- cost: float | None = None,
+ agent_name: Optional[str] = None,
+ input_tokens: Optional[int] = None,
+ output_tokens: Optional[int] = None,
+ cost: Optional[float] = None,
level: str = "INFO",
):
"""
@@ -518,7 +517,7 @@ class Logger:
if level == "DEBUG":
# Full detailed output
- self._log(log_level, header, symbol="◇")
+ self._log(log_level, header, symbol="◆")
self._log(
log_level, "┌─ Input ──────────────────────────────────────────────", symbol=" "
)
@@ -575,7 +574,7 @@ class Logger:
token_info += f" [Cost: ${cost:.6f}]"
message = f"{header}{token_info}"
- self._log(log_level, message, symbol="◇")
+ self._log(log_level, message, symbol="◆")
def update_token_stats(self, summary: dict[str, Any]):
"""Update token statistics (for display manager compatibility)"""
@@ -602,7 +601,7 @@ def get_logger(
level: str = "INFO",
console_output: bool = True,
file_output: bool = True,
- log_dir: str | None = None,
+ log_dir: Optional[str] = None,
) -> Logger:
"""
Get or create a logger instance.
@@ -622,12 +621,10 @@ def get_logger(
# If log_dir not provided, try to load from config
if log_dir is None:
try:
- from pathlib import Path
-
- from src.core.core import get_path_from_config, load_config_with_main
+ from src.services.config import get_path_from_config, load_config_with_main
# Use resolve() to get absolute path, ensuring correct project root regardless of working directory
- project_root = Path(__file__).resolve().parent.parent.parent.parent
+ project_root = Path(__file__).resolve().parent.parent.parent
config = load_config_with_main(
"solve_config.yaml", project_root
) # Use any config to get main.yaml
@@ -659,7 +656,7 @@ def get_logger(
return _loggers[name]
-def reset_logger(name: str | None = None):
+def reset_logger(name: Optional[str] = None):
"""
Reset logger(s).
@@ -673,39 +670,3 @@ def reset_logger(name: str | None = None):
elif name in _loggers:
del _loggers[name]
-
-if __name__ == "__main__":
- # Demo
- print("\n" + "=" * 60)
- print("DeepTutor Unified Logging System Demo")
- print("=" * 60 + "\n")
-
- # Create loggers for different modules
- solver = get_logger("Solver")
- research = get_logger("Research")
- guide = get_logger("Guide")
-
- # Standard logging
- solver.info("Initializing solver...")
- solver.progress("Loading knowledge base")
- solver.success("Ready", elapsed=2.3)
-
- # Stage logging
- research.stage("Analysis", "start")
- research.stage("Analysis", "running", "Processing 5 sources")
- research.stage("Analysis", "complete")
-
- # Tool calls
- guide.tool_call("RAG Search", status="success", elapsed_ms=150)
- guide.tool_call("Web Search", status="error", elapsed_ms=3000)
-
- # LLM calls
- solver.llm_call("gpt-4", agent="Planner", tokens_in=500, tokens_out=200, elapsed=1.5)
-
- # Warnings and errors
- research.warning("Rate limit approaching")
- guide.error("Failed to connect to database")
-
- print("\n" + "=" * 60)
- print("Demo complete! Logs saved to: user/logs/")
- print("=" * 60)
diff --git a/src/logging/stats/__init__.py b/src/logging/stats/__init__.py
new file mode 100644
index 000000000..5752f3142
--- /dev/null
+++ b/src/logging/stats/__init__.py
@@ -0,0 +1,17 @@
+"""
+Statistics Tracking
+===================
+
+Utilities for tracking LLM usage, costs, and performance metrics.
+"""
+
+from .llm_stats import LLMStats, LLMCall, get_pricing, estimate_tokens, MODEL_PRICING
+
+__all__ = [
+ "LLMStats",
+ "LLMCall",
+ "get_pricing",
+ "estimate_tokens",
+ "MODEL_PRICING",
+]
+
diff --git a/src/core/logging/llm_stats.py b/src/logging/stats/llm_stats.py
similarity index 92%
rename from src/core/logging/llm_stats.py
rename to src/logging/stats/llm_stats.py
index e8d9bf710..2900ddf5c 100644
--- a/src/core/logging/llm_stats.py
+++ b/src/logging/stats/llm_stats.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
LLM Stats Tracker
=================
@@ -6,7 +7,7 @@ Simple utility for tracking LLM token usage and costs across all modules.
Outputs summary to terminal at the end of processing.
Usage:
- from logs.llm_stats import LLMStats
+ from src.logging import LLMStats
stats = LLMStats()
@@ -23,7 +24,8 @@ Usage:
from dataclasses import dataclass, field
from datetime import datetime
-from typing import Any
+from typing import Any, Optional
+
# Model pricing per 1K tokens (USD)
MODEL_PRICING = {
@@ -34,6 +36,8 @@ MODEL_PRICING = {
"gpt-3.5-turbo": {"input": 0.0005, "output": 0.0015},
"deepseek-chat": {"input": 0.00014, "output": 0.00028},
"claude-3-5-sonnet": {"input": 0.003, "output": 0.015},
+ "claude-3-opus": {"input": 0.015, "output": 0.075},
+ "claude-3-haiku": {"input": 0.00025, "output": 0.00125},
}
@@ -85,12 +89,12 @@ class LLMStats:
def add_call(
self,
model: str,
- prompt_tokens: int | None = None,
- completion_tokens: int | None = None,
+ prompt_tokens: Optional[int] = None,
+ completion_tokens: Optional[int] = None,
# Alternative: estimate from text
- system_prompt: str | None = None,
- user_prompt: str | None = None,
- response: str | None = None,
+ system_prompt: Optional[str] = None,
+ user_prompt: Optional[str] = None,
+ response: Optional[str] = None,
):
"""
Add an LLM call to the stats.
@@ -174,3 +178,4 @@ class LLMStats:
self.total_completion_tokens = 0
self.total_cost = 0.0
self.model_used = None
+
diff --git a/src/rag/README.md b/src/rag/README.md
deleted file mode 100644
index 65faf686a..000000000
--- a/src/rag/README.md
+++ /dev/null
@@ -1,265 +0,0 @@
-# RAG Plugin System
-
-A flexible, plugin-based RAG system that allows easy switching between different RAG implementations.
-
-## 🎯 Quick Start
-
-### Using the Default RAG (LightRAG)
-
-```python
-from src.tools.rag_tool import rag_search
-
-# Search with default provider (from .env)
-result = await rag_search(
- query="What is machine learning?",
- kb_name="my_textbook",
- mode="hybrid"
-)
-```
-
-### Switching RAG Providers
-
-**Option 1: Change `.env` file** (affects all users)
-```bash
-# .env
-RAG_PROVIDER=lightrag # or chromadb, pinecone, etc.
-```
-
-**Option 2: Override per request** (temporary)
-```python
-result = await rag_search(
- query="What is ML?",
- kb_name="textbook",
- provider="chromadb" # Override default
-)
-```
-
-## 📦 Available Plugins
-
-| Plugin | Description | Modes | Best For |
-|--------|-------------|-------|----------|
-| **lightrag** | Graph-based RAG with entity extraction | hybrid, local, global, naive | Complex queries, relationships |
-
-## 🔌 Creating a New Plugin
-
-### Step 1: Copy the Template
-
-```bash
-cp src/rag/plugins/_template.py src/rag/plugins/my_rag.py
-```
-
-### Step 2: Implement 3 Functions
-
-```python
-async def initialize_rag(kb_name: str, documents: List[str]) -> bool:
- """Process and store documents"""
- # Your initialization code
- return True
-
-async def search_rag(query: str, kb_name: str, mode: str = "hybrid") -> Dict:
- """Search for information"""
- # Your search code
- return {
- "content": "results here",
- "mode": mode,
- "provider": "my_rag"
- }
-
-async def delete_rag(kb_name: str) -> bool:
- """Delete knowledge base"""
- # Your cleanup code
- return True
-
-# Optional: Metadata
-CONFIG = {
- "name": "My RAG",
- "description": "What this RAG does",
- "supported_modes": ["vector", "hybrid"],
-}
-```
-
-### Step 3: That's It!
-
-Your plugin is automatically discovered. No registration needed!
-
-```python
-# Use your new plugin
-result = await rag_search(
- query="Test",
- kb_name="kb",
- provider="my_rag" # Your plugin name (filename without .py)
-)
-```
-
-## 🛠️ Plugin API Reference
-
-### Functions Required
-
-All plugins must implement these 3 async functions:
-
-#### `initialize_rag(kb_name, documents) -> bool`
-Initialize the RAG system with documents.
-- **kb_name**: Name of the knowledge base
-- **documents**: List of document contents
-- **Returns**: True if successful
-
-#### `search_rag(query, kb_name, mode) -> dict`
-Search for relevant information.
-- **query**: Search query string
-- **kb_name**: Knowledge base to search
-- **mode**: Search mode (provider-specific)
-- **Returns**: Dict with `content`, `mode`, and `provider` keys
-
-#### `delete_rag(kb_name) -> bool`
-Delete a knowledge base.
-- **kb_name**: Knowledge base to delete
-- **Returns**: True if successful
-
-### CONFIG Dictionary (Optional)
-
-```python
-CONFIG = {
- "name": str, # Display name
- "version": str, # Version number
- "author": str, # Author name
- "description": str, # Brief description
- "supported_modes": list, # List of mode strings
- "requires": list, # Python dependencies
-}
-```
-
-## 📚 Usage Examples
-
-### List Available Providers
-
-```python
-from src.tools.rag_tool import get_available_providers
-
-providers = get_available_providers()
-for p in providers:
- print(f"{p['id']}: {p['description']}")
-```
-
-### Initialize a Knowledge Base
-
-```python
-from src.tools.rag_tool import initialize_rag
-
-documents = ["Doc 1 content", "Doc 2 content"]
-success = await initialize_rag("my_kb", documents, provider="lightrag")
-```
-
-### Delete a Knowledge Base
-
-```python
-from src.tools.rag_tool import delete_rag
-
-success = await delete_rag("old_kb")
-```
-
-## 🎨 Example Plugins
-
-### Simple Vector Search (ChromaDB)
-
-```python
-"""ChromaDB Plugin - Simple vector search"""
-import chromadb
-
-_client = chromadb.Client()
-
-async def initialize_rag(kb_name: str, documents: list) -> bool:
- collection = _client.create_collection(kb_name)
- collection.add(
- documents=documents,
- ids=[f"doc_{i}" for i in range(len(documents))]
- )
- return True
-
-async def search_rag(query: str, kb_name: str, mode: str = "hybrid") -> dict:
- collection = _client.get_collection(kb_name)
- results = collection.query(query_texts=[query], n_results=5)
- return {
- "content": "\n\n".join(results['documents'][0]),
- "provider": "chromadb"
- }
-
-async def delete_rag(kb_name: str) -> bool:
- _client.delete_collection(kb_name)
- return True
-
-CONFIG = {
- "name": "ChromaDB",
- "description": "Fast vector search",
- "supported_modes": ["vector"],
-}
-```
-
-Save as `src/rag/plugins/chromadb.py` and it's ready to use!
-
-## 🔧 Advanced Features
-
-### Per-Knowledge-Base Provider
-
-```python
-# KB 1 uses LightRAG (complex, graph-based)
-result1 = await rag_search("complex query", "textbook", provider="lightrag")
-
-# KB 2 uses ChromaDB (simple, fast)
-result2 = await rag_search("simple query", "notes", provider="chromadb")
-```
-
-### Error Handling
-
-```python
-from src.rag.plugin_loader import has_plugin
-
-if has_plugin("my_rag"):
- result = await rag_search(query, kb, provider="my_rag")
-else:
- print("Plugin not available")
-```
-
-### Reload Plugins (Development)
-
-```python
-from src.rag.plugin_loader import reload_plugins
-
-# After modifying a plugin
-reload_plugins()
-```
-
-## 🚀 Benefits
-
-✅ **No Vendor Lock-in**: Switch RAG systems anytime
-✅ **Easy to Extend**: Drop a file, it works
-✅ **Community Friendly**: Anyone can contribute plugins
-✅ **Flexible**: Each KB can use different RAG
-✅ **Simple**: No inheritance, just functions
-
-## 📁 Directory Structure
-
-```
-src/
-└── rag/
- ├── __init__.py
- ├── plugin_loader.py # Auto-discovery engine
- └── plugins/
- ├── __init__.py
- ├── _template.py # Copy this to start
- ├── lightrag.py # Built-in: LightRAG
- └── your_plugin.py # Drop your plugin here!
-```
-
-## 🤝 Contributing Plugins
-
-Want to add a new RAG system? Just:
-
-1. Copy `_template.py`
-2. Fill in 3 functions
-3. Submit PR
-
-That's it! No complex registration or factory patterns needed.
-
-## 📝 License
-
-Same as DeepTutor project license.
diff --git a/src/rag/__init__.py b/src/rag/__init__.py
deleted file mode 100644
index 250a0972c..000000000
--- a/src/rag/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-"""
-RAG Plugin System
-Provides flexible, pluggable RAG implementations
-"""
diff --git a/src/rag/plugin_loader.py b/src/rag/plugin_loader.py
deleted file mode 100644
index 717074fae..000000000
--- a/src/rag/plugin_loader.py
+++ /dev/null
@@ -1,163 +0,0 @@
-"""
-RAG Plugin Loader
-Automatically discovers and loads RAG plugins from the plugins directory.
-"""
-
-import importlib
-import sys
-from pathlib import Path
-from typing import Dict, List, Callable, Any
-import logging
-
-logger = logging.getLogger(__name__)
-
-
-class PluginLoader:
- """Discovers and manages RAG plugins"""
-
- def __init__(self):
- self.plugins: Dict[str, Dict[str, Any]] = {}
- self._load_plugins()
-
- def _load_plugins(self):
- """Auto-discover all plugins in plugins/ folder"""
- plugins_dir = Path(__file__).parent / "plugins"
-
- if not plugins_dir.exists():
- logger.warning(f"Plugins directory not found: {plugins_dir}")
- return
-
- # Find all Python files in plugins directory
- for plugin_file in plugins_dir.glob("*.py"):
- # Skip private files and template
- if plugin_file.stem.startswith("_"):
- continue
-
- try:
- # Import plugin module
- module_name = f"src.rag.plugins.{plugin_file.stem}"
- module = importlib.import_module(module_name)
-
- # Verify it has required functions
- required_functions = ["initialize_rag", "search_rag", "delete_rag"]
- missing = [func for func in required_functions if not hasattr(module, func)]
-
- if missing:
- logger.warning(
- f"Plugin {plugin_file.stem} missing required functions: {missing}"
- )
- continue
-
- # Load plugin metadata
- config = getattr(module, "CONFIG", {})
- plugin_name = config.get("name", plugin_file.stem)
-
- # Store plugin
- self.plugins[plugin_file.stem] = {
- "module": module,
- "config": config,
- "initialize": module.initialize_rag,
- "search": module.search_rag,
- "delete": module.delete_rag,
- "name": plugin_name,
- }
-
- logger.info(f"✅ Loaded RAG plugin: {plugin_file.stem} ({plugin_name})")
-
- except Exception as e:
- logger.error(f"❌ Failed to load plugin {plugin_file.stem}: {e}")
-
- def get_plugin(self, name: str) -> Dict[str, Any]:
- """
- Get plugin by name.
-
- Args:
- name: Plugin identifier (filename without .py)
-
- Returns:
- Dictionary with plugin functions and metadata
-
- Raises:
- ValueError: If plugin not found
- """
- if name not in self.plugins:
- available = list(self.plugins.keys())
- raise ValueError(
- f"RAG plugin '{name}' not found. "
- f"Available plugins: {available}"
- )
- return self.plugins[name]
-
- def list_plugins(self) -> List[Dict[str, Any]]:
- """
- List all available plugins with their metadata.
-
- Returns:
- List of plugin information dictionaries
- """
- return [
- {
- "id": plugin_id,
- "name": plugin["config"].get("name", plugin_id),
- "version": plugin["config"].get("version", "unknown"),
- "description": plugin["config"].get("description", ""),
- "author": plugin["config"].get("author", ""),
- "supported_modes": plugin["config"].get("supported_modes", []),
- "requires": plugin["config"].get("requires", []),
- }
- for plugin_id, plugin in self.plugins.items()
- ]
-
- def has_plugin(self, name: str) -> bool:
- """Check if a plugin is available"""
- return name in self.plugins
-
- def reload_plugins(self):
- """Reload all plugins (useful for development)"""
- self.plugins.clear()
- self._load_plugins()
-
-
-# Global loader instance
-_loader = None
-
-
-def get_loader() -> PluginLoader:
- """Get the global plugin loader instance"""
- global _loader
- if _loader is None:
- _loader = PluginLoader()
- return _loader
-
-
-def get_plugin(name: str) -> Dict[str, Any]:
- """
- Get a RAG plugin by name.
-
- Args:
- name: Plugin identifier
-
- Returns:
- Plugin dictionary with functions
- """
- return get_loader().get_plugin(name)
-
-
-def list_plugins() -> List[Dict[str, Any]]:
- """
- List all available RAG plugins.
-
- Returns:
- List of plugin metadata
- """
- return get_loader().list_plugins()
-
-
-def has_plugin(name: str) -> bool:
- """Check if a plugin exists"""
- return get_loader().has_plugin(name)
-
-
-def reload_plugins():
- """Reload all plugins"""
- get_loader().reload_plugins()
diff --git a/src/rag/plugins/__init__.py b/src/rag/plugins/__init__.py
deleted file mode 100644
index 9f530a310..000000000
--- a/src/rag/plugins/__init__.py
+++ /dev/null
@@ -1,4 +0,0 @@
-"""
-RAG Plugins
-Drop any .py file here implementing the plugin interface to add new RAG systems
-"""
diff --git a/src/rag/plugins/_template.py b/src/rag/plugins/_template.py
deleted file mode 100644
index 8319d6658..000000000
--- a/src/rag/plugins/_template.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""
-RAG Plugin Template
-Copy this file and implement these functions to create a new RAG plugin.
-No inheritance needed - just implement these 3 functions!
-
-Example:
- cp _template.py my_rag.py
- # Fill in the functions below
- # Done! Plugin auto-discovered
-"""
-
-from typing import Dict, List
-
-
-async def initialize_rag(kb_name: str, documents: List[str]) -> bool:
- """
- Process and store documents in the knowledge base.
-
- Args:
- kb_name: Name of the knowledge base
- documents: List of document contents to index
-
- Returns:
- True if successful, False otherwise
-
- Example:
- Initialize your RAG system, process documents, create indexes, etc.
- """
- # TODO: Implement your initialization logic
- raise NotImplementedError("initialize_rag not implemented")
-
-
-async def search_rag(query: str, kb_name: str, mode: str = "hybrid") -> Dict:
- """
- Search for relevant information in the knowledge base.
-
- Args:
- query: Search query string
- kb_name: Name of the knowledge base to search
- mode: Search mode (e.g., "hybrid", "vector", "semantic")
-
- Returns:
- Dictionary with at least:
- {
- "content": str, # Retrieved content
- "mode": str, # Mode used
- "provider": str # Your plugin name
- }
-
- Example:
- Perform semantic/vector/graph search and return results
- """
- # TODO: Implement your search logic
- raise NotImplementedError("search_rag not implemented")
-
-
-async def delete_rag(kb_name: str) -> bool:
- """
- Delete a knowledge base and all associated data.
-
- Args:
- kb_name: Name of the knowledge base to delete
-
- Returns:
- True if successful, False otherwise
-
- Example:
- Clean up indexes, delete files, free resources, etc.
- """
- # TODO: Implement your deletion logic
- raise NotImplementedError("delete_rag not implemented")
-
-
-# Optional: Plugin metadata (recommended)
-CONFIG = {
- "name": "My RAG Plugin",
- "version": "1.0.0",
- "author": "Your Name",
- "description": "Brief description of what this RAG does",
- "supported_modes": ["hybrid", "vector"], # List of supported search modes
- "requires": ["package1", "package2"], # Python dependencies
-}
diff --git a/src/rag/plugins/lightrag.py b/src/rag/plugins/lightrag.py
deleted file mode 100644
index 84ffec636..000000000
--- a/src/rag/plugins/lightrag.py
+++ /dev/null
@@ -1,202 +0,0 @@
-"""
-LightRAG Plugin
-Graph-based RAG with entity extraction and knowledge graph
-"""
-
-from pathlib import Path
-from typing import Dict, List
-import sys
-
-# Add raganything module path
-project_root = Path(__file__).parent.parent.parent.parent
-raganything_path = project_root.parent / "raganything" / "RAG-Anything"
-if raganything_path.exists():
- sys.path.insert(0, str(raganything_path))
-
-from lightrag.llm.openai import openai_complete_if_cache, openai_embed
-from lightrag.utils import EmbeddingFunc
-from raganything import RAGAnything, RAGAnythingConfig
-
-from src.core.core import get_embedding_config, get_llm_config
-from src.core.logging import LightRAGLogContext
-from src.knowledge.manager import KnowledgeBaseManager
-
-# Cache RAG instances to avoid reloading
-_rag_instances = {}
-
-
-def _get_rag_instance(working_dir: str) -> RAGAnything:
- """Get or create RAG instance for a working directory"""
- if working_dir in _rag_instances:
- return _rag_instances[working_dir]
-
- # Get configurations
- llm_config = get_llm_config()
- embedding_config = get_embedding_config()
-
- # LLM function
- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
- return openai_complete_if_cache(
- llm_config["model"],
- prompt,
- system_prompt=system_prompt,
- history_messages=history_messages,
- api_key=llm_config["api_key"],
- base_url=llm_config["base_url"],
- **kwargs,
- )
-
- # Embedding function
- embedding_func = EmbeddingFunc(
- embedding_dim=embedding_config["dim"],
- max_token_size=embedding_config["max_tokens"],
- func=lambda texts: openai_embed(
- texts,
- model=embedding_config["model"],
- api_key=embedding_config["api_key"],
- base_url=embedding_config["base_url"],
- ),
- )
-
- # Create RAG instance
- config = RAGAnythingConfig(
- working_dir=working_dir,
- enable_image_processing=True,
- enable_table_processing=True,
- enable_equation_processing=True,
- )
-
- rag = RAGAnything(
- config=config,
- llm_model_func=llm_model_func,
- embedding_func=embedding_func,
- )
-
- _rag_instances[working_dir] = rag
- return rag
-
-
-def _get_working_dir(kb_name: str, kb_base_dir: str = None) -> str:
- """Get RAG storage working directory for a knowledge base"""
- if kb_base_dir is None:
- project_root = Path(__file__).parent.parent.parent.parent
- kb_base_dir = str(project_root / "data" / "knowledge_bases")
-
- if kb_name:
- kb_dir = Path(kb_base_dir) / kb_name
- else:
- # Use default KB if no name provided
- from src.knowledge.manager import KnowledgeBaseManager
- kb_manager = KnowledgeBaseManager(kb_base_dir)
- kb_dir = Path(kb_base_dir) / kb_manager.get_default()
-
- working_dir = str(kb_dir / "rag_storage")
-
- # Create directory if it doesn't exist
- Path(working_dir).mkdir(parents=True, exist_ok=True)
-
- return working_dir
-
-
-async def initialize_rag(kb_name: str, documents: List[str]) -> bool:
- """
- Initialize LightRAG with documents.
-
- Args:
- kb_name: Knowledge base name
- documents: List of document contents to index
-
- Returns:
- True if successful
- """
- try:
- working_dir = _get_working_dir(kb_name)
- rag = _get_rag_instance(working_dir)
-
- # Ensure initialization
- await rag._ensure_lightrag_initialized()
-
- # Insert documents
- for doc in documents:
- await rag.ainsert(doc)
-
- return True
- except Exception as e:
- raise Exception(f"LightRAG initialization failed: {e}")
-
-
-async def search_rag(query: str, kb_name: str, mode: str = "hybrid", only_need_context: bool = False, **kwargs) -> Dict:
- """
- Search using LightRAG.
-
- Args:
- query: Search query
- kb_name: Knowledge base name
- mode: Search mode (hybrid, local, global, naive)
- only_need_context: If True, only return context without generating answer
- **kwargs: Additional parameters (ignored for compatibility)
-
- Returns:
- Dictionary with search results
- """
- try:
- working_dir = _get_working_dir(kb_name)
- rag = _get_rag_instance(working_dir)
-
- # Use log forwarding context
- with LightRAGLogContext(scene="rag_search"):
- # Ensure initialization
- await rag._ensure_lightrag_initialized()
-
- # Execute query
- answer = await rag.aquery(query, mode=mode, only_need_context=only_need_context)
- answer_str = answer if isinstance(answer, str) else str(answer)
-
- return {
- "query": query,
- "answer": answer_str,
- "content": answer_str,
- "mode": mode,
- "provider": "lightrag"
- }
- except Exception as e:
- raise Exception(f"LightRAG search failed: {e}")
-
-
-async def delete_rag(kb_name: str) -> bool:
- """
- Delete LightRAG knowledge base.
-
- Args:
- kb_name: Knowledge base name
-
- Returns:
- True if successful
- """
- try:
- working_dir = _get_working_dir(kb_name)
-
- # Remove from cache
- if working_dir in _rag_instances:
- del _rag_instances[working_dir]
-
- # Delete storage directory
- storage_path = Path(working_dir)
- if storage_path.exists():
- import shutil
- shutil.rmtree(storage_path)
-
- return True
- except Exception as e:
- raise Exception(f"LightRAG deletion failed: {e}")
-
-
-# Plugin metadata
-CONFIG = {
- "name": "LightRAG",
- "version": "1.0.0",
- "author": "DeepTutor Team",
- "description": "Graph-based RAG with entity extraction and knowledge graph",
- "supported_modes": ["hybrid", "local", "global", "naive"],
- "requires": ["lightrag", "raganything", "networkx"]
-}
diff --git a/src/rag/plugins/llamaindex.py b/src/rag/plugins/llamaindex.py
deleted file mode 100644
index ae589e06f..000000000
--- a/src/rag/plugins/llamaindex.py
+++ /dev/null
@@ -1,255 +0,0 @@
-"""
-LlamaIndex Plugin - Simple and fast RAG system
-Best for general documents and Q&A - much faster than graph-based approaches
-"""
-
-from pathlib import Path
-from typing import Dict, List
-import os
-
-try:
- from llama_index.core import (
- VectorStoreIndex,
- SimpleDirectoryReader,
- StorageContext,
- Settings,
- Document,
- )
- from llama_index.core import load_index_from_storage
- from llama_index.embeddings.openai import OpenAIEmbedding
- LLAMAINDEX_AVAILABLE = True
-except ImportError:
- LLAMAINDEX_AVAILABLE = False
-
-from src.core.core import get_embedding_config, get_llm_config
-
-# Cache indices to avoid reloading
-_indices = {}
-
-
-def _get_storage_dir(kb_name: str) -> Path:
- """Get storage directory for a knowledge base"""
- project_root = Path(__file__).parent.parent.parent.parent
- storage_dir = project_root / "data" / "knowledge_bases" / kb_name / "llamaindex_storage"
-
- # Create directory if it doesn't exist
- storage_dir.mkdir(parents=True, exist_ok=True)
-
- return storage_dir
-
-
-def _configure_settings():
- """Configure LlamaIndex with embedding settings"""
- if not LLAMAINDEX_AVAILABLE:
- raise ImportError("LlamaIndex not installed. Run: pip install llama-index llama-index-embeddings-openai")
-
- try:
- embedding_config = get_embedding_config()
-
- # Configure embedding model
- Settings.embed_model = OpenAIEmbedding(
- api_key=embedding_config["api_key"],
- api_base=embedding_config["base_url"],
- model=embedding_config["model"],
- embed_batch_size=10,
- )
-
- # Set chunk size and overlap
- Settings.chunk_size = 512
- Settings.chunk_overlap = 50
-
- except Exception as e:
- raise Exception(f"Failed to configure LlamaIndex settings: {e}")
-
-
-async def initialize_rag(kb_name: str, documents: List[str]) -> bool:
- """
- Initialize LlamaIndex with documents.
-
- Args:
- kb_name: Knowledge base name
- documents: List of document contents to index
-
- Returns:
- True if successful
- """
- if not LLAMAINDEX_AVAILABLE:
- raise ImportError("LlamaIndex not installed. Run: pip install llama-index llama-index-embeddings-openai")
-
- try:
- # Configure settings
- _configure_settings()
-
- # Get storage directory
- storage_dir = _get_storage_dir(kb_name)
- storage_dir.mkdir(parents=True, exist_ok=True)
-
- # Create temporary directory for documents
- temp_dir = storage_dir / "temp_docs"
- temp_dir.mkdir(exist_ok=True)
-
- # Save documents to temporary files
- doc_files = []
- for idx, doc_content in enumerate(documents):
- doc_file = temp_dir / f"doc_{idx}.txt"
- doc_file.write_text(doc_content, encoding='utf-8')
- doc_files.append(str(doc_file))
-
- # Load documents using SimpleDirectoryReader
- reader = SimpleDirectoryReader(input_dir=str(temp_dir))
- loaded_docs = reader.load_data()
-
- # Create index from documents
- index = VectorStoreIndex.from_documents(
- loaded_docs,
- show_progress=True
- )
-
- # Persist to disk
- index.storage_context.persist(persist_dir=str(storage_dir))
-
- # Cache in memory
- _indices[kb_name] = index
-
- # Cleanup temporary files
- import shutil
- shutil.rmtree(temp_dir)
-
- return True
-
- except Exception as e:
- raise Exception(f"LlamaIndex initialization failed: {e}")
-
-
-async def search_rag(query: str, kb_name: str, mode: str = "semantic", only_need_context: bool = False, **kwargs) -> Dict:
- """
- Search using LlamaIndex.
-
- Args:
- query: Search query
- kb_name: Knowledge base name
- mode: Search mode (semantic, hybrid)
- only_need_context: If True, only return context without generating answer
- **kwargs: Additional parameters (ignored for compatibility)
-
- Returns:
- Dictionary with search results
- """
- if not LLAMAINDEX_AVAILABLE:
- raise ImportError("LlamaIndex not installed. Run: pip install llama-index llama-index-embeddings-openai")
-
- try:
- # Configure settings
- _configure_settings()
-
- # Get or load index
- if kb_name not in _indices:
- storage_dir = _get_storage_dir(kb_name)
-
- if not storage_dir.exists():
- raise ValueError(
- f"Knowledge base '{kb_name}' not initialized. "
- "Please initialize it first."
- )
-
- # Load from disk
- storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))
- _indices[kb_name] = load_index_from_storage(storage_context)
-
- index = _indices[kb_name]
-
- # Determine query parameters based on mode
- if mode == "hybrid":
- # Tree summarize for better synthesis
- response_mode = "tree_summarize"
- similarity_top_k = 5
- else: # semantic
- # Compact for faster responses
- response_mode = "compact"
- similarity_top_k = 3
-
- # If only context needed, use retriever instead of query engine
- if only_need_context:
- # Get retriever for raw context
- retriever = index.as_retriever(similarity_top_k=similarity_top_k)
- nodes = retriever.retrieve(query)
-
- # Combine context from all nodes
- context_parts = [node.text for node in nodes]
- context_text = "\n\n".join(context_parts)
-
- return {
- "query": query,
- "answer": context_text,
- "content": context_text,
- "mode": mode,
- "provider": "llamaindex",
- "sources": len(nodes)
- }
-
- # Create query engine for full answer generation
- query_engine = index.as_query_engine(
- similarity_top_k=similarity_top_k,
- response_mode=response_mode,
- )
-
- # Execute query
- response = query_engine.query(query)
-
- # Extract response text
- response_text = str(response)
-
- # Get source information if available
- source_count = 0
- if hasattr(response, 'source_nodes'):
- source_count = len(response.source_nodes)
-
- return {
- "query": query,
- "answer": response_text,
- "content": response_text,
- "mode": mode,
- "provider": "llamaindex",
- "sources": source_count
- }
-
- except Exception as e:
- raise Exception(f"LlamaIndex search failed: {e}")
-
-
-async def delete_rag(kb_name: str) -> bool:
- """
- Delete LlamaIndex knowledge base.
-
- Args:
- kb_name: Knowledge base name
-
- Returns:
- True if successful
- """
- try:
- # Remove from cache
- if kb_name in _indices:
- del _indices[kb_name]
-
- # Delete storage directory
- storage_dir = _get_storage_dir(kb_name)
- if storage_dir.exists():
- import shutil
- shutil.rmtree(storage_dir)
-
- return True
-
- except Exception as e:
- raise Exception(f"LlamaIndex deletion failed: {e}")
-
-
-# Plugin metadata
-CONFIG = {
- "name": "LlamaIndex",
- "version": "1.0.0",
- "author": "DeepTutor Team",
- "description": "Simple and fast vector-based RAG - great for general documents and Q&A",
- "supported_modes": ["semantic", "hybrid"],
- "requires": ["llama-index", "llama-index-embeddings-openai"]
-}
diff --git a/src/services/__init__.py b/src/services/__init__.py
new file mode 100644
index 000000000..6954e121a
--- /dev/null
+++ b/src/services/__init__.py
@@ -0,0 +1,56 @@
+"""
+Services Layer
+==============
+
+Unified service layer for DeepTutor providing:
+- LLM client and configuration
+- Embedding client and configuration
+- RAG pipelines and components
+- Prompt management
+- TTS configuration
+- System setup utilities
+- Configuration loading
+
+Usage:
+ from src.services.llm import get_llm_client
+ from src.services.embedding import get_embedding_client
+ from src.services.rag import get_pipeline
+ from src.services.prompt import get_prompt_manager
+ from src.services.tts import get_tts_config
+ from src.services.setup import init_user_directories
+ from src.services.config import load_config_with_main
+
+ # LLM
+ llm = get_llm_client()
+ response = await llm.complete("Hello, world!")
+
+ # Embedding
+ embed = get_embedding_client()
+ vectors = await embed.embed(["text1", "text2"])
+
+ # RAG
+ pipeline = get_pipeline("raganything")
+ result = await pipeline.search("query", "kb_name")
+
+ # Prompt
+ pm = get_prompt_manager()
+ prompts = pm.load_prompts("guide", "tutor_agent")
+"""
+
+from . import llm
+from . import embedding
+from . import rag
+from . import prompt
+from . import tts
+from . import setup
+from . import config
+
+__all__ = [
+ "llm",
+ "embedding",
+ "rag",
+ "prompt",
+ "tts",
+ "setup",
+ "config",
+]
diff --git a/src/services/config/__init__.py b/src/services/config/__init__.py
new file mode 100644
index 000000000..61471fa7f
--- /dev/null
+++ b/src/services/config/__init__.py
@@ -0,0 +1,34 @@
+"""
+Configuration Service
+=====================
+
+Unified configuration loading for all DeepTutor modules.
+
+Usage:
+ from src.services.config import load_config_with_main, PROJECT_ROOT
+
+ # Load module configuration
+ config = load_config_with_main("solve_config.yaml")
+
+ # Get agent parameters
+ params = get_agent_params("guide")
+"""
+
+from .loader import (
+ PROJECT_ROOT,
+ load_config_with_main,
+ get_path_from_config,
+ parse_language,
+ get_agent_params,
+ _deep_merge,
+)
+
+__all__ = [
+ "PROJECT_ROOT",
+ "load_config_with_main",
+ "get_path_from_config",
+ "parse_language",
+ "get_agent_params",
+ "_deep_merge",
+]
+
diff --git a/src/services/config/loader.py b/src/services/config/loader.py
new file mode 100644
index 000000000..57c658502
--- /dev/null
+++ b/src/services/config/loader.py
@@ -0,0 +1,207 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+Configuration Loader
+====================
+
+Unified configuration loading for all DeepTutor modules.
+Provides YAML configuration loading, path resolution, and language parsing.
+"""
+
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+# PROJECT_ROOT points to the actual project root directory (DeepTutor/)
+# Path(__file__) = src/services/config/loader.py
+# .parent = src/services/config/
+# .parent.parent = src/services/
+# .parent.parent.parent = src/
+# .parent.parent.parent.parent = DeepTutor/ (project root)
+PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
+
+
+def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
+ """
+ Deep merge two dictionaries, values in override will override values in base
+
+ Args:
+ base: Base configuration
+ override: Override configuration
+
+ Returns:
+ Merged configuration
+ """
+ result = base.copy()
+
+ for key, value in override.items():
+ if key in result and isinstance(result[key], dict) and isinstance(value, dict):
+ # Recursively merge dictionaries
+ result[key] = _deep_merge(result[key], value)
+ else:
+ # Direct override
+ result[key] = value
+
+ return result
+
+
+def load_config_with_main(config_file: str, project_root: Path | None = None) -> dict[str, Any]:
+ """
+ Load configuration file, automatically merge with main.yaml common configuration
+
+ Args:
+ config_file: Sub-module configuration file name (e.g., "solve_config.yaml")
+ project_root: Project root directory (if None, will try to auto-detect)
+
+ Returns:
+ Merged configuration dictionary
+ """
+ if project_root is None:
+ project_root = PROJECT_ROOT
+
+ config_dir = project_root / "config"
+
+ # 1. Load main.yaml (common configuration)
+ main_config = {}
+ main_config_path = config_dir / "main.yaml"
+ if main_config_path.exists():
+ try:
+ with open(main_config_path, encoding="utf-8") as f:
+ main_config = yaml.safe_load(f) or {}
+ except Exception as e:
+ print(f"⚠️ Failed to load main.yaml: {e}")
+
+ # 2. Load sub-module configuration file
+ module_config = {}
+ module_config_path = config_dir / config_file
+ if module_config_path.exists():
+ try:
+ with open(module_config_path, encoding="utf-8") as f:
+ module_config = yaml.safe_load(f) or {}
+ except Exception as e:
+ print(f"⚠️ Failed to load {config_file}: {e}")
+
+ # 3. Merge configurations: main.yaml as base, sub-module config overrides
+ merged_config = _deep_merge(main_config, module_config)
+
+ return merged_config
+
+
+def get_path_from_config(config: dict[str, Any], path_key: str, default: str = None) -> str:
+ """
+ Get path from configuration, supports searching in paths and system
+
+ Args:
+ config: Configuration dictionary
+ path_key: Path key name (e.g., "log_dir", "workspace")
+ default: Default value
+
+ Returns:
+ Path string
+ """
+ # Priority: search in paths
+ if "paths" in config and path_key in config["paths"]:
+ return config["paths"][path_key]
+
+ # Search in system (backward compatibility)
+ if "system" in config and path_key in config["system"]:
+ return config["system"][path_key]
+
+ # Search in tools (e.g., run_code.workspace)
+ if "tools" in config:
+ if path_key == "workspace" and "run_code" in config["tools"]:
+ return config["tools"]["run_code"].get("workspace", default)
+
+ return default
+
+
+def parse_language(language: Any) -> str:
+ """
+ Unified language configuration parser, supports multiple input formats
+
+ Supported language representations:
+ - English: "en", "english", "English"
+ - Chinese: "zh", "chinese", "Chinese"
+
+ Args:
+ language: Language configuration value (can be "zh"/"en"/"Chinese"/"English" etc.)
+
+ Returns:
+ Standardized language code: 'zh' or 'en', defaults to 'zh'
+ """
+ if not language:
+ return "zh"
+
+ if isinstance(language, str):
+ lang_lower = language.lower()
+ if lang_lower in ["en", "english"]:
+ return "en"
+ if lang_lower in ["zh", "chinese"]:
+ return "zh"
+
+ return "zh" # Default Chinese
+
+
+def get_agent_params(module_name: str) -> dict:
+ """
+ Get agent parameters (temperature, max_tokens) for a specific module.
+
+ This function loads parameters from config/agents.yaml which serves as the
+ SINGLE source of truth for all agent temperature and max_tokens settings.
+
+ Args:
+ module_name: Module name, one of:
+ - "guide": Guide module agents
+ - "solve": Solve module agents
+ - "research": Research module agents
+ - "question": Question module agents
+ - "ideagen": IdeaGen module agents
+ - "co_writer": CoWriter module agents
+ - "narrator": Narrator agent (independent, for TTS)
+
+ Returns:
+ dict: Dictionary containing:
+ - temperature: float, default 0.5
+ - max_tokens: int, default 4096
+
+ Example:
+ >>> params = get_agent_params("guide")
+ >>> params["temperature"] # 0.5
+ >>> params["max_tokens"] # 8192
+ """
+ # Default values
+ defaults = {
+ "temperature": 0.5,
+ "max_tokens": 4096,
+ }
+
+ # Try to load from agents.yaml
+ try:
+ config_path = PROJECT_ROOT / "config" / "agents.yaml"
+
+ if config_path.exists():
+ with open(config_path, encoding="utf-8") as f:
+ agents_config = yaml.safe_load(f) or {}
+
+ if module_name in agents_config:
+ module_config = agents_config[module_name]
+ return {
+ "temperature": module_config.get("temperature", defaults["temperature"]),
+ "max_tokens": module_config.get("max_tokens", defaults["max_tokens"]),
+ }
+ except Exception as e:
+ print(f"⚠️ Failed to load agents.yaml: {e}, using defaults")
+
+ return defaults
+
+
+__all__ = [
+ "PROJECT_ROOT",
+ "load_config_with_main",
+ "get_path_from_config",
+ "parse_language",
+ "get_agent_params",
+ "_deep_merge",
+]
+
diff --git a/src/services/embedding/__init__.py b/src/services/embedding/__init__.py
new file mode 100644
index 000000000..3d3edfb90
--- /dev/null
+++ b/src/services/embedding/__init__.py
@@ -0,0 +1,28 @@
+"""
+Embedding Service
+=================
+
+Unified embedding client for all DeepTutor modules.
+
+Usage:
+ from src.services.embedding import get_embedding_client, EmbeddingClient, EmbeddingConfig
+
+ # Get singleton client
+ client = get_embedding_client()
+ vectors = await client.embed(["text1", "text2"])
+
+ # Get LightRAG-compatible EmbeddingFunc
+ embed_func = client.get_embedding_func()
+"""
+
+from .client import EmbeddingClient, get_embedding_client, reset_embedding_client
+from .config import EmbeddingConfig, get_embedding_config
+
+__all__ = [
+ "EmbeddingClient",
+ "EmbeddingConfig",
+ "get_embedding_client",
+ "get_embedding_config",
+ "reset_embedding_client",
+]
+
diff --git a/src/services/embedding/client.py b/src/services/embedding/client.py
new file mode 100644
index 000000000..96ca6e0db
--- /dev/null
+++ b/src/services/embedding/client.py
@@ -0,0 +1,116 @@
+"""
+Embedding Client
+================
+
+Unified embedding client for all DeepTutor services.
+"""
+
+from typing import List, Optional
+
+from src.logging import get_logger
+from .config import EmbeddingConfig, get_embedding_config
+
+
+class EmbeddingClient:
+ """
+ Unified embedding client for all services.
+
+ Wraps the underlying embedding API (OpenAI-compatible) with a consistent interface.
+ """
+
+ def __init__(self, config: Optional[EmbeddingConfig] = None):
+ """
+ Initialize embedding client.
+
+ Args:
+ config: Embedding configuration. If None, loads from environment.
+ """
+ self.config = config or get_embedding_config()
+ self.logger = get_logger("EmbeddingClient")
+
+ async def embed(self, texts: List[str]) -> List[List[float]]:
+ """
+ Get embeddings for texts.
+
+ Args:
+ texts: List of texts to embed
+
+ Returns:
+ List of embedding vectors
+ """
+ from lightrag.llm.openai import openai_embed
+
+ return await openai_embed(
+ texts,
+ model=self.config.model,
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ )
+
+ def embed_sync(self, texts: List[str]) -> List[List[float]]:
+ """
+ Synchronous wrapper for embed().
+
+ Use this when you need to call from non-async context.
+ """
+ import asyncio
+
+ try:
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ import concurrent.futures
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(asyncio.run, self.embed(texts))
+ return future.result()
+ else:
+ return loop.run_until_complete(self.embed(texts))
+ except RuntimeError:
+ return asyncio.run(self.embed(texts))
+
+ def get_embedding_func(self):
+ """
+ Get an EmbeddingFunc compatible with LightRAG.
+
+ Returns:
+ EmbeddingFunc instance
+ """
+ from lightrag.utils import EmbeddingFunc
+ from lightrag.llm.openai import openai_embed
+
+ return EmbeddingFunc(
+ embedding_dim=self.config.dim,
+ max_token_size=self.config.max_tokens,
+ func=lambda texts: openai_embed(
+ texts,
+ model=self.config.model,
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ ),
+ )
+
+
+# Singleton instance
+_client: Optional[EmbeddingClient] = None
+
+
+def get_embedding_client(config: Optional[EmbeddingConfig] = None) -> EmbeddingClient:
+ """
+ Get or create the singleton embedding client.
+
+ Args:
+ config: Optional configuration. Only used on first call.
+
+ Returns:
+ EmbeddingClient instance
+ """
+ global _client
+ if _client is None:
+ _client = EmbeddingClient(config)
+ return _client
+
+
+def reset_embedding_client():
+ """Reset the singleton embedding client."""
+ global _client
+ _client = None
+
diff --git a/src/services/embedding/config.py b/src/services/embedding/config.py
new file mode 100644
index 000000000..6227a7918
--- /dev/null
+++ b/src/services/embedding/config.py
@@ -0,0 +1,89 @@
+"""
+Embedding Configuration
+=======================
+
+Configuration management for embedding services.
+"""
+
+from dataclasses import dataclass
+import os
+from pathlib import Path
+from typing import Optional
+
+from dotenv import load_dotenv
+
+# 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)
+
+
+@dataclass
+class EmbeddingConfig:
+ """Embedding configuration dataclass."""
+
+ model: str
+ api_key: str
+ base_url: Optional[str] = None
+ binding: str = "openai"
+ dim: int = 3072
+ max_tokens: int = 8192
+
+
+def _strip_value(value: Optional[str]) -> Optional[str]:
+ """Remove leading/trailing whitespace and quotes from string."""
+ if value is None:
+ return None
+ return value.strip().strip("\"'")
+
+
+def _to_int(value: Optional[str], default: int) -> int:
+ """Convert environment variable to int, fallback to default value on failure."""
+ try:
+ return int(value) if value is not None else default
+ except (TypeError, ValueError):
+ return default
+
+
+def get_embedding_config() -> EmbeddingConfig:
+ """
+ Load embedding configuration from environment variables.
+
+ Returns:
+ EmbeddingConfig: Configuration dataclass
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ binding = _strip_value(os.getenv("EMBEDDING_BINDING", "openai"))
+ model = _strip_value(os.getenv("EMBEDDING_MODEL"))
+ api_key = _strip_value(os.getenv("EMBEDDING_BINDING_API_KEY"))
+ base_url = _strip_value(os.getenv("EMBEDDING_BINDING_HOST"))
+
+ # Strict mode: All model configuration must come from .env
+ if not model:
+ raise ValueError("Error: EMBEDDING_MODEL not set, please configure it in .env file")
+
+ # Check if API key is required
+ requires_key = os.getenv("EMBEDDING_API_KEY_REQUIRED", "true").lower() == "true"
+
+ if requires_key and not api_key:
+ raise ValueError(
+ "Error: EMBEDDING_BINDING_API_KEY not set, please configure it in .env file"
+ )
+ if not base_url:
+ raise ValueError("Error: EMBEDDING_BINDING_HOST not set, please configure it in .env file")
+
+ # Get optional configuration
+ dim = _to_int(_strip_value(os.getenv("EMBEDDING_DIM")), 3072)
+ max_tokens = _to_int(_strip_value(os.getenv("EMBEDDING_MAX_TOKENS")), 8192)
+
+ return EmbeddingConfig(
+ binding=binding,
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ dim=dim,
+ max_tokens=max_tokens,
+ )
+
diff --git a/src/services/llm/__init__.py b/src/services/llm/__init__.py
new file mode 100644
index 000000000..8a5c7a147
--- /dev/null
+++ b/src/services/llm/__init__.py
@@ -0,0 +1,50 @@
+"""
+LLM Service
+===========
+
+Unified LLM client for all DeepTutor modules.
+
+Usage:
+ from src.services.llm import get_llm_client, LLMClient, LLMConfig
+
+ # Get singleton client
+ client = get_llm_client()
+ response = await client.complete("Hello, world!")
+
+ # Or create custom client
+ config = LLMConfig(model="gpt-4o", api_key="...", base_url="...")
+ client = LLMClient(config)
+
+ # Provider management
+ from src.services.llm import provider_manager, LLMProvider
+ providers = provider_manager.list_providers()
+"""
+
+from .client import LLMClient, get_llm_client, reset_llm_client
+from .config import (
+ LLMConfig,
+ get_llm_config,
+ uses_max_completion_tokens,
+ get_token_limit_kwargs,
+)
+from .provider import (
+ LLMProvider,
+ LLMProviderManager,
+ provider_manager,
+)
+
+__all__ = [
+ # Client
+ "LLMClient",
+ "get_llm_client",
+ "reset_llm_client",
+ # Config
+ "LLMConfig",
+ "get_llm_config",
+ "uses_max_completion_tokens",
+ "get_token_limit_kwargs",
+ # Provider
+ "LLMProvider",
+ "LLMProviderManager",
+ "provider_manager",
+]
diff --git a/src/services/llm/client.py b/src/services/llm/client.py
new file mode 100644
index 000000000..34b0e72a4
--- /dev/null
+++ b/src/services/llm/client.py
@@ -0,0 +1,215 @@
+"""
+LLM Client
+==========
+
+Unified LLM client for all DeepTutor services.
+"""
+
+from typing import Any, Dict, List, Optional
+
+from src.logging import get_logger
+from .config import LLMConfig, get_llm_config
+
+
+class LLMClient:
+ """
+ Unified LLM client for all services.
+
+ Wraps the underlying LLM API (OpenAI-compatible) with a consistent interface.
+ """
+
+ def __init__(self, config: Optional[LLMConfig] = None):
+ """
+ Initialize LLM client.
+
+ Args:
+ config: LLM configuration. If None, loads from environment.
+ """
+ self.config = config or get_llm_config()
+ self.logger = get_logger("LLMClient")
+
+ async def complete(
+ self,
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ history: Optional[List[Dict[str, str]]] = None,
+ **kwargs: Any,
+ ) -> str:
+ """
+ Call LLM completion.
+
+ Args:
+ prompt: User prompt
+ system_prompt: Optional system prompt
+ history: Optional conversation history
+ **kwargs: Additional arguments passed to the API
+
+ Returns:
+ LLM response text
+ """
+ from lightrag.llm.openai import openai_complete_if_cache
+
+ return await openai_complete_if_cache(
+ self.config.model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history or [],
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ **kwargs,
+ )
+
+ def complete_sync(
+ self,
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ history: Optional[List[Dict[str, str]]] = None,
+ **kwargs: Any,
+ ) -> str:
+ """
+ Synchronous wrapper for complete().
+
+ Use this when you need to call from non-async context.
+ """
+ import asyncio
+
+ try:
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ # If already in an async context, we need to use a different approach
+ import concurrent.futures
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(
+ asyncio.run,
+ self.complete(prompt, system_prompt, history, **kwargs)
+ )
+ return future.result()
+ else:
+ return loop.run_until_complete(
+ self.complete(prompt, system_prompt, history, **kwargs)
+ )
+ except RuntimeError:
+ return asyncio.run(
+ self.complete(prompt, system_prompt, history, **kwargs)
+ )
+
+ def get_model_func(self):
+ """
+ Get a function compatible with LightRAG's llm_model_func parameter.
+
+ Returns:
+ Callable that can be used as llm_model_func
+ """
+ from lightrag.llm.openai import openai_complete_if_cache
+
+ def llm_model_func(
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ history_messages: Optional[List[Dict]] = None,
+ **kwargs: Any,
+ ):
+ return openai_complete_if_cache(
+ self.config.model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages or [],
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ **kwargs,
+ )
+
+ return llm_model_func
+
+ def get_vision_model_func(self):
+ """
+ Get a function compatible with RAG-Anything's vision_model_func parameter.
+
+ Returns:
+ Callable that can be used as vision_model_func
+ """
+ from lightrag.llm.openai import openai_complete_if_cache
+
+ def vision_model_func(
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ history_messages: Optional[List[Dict]] = None,
+ image_data: Optional[str] = None,
+ messages: Optional[List[Dict]] = None,
+ **kwargs: Any,
+ ):
+ # Handle multimodal messages
+ if messages:
+ clean_kwargs = {
+ k: v for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ self.config.model,
+ prompt="",
+ messages=messages,
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ **clean_kwargs,
+ )
+
+ # Handle image data
+ if image_data:
+ # Build image message
+ image_message = {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": prompt},
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
+ },
+ ],
+ }
+ return openai_complete_if_cache(
+ self.config.model,
+ prompt="",
+ messages=[image_message],
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ **kwargs,
+ )
+
+ # Fallback to regular completion
+ return openai_complete_if_cache(
+ self.config.model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages or [],
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ **kwargs,
+ )
+
+ return vision_model_func
+
+
+# Singleton instance
+_client: Optional[LLMClient] = None
+
+
+def get_llm_client(config: Optional[LLMConfig] = None) -> LLMClient:
+ """
+ Get or create the singleton LLM client.
+
+ Args:
+ config: Optional configuration. Only used on first call.
+
+ Returns:
+ LLMClient instance
+ """
+ global _client
+ if _client is None:
+ _client = LLMClient(config)
+ return _client
+
+
+def reset_llm_client():
+ """Reset the singleton LLM client."""
+ global _client
+ _client = None
+
diff --git a/src/services/llm/config.py b/src/services/llm/config.py
new file mode 100644
index 000000000..91497c754
--- /dev/null
+++ b/src/services/llm/config.py
@@ -0,0 +1,167 @@
+# -*- coding: utf-8 -*-
+"""
+LLM Configuration
+=================
+
+Configuration management for LLM services.
+"""
+
+from dataclasses import dataclass
+import os
+from pathlib import Path
+import re
+from typing import Optional
+
+from dotenv import load_dotenv
+
+# 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)
+
+
+@dataclass
+class LLMConfig:
+ """LLM configuration dataclass."""
+
+ model: str
+ api_key: str
+ base_url: Optional[str] = None
+ binding: str = "openai"
+ max_tokens: int = 4096
+ temperature: float = 0.7
+
+
+def _strip_value(value: Optional[str]) -> Optional[str]:
+ """Remove leading/trailing whitespace and quotes from string."""
+ if value is None:
+ return None
+ return value.strip().strip("\"'")
+
+
+def get_llm_config() -> LLMConfig:
+ """
+ Load LLM configuration from environment variables or provider manager.
+
+ Priority:
+ 1. Active provider from llm_providers.json
+ 2. Environment variables (.env)
+
+ Returns:
+ LLMConfig: Configuration dataclass
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ # 1. Try to get active provider from provider manager
+ try:
+ from .provider import provider_manager
+
+ active_provider = provider_manager.get_active_provider()
+
+ if active_provider:
+ return LLMConfig(
+ binding=active_provider.binding,
+ model=active_provider.model,
+ api_key=active_provider.api_key,
+ base_url=active_provider.base_url,
+ )
+ except Exception as e:
+ print(f"⚠️ Failed to load active provider: {e}")
+
+ # 2. Fallback to environment variables
+ binding = _strip_value(os.getenv("LLM_BINDING", "openai"))
+ model = _strip_value(os.getenv("LLM_MODEL"))
+ api_key = _strip_value(os.getenv("LLM_BINDING_API_KEY"))
+ base_url = _strip_value(os.getenv("LLM_BINDING_HOST"))
+
+ # Validate required configuration
+ if not model:
+ raise ValueError(
+ "Error: LLM_MODEL not set, please configure it in .env file or activate a provider"
+ )
+
+ # Check if API key is required
+ requires_key = os.getenv("LLM_API_KEY_REQUIRED", "true").lower() == "true"
+
+ if requires_key and not api_key:
+ raise ValueError(
+ "Error: LLM_BINDING_API_KEY not set, please configure it in .env file or activate a provider"
+ )
+ if not base_url:
+ raise ValueError(
+ "Error: LLM_BINDING_HOST not set, please configure it in .env file or activate a provider"
+ )
+
+ return LLMConfig(
+ binding=binding,
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ )
+
+
+def uses_max_completion_tokens(model: str) -> bool:
+ """
+ Check if the model uses max_completion_tokens instead of max_tokens.
+
+ Newer OpenAI models (o1, o3, gpt-4o, gpt-5.x, etc.) require max_completion_tokens
+ while older models use max_tokens.
+
+ Args:
+ model: The model name
+
+ Returns:
+ True if the model requires max_completion_tokens, False otherwise
+ """
+ model_lower = model.lower()
+
+ # Models that require max_completion_tokens:
+ # - o1, o3 series (reasoning models)
+ # - gpt-4o series
+ # - gpt-5.x and later
+ patterns = [
+ r"^o[13]", # o1, o3 models
+ r"^gpt-4o", # gpt-4o models
+ r"^gpt-[5-9]", # gpt-5.x and later
+ r"^gpt-\d{2,}", # gpt-10+ (future proofing)
+ ]
+
+ for pattern in patterns:
+ if re.match(pattern, model_lower):
+ return True
+
+ return False
+
+
+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 name
+ max_tokens: The desired token limit
+
+ Returns:
+ 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}
+ return {"max_tokens": max_tokens}
+
+
+__all__ = [
+ "LLMConfig",
+ "get_llm_config",
+ "uses_max_completion_tokens",
+ "get_token_limit_kwargs",
+]
diff --git a/src/core/llm_provider.py b/src/services/llm/provider.py
similarity index 96%
rename from src/core/llm_provider.py
rename to src/services/llm/provider.py
index 00348599f..5b514cec5 100644
--- a/src/core/llm_provider.py
+++ b/src/services/llm/provider.py
@@ -1,3 +1,10 @@
+"""
+LLM Provider Management
+=======================
+
+Manages LLM provider configurations, persisting them to a JSON file.
+"""
+
import json
from pathlib import Path
from typing import Any, Dict, List, Optional
@@ -158,3 +165,11 @@ class LLMProviderManager:
# Global instance
provider_manager = LLMProviderManager()
+
+
+__all__ = [
+ "LLMProvider",
+ "LLMProviderManager",
+ "provider_manager",
+]
+
diff --git a/src/services/prompt/__init__.py b/src/services/prompt/__init__.py
new file mode 100644
index 000000000..cc411c935
--- /dev/null
+++ b/src/services/prompt/__init__.py
@@ -0,0 +1,26 @@
+"""
+Prompt Service
+==============
+
+Unified prompt management for all DeepTutor modules.
+
+Usage:
+ from src.services.prompt import get_prompt_manager, PromptManager
+
+ # Get singleton manager
+ pm = get_prompt_manager()
+
+ # Load prompts for an agent
+ prompts = pm.load_prompts("guide", "tutor_agent", language="en")
+
+ # Get specific prompt
+ system_prompt = pm.get_prompt(prompts, "system", "base")
+"""
+
+from .manager import PromptManager, get_prompt_manager
+
+__all__ = [
+ "PromptManager",
+ "get_prompt_manager",
+]
+
diff --git a/src/core/prompt_manager.py b/src/services/prompt/manager.py
similarity index 99%
rename from src/core/prompt_manager.py
rename to src/services/prompt/manager.py
index e50b526ac..22f5e904e 100644
--- a/src/core/prompt_manager.py
+++ b/src/services/prompt/manager.py
@@ -9,7 +9,7 @@ from typing import Any
import yaml
-from .core import PROJECT_ROOT, parse_language
+from src.services.config import PROJECT_ROOT, parse_language
class PromptManager:
@@ -204,3 +204,4 @@ def get_prompt_manager() -> PromptManager:
__all__ = ["PromptManager", "get_prompt_manager"]
+
diff --git a/src/services/rag/__init__.py b/src/services/rag/__init__.py
new file mode 100644
index 000000000..7a38fc61c
--- /dev/null
+++ b/src/services/rag/__init__.py
@@ -0,0 +1,52 @@
+"""
+RAG Service
+===========
+
+Unified RAG pipeline service for DeepTutor.
+
+Provides:
+- Composable RAG pipelines
+- Pre-configured pipelines (RAGAnything, LightRAG, LlamaIndex, Academic)
+- Modular components (parsers, chunkers, embedders, indexers, retrievers)
+- Factory for pipeline creation
+
+Usage:
+ from src.services.rag import get_pipeline, RAGPipeline, RAGAnythingPipeline
+
+ # Get pre-configured pipeline
+ pipeline = get_pipeline("raganything")
+ await pipeline.initialize("kb_name", ["doc1.pdf", "doc2.pdf"])
+ result = await pipeline.search("query", "kb_name")
+
+ # Or build custom pipeline
+ from src.services.rag.components import PDFParser, SemanticChunker, GraphIndexer
+
+ custom = (
+ RAGPipeline("custom")
+ .parser(PDFParser())
+ .chunker(SemanticChunker())
+ .indexer(GraphIndexer())
+ )
+"""
+
+from .types import Document, Chunk
+from .pipeline import RAGPipeline
+from .factory import get_pipeline, list_pipelines, register_pipeline
+
+# Import pipeline classes for convenience
+from .pipelines.raganything import RAGAnythingPipeline
+
+__all__ = [
+ # Types
+ "Document",
+ "Chunk",
+ # Pipeline
+ "RAGPipeline",
+ # Factory
+ "get_pipeline",
+ "list_pipelines",
+ "register_pipeline",
+ # Pipeline implementations
+ "RAGAnythingPipeline",
+]
+
diff --git a/src/services/rag/components/__init__.py b/src/services/rag/components/__init__.py
new file mode 100644
index 000000000..ddd4b6bf6
--- /dev/null
+++ b/src/services/rag/components/__init__.py
@@ -0,0 +1,30 @@
+"""
+RAG Components
+==============
+
+Modular components for building RAG pipelines.
+
+Components follow a simple protocol:
+- Each component has a `name` attribute
+- Each component has an async `process()` method
+"""
+
+from .base import Component, BaseComponent
+
+# Import component modules for convenience
+from . import parsers
+from . import chunkers
+from . import embedders
+from . import indexers
+from . import retrievers
+
+__all__ = [
+ "Component",
+ "BaseComponent",
+ "parsers",
+ "chunkers",
+ "embedders",
+ "indexers",
+ "retrievers",
+]
+
diff --git a/src/services/rag/components/base.py b/src/services/rag/components/base.py
new file mode 100644
index 000000000..54b56e5d6
--- /dev/null
+++ b/src/services/rag/components/base.py
@@ -0,0 +1,59 @@
+"""
+Base Component
+==============
+
+Base classes and protocols for RAG components.
+"""
+
+from typing import Any, Protocol, runtime_checkable
+
+
+@runtime_checkable
+class Component(Protocol):
+ """
+ Base protocol for all RAG components.
+
+ All components must implement:
+ - name: str - Component identifier
+ - process(data, **kwargs) -> Any - Process input data
+ """
+
+ name: str
+
+ async def process(self, data: Any, **kwargs) -> Any:
+ """
+ Process input data.
+
+ Args:
+ data: Input data to process
+ **kwargs: Additional arguments
+
+ Returns:
+ Processed output
+ """
+ ...
+
+
+class BaseComponent:
+ """
+ Base class with common functionality for components.
+
+ Provides:
+ - Logger initialization
+ - Default name from class name
+ """
+
+ name: str = "base"
+
+ def __init__(self):
+ from src.logging import get_logger
+ self.logger = get_logger(self.__class__.__name__)
+
+ async def process(self, data: Any, **kwargs) -> Any:
+ """
+ Process input data.
+
+ Override this method in subclasses.
+ """
+ raise NotImplementedError("Subclasses must implement process()")
+
diff --git a/src/services/rag/components/chunkers/__init__.py b/src/services/rag/components/chunkers/__init__.py
new file mode 100644
index 000000000..8d5e12a6e
--- /dev/null
+++ b/src/services/rag/components/chunkers/__init__.py
@@ -0,0 +1,19 @@
+"""
+Document Chunkers
+=================
+
+Chunkers for splitting documents into smaller pieces.
+"""
+
+from .base import BaseChunker
+from .semantic import SemanticChunker
+from .fixed import FixedSizeChunker
+from .numbered_item import NumberedItemExtractor
+
+__all__ = [
+ "BaseChunker",
+ "SemanticChunker",
+ "FixedSizeChunker",
+ "NumberedItemExtractor",
+]
+
diff --git a/src/services/rag/components/chunkers/base.py b/src/services/rag/components/chunkers/base.py
new file mode 100644
index 000000000..cc0550fef
--- /dev/null
+++ b/src/services/rag/components/chunkers/base.py
@@ -0,0 +1,35 @@
+"""
+Base Chunker
+============
+
+Base class for document chunkers.
+"""
+
+from typing import List
+
+from ..base import BaseComponent
+from ...types import Document, Chunk
+
+
+class BaseChunker(BaseComponent):
+ """
+ Base class for document chunkers.
+
+ Chunkers split documents into smaller chunks for processing.
+ """
+
+ name = "base_chunker"
+
+ async def process(self, doc: Document, **kwargs) -> List[Chunk]:
+ """
+ Chunk a document.
+
+ Args:
+ doc: Document to chunk
+ **kwargs: Additional arguments
+
+ Returns:
+ List of Chunks
+ """
+ raise NotImplementedError("Subclasses must implement process()")
+
diff --git a/src/services/rag/components/chunkers/fixed.py b/src/services/rag/components/chunkers/fixed.py
new file mode 100644
index 000000000..51df56b44
--- /dev/null
+++ b/src/services/rag/components/chunkers/fixed.py
@@ -0,0 +1,70 @@
+"""
+Fixed Size Chunker
+==================
+
+Chunker that splits documents into fixed-size pieces.
+"""
+
+from typing import List
+
+from ..base import BaseComponent
+from ...types import Document, Chunk
+
+
+class FixedSizeChunker(BaseComponent):
+ """
+ Fixed-size chunker.
+
+ Splits documents into chunks of a fixed size with optional overlap.
+ """
+
+ name = "fixed_size_chunker"
+
+ def __init__(self, chunk_size: int = 1000, chunk_overlap: int = 100):
+ """
+ Initialize fixed-size chunker.
+
+ Args:
+ chunk_size: Size of each chunk in characters
+ chunk_overlap: Overlap between chunks
+ """
+ super().__init__()
+ self.chunk_size = chunk_size
+ self.chunk_overlap = chunk_overlap
+
+ async def process(self, doc: Document, **kwargs) -> List[Chunk]:
+ """
+ Chunk a document into fixed-size pieces.
+
+ Args:
+ doc: Document to chunk
+ **kwargs: Additional arguments
+
+ Returns:
+ List of fixed-size Chunks
+ """
+ self.logger.info(f"Chunking document: {doc.file_path or 'inline'}")
+
+ text = doc.content
+ if not text:
+ return []
+
+ chunks = []
+ step = self.chunk_size - self.chunk_overlap
+
+ for i in range(0, len(text), step):
+ chunk_text = text[i:i + self.chunk_size].strip()
+ if chunk_text:
+ chunks.append(Chunk(
+ content=chunk_text,
+ chunk_type="text",
+ metadata={
+ "start_pos": i,
+ "end_pos": min(i + self.chunk_size, len(text)),
+ "source": doc.file_path,
+ },
+ ))
+
+ self.logger.info(f"Created {len(chunks)} chunks")
+ return chunks
+
diff --git a/src/services/rag/components/chunkers/numbered_item.py b/src/services/rag/components/chunkers/numbered_item.py
new file mode 100644
index 000000000..0f369d4d6
--- /dev/null
+++ b/src/services/rag/components/chunkers/numbered_item.py
@@ -0,0 +1,93 @@
+"""
+Numbered Item Extractor
+=======================
+
+Extracts numbered items (definitions, theorems, equations) from documents.
+"""
+
+from typing import List, Optional
+
+from ..base import BaseComponent
+from ...types import Document, Chunk
+
+
+class NumberedItemExtractor(BaseComponent):
+ """
+ Extract numbered items (definitions, theorems, equations) from documents.
+
+ Uses LLM to identify and extract structured academic content like
+ definitions, theorems, lemmas, propositions, equations, etc.
+ """
+
+ name = "numbered_item_extractor"
+
+ def __init__(self, batch_size: int = 20, max_concurrent: int = 5):
+ """
+ Initialize numbered item extractor.
+
+ Args:
+ batch_size: Number of content items to process per batch
+ max_concurrent: Maximum concurrent LLM calls
+ """
+ super().__init__()
+ self.batch_size = batch_size
+ self.max_concurrent = max_concurrent
+
+ async def process(self, doc: Document, **kwargs) -> List[Chunk]:
+ """
+ Extract numbered items from a document.
+
+ Args:
+ doc: Document to extract from (must have content_items)
+ **kwargs: Additional arguments
+
+ Returns:
+ List of Chunks representing numbered items
+ """
+ if not doc.content_items:
+ self.logger.warning("No content_items in document, skipping extraction")
+ return []
+
+ self.logger.info(f"Extracting numbered items from {len(doc.content_items)} content items")
+
+ try:
+ from src.services.llm import get_llm_client
+ from src.knowledge.extract_numbered_items import (
+ extract_numbered_items_with_llm_async,
+ )
+
+ llm_client = get_llm_client()
+
+ # Use existing extraction logic
+ items = await extract_numbered_items_with_llm_async(
+ doc.content_items,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ batch_size=self.batch_size,
+ max_concurrent=self.max_concurrent,
+ )
+
+ # Convert to Chunks
+ chunks = []
+ for identifier, item_data in items.items():
+ chunks.append(Chunk(
+ content=item_data["text"],
+ chunk_type=item_data["type"], # Definition, Theorem, Equation...
+ metadata={
+ "identifier": identifier,
+ "page": item_data.get("page", 0),
+ "img_paths": item_data.get("img_paths", []),
+ "source": doc.file_path,
+ },
+ ))
+
+ self.logger.info(f"Extracted {len(chunks)} numbered items")
+ return chunks
+
+ except ImportError as e:
+ self.logger.warning(f"Could not import extraction module: {e}")
+ return []
+ except Exception as e:
+ self.logger.error(f"Failed to extract numbered items: {e}")
+ return []
+
diff --git a/src/services/rag/components/chunkers/semantic.py b/src/services/rag/components/chunkers/semantic.py
new file mode 100644
index 000000000..5e8553964
--- /dev/null
+++ b/src/services/rag/components/chunkers/semantic.py
@@ -0,0 +1,96 @@
+"""
+Semantic Chunker
+================
+
+Chunker that splits documents based on semantic boundaries.
+"""
+
+from typing import List
+
+from ..base import BaseComponent
+from ...types import Document, Chunk
+
+
+class SemanticChunker(BaseComponent):
+ """
+ Semantic chunker.
+
+ Splits documents based on semantic boundaries like paragraphs,
+ sections, or natural breakpoints.
+ """
+
+ name = "semantic_chunker"
+
+ def __init__(
+ self,
+ chunk_size: int = 1000,
+ chunk_overlap: int = 200,
+ separators: List[str] = None,
+ ):
+ """
+ Initialize semantic chunker.
+
+ Args:
+ chunk_size: Target chunk size in characters
+ chunk_overlap: Overlap between chunks
+ separators: List of separators to split on
+ """
+ super().__init__()
+ self.chunk_size = chunk_size
+ self.chunk_overlap = chunk_overlap
+ self.separators = separators or ["\n\n", "\n", ". ", " "]
+
+ async def process(self, doc: Document, **kwargs) -> List[Chunk]:
+ """
+ Chunk a document semantically.
+
+ Args:
+ doc: Document to chunk
+ **kwargs: Additional arguments
+
+ Returns:
+ List of semantic Chunks
+ """
+ self.logger.info(f"Chunking document: {doc.file_path or 'inline'}")
+
+ text = doc.content
+ if not text:
+ return []
+
+ chunks = []
+ current_pos = 0
+
+ while current_pos < len(text):
+ # Find chunk end
+ end_pos = min(current_pos + self.chunk_size, len(text))
+
+ # Try to find a natural break point
+ if end_pos < len(text):
+ for sep in self.separators:
+ # Look for separator in the last portion of the chunk
+ search_start = max(current_pos + self.chunk_size - 200, current_pos)
+ sep_pos = text.rfind(sep, search_start, end_pos)
+ if sep_pos > current_pos:
+ end_pos = sep_pos + len(sep)
+ break
+
+ chunk_text = text[current_pos:end_pos].strip()
+ if chunk_text:
+ chunks.append(Chunk(
+ content=chunk_text,
+ chunk_type="text",
+ metadata={
+ "start_pos": current_pos,
+ "end_pos": end_pos,
+ "source": doc.file_path,
+ },
+ ))
+
+ # Move to next position with overlap
+ current_pos = end_pos - self.chunk_overlap
+ if current_pos >= len(text) - self.chunk_overlap:
+ break
+
+ self.logger.info(f"Created {len(chunks)} chunks")
+ return chunks
+
diff --git a/src/services/rag/components/embedders/__init__.py b/src/services/rag/components/embedders/__init__.py
new file mode 100644
index 000000000..1335f62db
--- /dev/null
+++ b/src/services/rag/components/embedders/__init__.py
@@ -0,0 +1,15 @@
+"""
+Document Embedders
+==================
+
+Embedders for generating vector representations of text.
+"""
+
+from .base import BaseEmbedder
+from .openai import OpenAIEmbedder
+
+__all__ = [
+ "BaseEmbedder",
+ "OpenAIEmbedder",
+]
+
diff --git a/src/services/rag/components/embedders/base.py b/src/services/rag/components/embedders/base.py
new file mode 100644
index 000000000..97438af50
--- /dev/null
+++ b/src/services/rag/components/embedders/base.py
@@ -0,0 +1,33 @@
+"""
+Base Embedder
+=============
+
+Base class for document embedders.
+"""
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class BaseEmbedder(BaseComponent):
+ """
+ Base class for document embedders.
+
+ Embedders generate vector representations for document chunks.
+ """
+
+ name = "base_embedder"
+
+ async def process(self, doc: Document, **kwargs) -> Document:
+ """
+ Embed a document's chunks.
+
+ Args:
+ doc: Document with chunks to embed
+ **kwargs: Additional arguments
+
+ Returns:
+ Document with embedded chunks
+ """
+ raise NotImplementedError("Subclasses must implement process()")
+
diff --git a/src/services/rag/components/embedders/openai.py b/src/services/rag/components/embedders/openai.py
new file mode 100644
index 000000000..3b708184a
--- /dev/null
+++ b/src/services/rag/components/embedders/openai.py
@@ -0,0 +1,66 @@
+"""
+OpenAI Embedder
+===============
+
+Embedder using OpenAI-compatible embedding API.
+"""
+
+from typing import List
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class OpenAIEmbedder(BaseComponent):
+ """
+ OpenAI-compatible embedder.
+
+ Uses the embedding service to generate vectors for document chunks.
+ """
+
+ name = "openai_embedder"
+
+ def __init__(self, batch_size: int = 100):
+ """
+ Initialize OpenAI embedder.
+
+ Args:
+ batch_size: Number of texts to embed per API call
+ """
+ super().__init__()
+ self.batch_size = batch_size
+
+ async def process(self, doc: Document, **kwargs) -> Document:
+ """
+ Embed a document's chunks.
+
+ Args:
+ doc: Document with chunks to embed
+ **kwargs: Additional arguments
+
+ Returns:
+ Document with embedded chunks
+ """
+ if not doc.chunks:
+ self.logger.warning("No chunks to embed")
+ return doc
+
+ self.logger.info(f"Embedding {len(doc.chunks)} chunks")
+
+ from src.services.embedding import get_embedding_client
+
+ client = get_embedding_client()
+
+ # Batch embed
+ for i in range(0, len(doc.chunks), self.batch_size):
+ batch = doc.chunks[i:i + self.batch_size]
+ texts = [chunk.content for chunk in batch]
+
+ embeddings = await client.embed(texts)
+
+ for chunk, embedding in zip(batch, embeddings):
+ chunk.embedding = embedding
+
+ self.logger.info("Embedding complete")
+ return doc
+
diff --git a/src/services/rag/components/indexers/__init__.py b/src/services/rag/components/indexers/__init__.py
new file mode 100644
index 000000000..4d30d7d85
--- /dev/null
+++ b/src/services/rag/components/indexers/__init__.py
@@ -0,0 +1,17 @@
+"""
+Document Indexers
+=================
+
+Indexers for building searchable indexes from documents.
+"""
+
+from .base import BaseIndexer
+from .vector import VectorIndexer
+from .graph import GraphIndexer
+
+__all__ = [
+ "BaseIndexer",
+ "VectorIndexer",
+ "GraphIndexer",
+]
+
diff --git a/src/services/rag/components/indexers/base.py b/src/services/rag/components/indexers/base.py
new file mode 100644
index 000000000..b086bce6e
--- /dev/null
+++ b/src/services/rag/components/indexers/base.py
@@ -0,0 +1,36 @@
+"""
+Base Indexer
+============
+
+Base class for document indexers.
+"""
+
+from typing import List
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class BaseIndexer(BaseComponent):
+ """
+ Base class for document indexers.
+
+ Indexers build searchable indexes from documents.
+ """
+
+ name = "base_indexer"
+
+ async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:
+ """
+ Index documents into a knowledge base.
+
+ Args:
+ kb_name: Knowledge base name
+ documents: List of documents to index
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ raise NotImplementedError("Subclasses must implement process()")
+
diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.py
new file mode 100644
index 000000000..5634d1013
--- /dev/null
+++ b/src/services/rag/components/indexers/graph.py
@@ -0,0 +1,120 @@
+"""
+Graph Indexer
+=============
+
+Knowledge graph indexer using LightRAG.
+"""
+
+from pathlib import Path
+import sys
+from typing import Dict, List, Optional
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class GraphIndexer(BaseComponent):
+ """
+ Knowledge graph indexer using LightRAG.
+
+ Builds a knowledge graph from documents for graph-based retrieval.
+ """
+
+ name = "graph_indexer"
+ _instances: Dict[str, any] = {} # Cache RAG instances
+
+ def __init__(self, kb_base_dir: Optional[str] = None):
+ """
+ Initialize graph indexer.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ """
+ super().__init__()
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent
+ / "data" / "knowledge_bases"
+ )
+
+ def _get_rag_instance(self, kb_name: str):
+ """Get or create a RAGAnything instance."""
+ working_dir = str(Path(self.kb_base_dir) / kb_name / "rag_storage")
+
+ if working_dir in self._instances:
+ return self._instances[working_dir]
+
+ # Add RAG-Anything path
+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent.parent
+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+ if raganything_path.exists() and str(raganything_path) not in sys.path:
+ sys.path.insert(0, str(raganything_path))
+
+ try:
+ from lightrag.llm.openai import openai_complete_if_cache
+ from raganything import RAGAnything, RAGAnythingConfig
+ from src.services.llm import get_llm_client
+ from src.services.embedding import get_embedding_client
+
+ llm_client = get_llm_client()
+ embed_client = get_embedding_client()
+
+ # LLM function using services
+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ return openai_complete_if_cache(
+ llm_client.config.model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ **kwargs,
+ )
+
+ config = RAGAnythingConfig(
+ working_dir=working_dir,
+ enable_image_processing=True,
+ enable_table_processing=True,
+ enable_equation_processing=True,
+ )
+
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ embedding_func=embed_client.get_embedding_func(),
+ )
+
+ self._instances[working_dir] = rag
+ return rag
+
+ except ImportError as e:
+ self.logger.error(f"Failed to import RAG-Anything: {e}")
+ raise
+
+ async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:
+ """
+ Build knowledge graph from documents.
+
+ Args:
+ kb_name: Knowledge base name
+ documents: List of documents to index
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ self.logger.info(f"Building knowledge graph for {kb_name}...")
+
+ from src.logging.adapters import LightRAGLogContext
+
+ # Use log forwarding context
+ with LightRAGLogContext(scene="indexer"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ for doc in documents:
+ if doc.content:
+ await rag.ainsert(doc.content)
+
+ self.logger.info("Knowledge graph built successfully")
+ return True
+
diff --git a/src/services/rag/components/indexers/vector.py b/src/services/rag/components/indexers/vector.py
new file mode 100644
index 000000000..2007418db
--- /dev/null
+++ b/src/services/rag/components/indexers/vector.py
@@ -0,0 +1,86 @@
+"""
+Vector Indexer
+==============
+
+Vector-based indexer using dense embeddings.
+"""
+
+from pathlib import Path
+from typing import List, Optional
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class VectorIndexer(BaseComponent):
+ """
+ Vector indexer using dense embeddings.
+
+ Can use LlamaIndex or other vector stores for indexing.
+ """
+
+ name = "vector_indexer"
+
+ def __init__(self, kb_base_dir: Optional[str] = None):
+ """
+ Initialize vector indexer.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ """
+ super().__init__()
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent
+ / "data" / "knowledge_bases"
+ )
+
+ async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:
+ """
+ Index documents using vector embeddings.
+
+ Args:
+ kb_name: Knowledge base name
+ documents: List of documents to index
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ self.logger.info(f"Indexing {len(documents)} documents into vector store for {kb_name}")
+
+ # Collect all chunks with embeddings
+ all_chunks = []
+ for doc in documents:
+ for chunk in doc.chunks:
+ if chunk.embedding:
+ all_chunks.append(chunk)
+
+ if not all_chunks:
+ self.logger.warning("No chunks with embeddings to index")
+ return False
+
+ self.logger.info(f"Indexing {len(all_chunks)} chunks")
+
+ # Create vector store directory
+ kb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"
+ kb_dir.mkdir(parents=True, exist_ok=True)
+
+ # Simple JSON-based storage (placeholder for actual vector store)
+ import json
+
+ index_data = []
+ for i, chunk in enumerate(all_chunks):
+ index_data.append({
+ "id": i,
+ "content": chunk.content,
+ "type": chunk.chunk_type,
+ "metadata": chunk.metadata,
+ "embedding": chunk.embedding,
+ })
+
+ with open(kb_dir / "index.json", "w", encoding="utf-8") as f:
+ json.dump(index_data, f, ensure_ascii=False, indent=2)
+
+ self.logger.info(f"Vector index saved to {kb_dir}")
+ return True
+
diff --git a/src/services/rag/components/parsers/__init__.py b/src/services/rag/components/parsers/__init__.py
new file mode 100644
index 000000000..b9d3935f2
--- /dev/null
+++ b/src/services/rag/components/parsers/__init__.py
@@ -0,0 +1,17 @@
+"""
+Document Parsers
+================
+
+Parsers for extracting content from various document formats.
+"""
+
+from .base import BaseParser
+from .pdf import PDFParser
+from .markdown import MarkdownParser
+
+__all__ = [
+ "BaseParser",
+ "PDFParser",
+ "MarkdownParser",
+]
+
diff --git a/src/services/rag/components/parsers/base.py b/src/services/rag/components/parsers/base.py
new file mode 100644
index 000000000..30d11581c
--- /dev/null
+++ b/src/services/rag/components/parsers/base.py
@@ -0,0 +1,36 @@
+"""
+Base Parser
+===========
+
+Base class for document parsers.
+"""
+
+from typing import Union
+from pathlib import Path
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class BaseParser(BaseComponent):
+ """
+ Base class for document parsers.
+
+ Parsers convert raw files into Document objects.
+ """
+
+ name = "base_parser"
+
+ async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
+ """
+ Parse a file into a Document.
+
+ Args:
+ file_path: Path to the file to parse
+ **kwargs: Additional arguments
+
+ Returns:
+ Parsed Document
+ """
+ raise NotImplementedError("Subclasses must implement process()")
+
diff --git a/src/services/rag/components/parsers/markdown.py b/src/services/rag/components/parsers/markdown.py
new file mode 100644
index 000000000..3875b721c
--- /dev/null
+++ b/src/services/rag/components/parsers/markdown.py
@@ -0,0 +1,53 @@
+"""
+Markdown Parser
+===============
+
+Parser for Markdown documents.
+"""
+
+from pathlib import Path
+from typing import Union
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class MarkdownParser(BaseComponent):
+ """
+ Markdown parser.
+
+ Parses Markdown files into Document objects.
+ """
+
+ name = "markdown_parser"
+
+ async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
+ """
+ Parse a Markdown file into a Document.
+
+ Args:
+ file_path: Path to the Markdown file
+ **kwargs: Additional arguments
+
+ Returns:
+ Parsed Document
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise FileNotFoundError(f"Markdown file not found: {file_path}")
+
+ self.logger.info(f"Parsing Markdown: {file_path.name}")
+
+ with open(file_path, "r", encoding="utf-8") as f:
+ content = f.read()
+
+ return Document(
+ content=content,
+ file_path=str(file_path),
+ metadata={
+ "filename": file_path.name,
+ "parser": self.name,
+ },
+ )
+
diff --git a/src/services/rag/components/parsers/pdf.py b/src/services/rag/components/parsers/pdf.py
new file mode 100644
index 000000000..aa5d946ba
--- /dev/null
+++ b/src/services/rag/components/parsers/pdf.py
@@ -0,0 +1,116 @@
+"""
+PDF Parser
+==========
+
+Parser for PDF documents using MinerU/RAG-Anything.
+"""
+
+import json
+from pathlib import Path
+from typing import Optional, Union
+
+from ..base import BaseComponent
+from ...types import Document
+
+
+class PDFParser(BaseComponent):
+ """
+ PDF parser using MinerU for extraction.
+
+ Can use RAG-Anything's MinerU integration or standalone MinerU.
+ """
+
+ name = "pdf_parser"
+
+ def __init__(self, use_mineru: bool = True, output_dir: Optional[str] = None):
+ """
+ Initialize PDF parser.
+
+ Args:
+ use_mineru: Whether to use MinerU for parsing
+ output_dir: Directory to store parsed output
+ """
+ super().__init__()
+ self.use_mineru = use_mineru
+ self.output_dir = output_dir
+
+ async def process(self, file_path: Union[str, Path], **kwargs) -> Document:
+ """
+ Parse a PDF file into a Document.
+
+ Args:
+ file_path: Path to the PDF file
+ **kwargs: Additional arguments
+
+ Returns:
+ Parsed Document with content and content_items
+ """
+ file_path = Path(file_path)
+
+ if not file_path.exists():
+ raise FileNotFoundError(f"PDF file not found: {file_path}")
+
+ self.logger.info(f"Parsing PDF: {file_path.name}")
+
+ # Check for existing parsed content
+ output_dir = Path(kwargs.get("output_dir", self.output_dir or file_path.parent))
+ content_list_file = output_dir / f"{file_path.stem}.json"
+
+ content_items = []
+ content = ""
+
+ if content_list_file.exists():
+ # Load existing parsed content
+ self.logger.info(f"Loading existing parsed content from {content_list_file}")
+ with open(content_list_file, "r", encoding="utf-8") as f:
+ content_items = json.load(f)
+
+ # Extract text content
+ content = self._extract_text_from_content_items(content_items)
+ else:
+ # Parse PDF (placeholder - actual MinerU parsing would happen here)
+ self.logger.warning(
+ f"No pre-parsed content found. Use RAGAnythingPipeline for full PDF parsing."
+ )
+ # Basic text extraction fallback
+ content = await self._basic_pdf_extract(file_path)
+
+ return Document(
+ content=content,
+ file_path=str(file_path),
+ content_items=content_items,
+ metadata={
+ "filename": file_path.name,
+ "parser": self.name,
+ },
+ )
+
+ def _extract_text_from_content_items(self, content_items: list) -> str:
+ """Extract plain text from MinerU content items."""
+ texts = []
+ for item in content_items:
+ if isinstance(item, dict):
+ if "text" in item:
+ texts.append(item["text"])
+ elif "content" in item:
+ texts.append(item["content"])
+ return "\n\n".join(texts)
+
+ async def _basic_pdf_extract(self, file_path: Path) -> str:
+ """Basic PDF text extraction fallback."""
+ try:
+ import fitz # PyMuPDF
+
+ doc = fitz.open(file_path)
+ texts = []
+ for page in doc:
+ texts.append(page.get_text())
+ doc.close()
+ return "\n\n".join(texts)
+ except ImportError:
+ self.logger.warning("PyMuPDF not installed. Cannot extract PDF text.")
+ return ""
+ except Exception as e:
+ self.logger.error(f"Failed to extract PDF text: {e}")
+ return ""
+
diff --git a/src/services/rag/components/retrievers/__init__.py b/src/services/rag/components/retrievers/__init__.py
new file mode 100644
index 000000000..58301d74b
--- /dev/null
+++ b/src/services/rag/components/retrievers/__init__.py
@@ -0,0 +1,17 @@
+"""
+Document Retrievers
+===================
+
+Retrievers for searching indexed documents.
+"""
+
+from .base import BaseRetriever
+from .dense import DenseRetriever
+from .hybrid import HybridRetriever
+
+__all__ = [
+ "BaseRetriever",
+ "DenseRetriever",
+ "HybridRetriever",
+]
+
diff --git a/src/services/rag/components/retrievers/base.py b/src/services/rag/components/retrievers/base.py
new file mode 100644
index 000000000..df5b45c8a
--- /dev/null
+++ b/src/services/rag/components/retrievers/base.py
@@ -0,0 +1,35 @@
+"""
+Base Retriever
+==============
+
+Base class for document retrievers.
+"""
+
+from typing import Any, Dict
+
+from ..base import BaseComponent
+
+
+class BaseRetriever(BaseComponent):
+ """
+ Base class for document retrievers.
+
+ Retrievers search indexed documents and return relevant results.
+ """
+
+ name = "base_retriever"
+
+ async def process(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
+ """
+ Search for documents matching a query.
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ **kwargs: Additional arguments
+
+ Returns:
+ Search results dictionary
+ """
+ raise NotImplementedError("Subclasses must implement process()")
+
diff --git a/src/services/rag/components/retrievers/dense.py b/src/services/rag/components/retrievers/dense.py
new file mode 100644
index 000000000..c0d7a14bb
--- /dev/null
+++ b/src/services/rag/components/retrievers/dense.py
@@ -0,0 +1,115 @@
+"""
+Dense Retriever
+===============
+
+Dense vector-based retriever.
+"""
+
+import json
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from ..base import BaseComponent
+
+
+class DenseRetriever(BaseComponent):
+ """
+ Dense vector retriever.
+
+ Uses embedding similarity for retrieval.
+ """
+
+ name = "dense_retriever"
+
+ def __init__(self, kb_base_dir: Optional[str] = None, top_k: int = 5):
+ """
+ Initialize dense retriever.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ top_k: Number of results to return
+ """
+ super().__init__()
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent
+ / "data" / "knowledge_bases"
+ )
+ self.top_k = top_k
+
+ async def process(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
+ """
+ Search using dense embeddings.
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ **kwargs: Additional arguments
+
+ Returns:
+ Search results dictionary
+ """
+ self.logger.info(f"Dense search in {kb_name}: {query[:50]}...")
+
+ from src.services.embedding import get_embedding_client
+
+ # Get query embedding
+ client = get_embedding_client()
+ query_embedding = (await client.embed([query]))[0]
+
+ # Load index
+ kb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"
+ index_file = kb_dir / "index.json"
+
+ if not index_file.exists():
+ self.logger.warning(f"No vector index found at {index_file}")
+ return {
+ "query": query,
+ "answer": "No documents indexed.",
+ "content": "",
+ "mode": "dense",
+ "provider": "vector",
+ }
+
+ with open(index_file, "r", encoding="utf-8") as f:
+ index_data = json.load(f)
+
+ # Compute similarities
+ results = []
+ for item in index_data:
+ if item.get("embedding"):
+ similarity = self._cosine_similarity(query_embedding, item["embedding"])
+ results.append((similarity, item))
+
+ # Sort by similarity
+ results.sort(key=lambda x: x[0], reverse=True)
+ top_results = results[:self.top_k]
+
+ # Build response
+ content_parts = []
+ for score, item in top_results:
+ content_parts.append(f"[Score: {score:.3f}] {item['content'][:500]}")
+
+ content = "\n\n".join(content_parts)
+
+ return {
+ "query": query,
+ "answer": content,
+ "content": content,
+ "mode": "dense",
+ "provider": "vector",
+ "results": [item for _, item in top_results],
+ }
+
+ def _cosine_similarity(self, a: List[float], b: List[float]) -> float:
+ """Compute cosine similarity between two vectors."""
+ import math
+
+ dot_product = sum(x * y for x, y in zip(a, b))
+ norm_a = math.sqrt(sum(x * x for x in a))
+ norm_b = math.sqrt(sum(x * x for x in b))
+
+ if norm_a == 0 or norm_b == 0:
+ return 0.0
+
+ return dot_product / (norm_a * norm_b)
+
diff --git a/src/services/rag/components/retrievers/hybrid.py b/src/services/rag/components/retrievers/hybrid.py
new file mode 100644
index 000000000..1877633d6
--- /dev/null
+++ b/src/services/rag/components/retrievers/hybrid.py
@@ -0,0 +1,130 @@
+"""
+Hybrid Retriever
+================
+
+Hybrid retriever combining multiple retrieval strategies.
+"""
+
+from pathlib import Path
+import sys
+from typing import Any, Dict, Optional
+
+from ..base import BaseComponent
+
+
+class HybridRetriever(BaseComponent):
+ """
+ Hybrid retriever combining graph and vector retrieval.
+
+ Uses LightRAG's hybrid mode for retrieval.
+ """
+
+ name = "hybrid_retriever"
+ _instances: Dict[str, any] = {}
+
+ def __init__(self, kb_base_dir: Optional[str] = None):
+ """
+ Initialize hybrid retriever.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ """
+ super().__init__()
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent
+ / "data" / "knowledge_bases"
+ )
+
+ def _get_rag_instance(self, kb_name: str):
+ """Get or create a RAGAnything instance."""
+ working_dir = str(Path(self.kb_base_dir) / kb_name / "rag_storage")
+
+ if working_dir in self._instances:
+ return self._instances[working_dir]
+
+ # Add RAG-Anything path
+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent.parent
+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+ if raganything_path.exists() and str(raganything_path) not in sys.path:
+ sys.path.insert(0, str(raganything_path))
+
+ try:
+ from lightrag.llm.openai import openai_complete_if_cache
+ from raganything import RAGAnything, RAGAnythingConfig
+ from src.services.llm import get_llm_client
+ from src.services.embedding import get_embedding_client
+
+ llm_client = get_llm_client()
+ embed_client = get_embedding_client()
+
+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ return openai_complete_if_cache(
+ llm_client.config.model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ **kwargs,
+ )
+
+ config = RAGAnythingConfig(
+ working_dir=working_dir,
+ enable_image_processing=True,
+ enable_table_processing=True,
+ enable_equation_processing=True,
+ )
+
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ embedding_func=embed_client.get_embedding_func(),
+ )
+
+ self._instances[working_dir] = rag
+ return rag
+
+ except ImportError as e:
+ self.logger.error(f"Failed to import RAG-Anything: {e}")
+ raise
+
+ async def process(
+ self,
+ query: str,
+ kb_name: str,
+ mode: str = "hybrid",
+ only_need_context: bool = False,
+ **kwargs
+ ) -> Dict[str, Any]:
+ """
+ Search using hybrid retrieval.
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ mode: Search mode (hybrid, local, global, naive)
+ only_need_context: Whether to only return context without answer
+ **kwargs: Additional arguments
+
+ Returns:
+ Search results dictionary
+ """
+ self.logger.info(f"Hybrid search ({mode}) in {kb_name}: {query[:50]}...")
+
+ from src.logging.adapters import LightRAGLogContext
+
+ with LightRAGLogContext(scene="rag_search"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ answer = await rag.aquery(query, mode=mode, only_need_context=only_need_context)
+ answer_str = answer if isinstance(answer, str) else str(answer)
+
+ return {
+ "query": query,
+ "answer": answer_str,
+ "content": answer_str,
+ "mode": mode,
+ "provider": "hybrid",
+ }
+
diff --git a/src/services/rag/factory.py b/src/services/rag/factory.py
new file mode 100644
index 000000000..ed1861756
--- /dev/null
+++ b/src/services/rag/factory.py
@@ -0,0 +1,156 @@
+"""
+Pipeline Factory
+================
+
+Factory for creating and managing RAG pipelines.
+"""
+
+from typing import Callable, Dict, List, Union
+
+from .pipeline import RAGPipeline
+from .pipelines.raganything import RAGAnythingPipeline
+from .pipelines import lightrag, llamaindex, academic
+
+
+# Pipeline registry
+_PIPELINES: Dict[str, Callable] = {
+ "raganything": RAGAnythingPipeline,
+ "lightrag": lightrag.LightRAGPipeline,
+ "llamaindex": llamaindex.LlamaIndexPipeline,
+ "academic": academic.AcademicPipeline,
+}
+
+
+def get_pipeline(
+ name: str = "raganything",
+ **kwargs
+) -> Union[RAGPipeline, RAGAnythingPipeline]:
+ """
+ Get a pre-configured pipeline by name.
+
+ Args:
+ name: Pipeline name (raganything, lightrag, llamaindex, academic)
+ **kwargs: Additional arguments passed to pipeline constructor
+
+ Returns:
+ Pipeline instance
+
+ Raises:
+ ValueError: If pipeline name is not found
+ """
+ if name not in _PIPELINES:
+ available = list(_PIPELINES.keys())
+ raise ValueError(f"Unknown pipeline: {name}. Available: {available}")
+
+ factory = _PIPELINES[name]
+
+ # RAGAnythingPipeline takes kwargs, others are factory functions
+ if name == "raganything":
+ return factory(**kwargs) if kwargs else factory()
+ else:
+ # Factory functions don't take kwargs
+ return factory()
+
+
+def list_pipelines() -> List[Dict[str, str]]:
+ """
+ List available pipelines.
+
+ Returns:
+ List of pipeline info dictionaries
+ """
+ return [
+ {
+ "id": "raganything",
+ "name": "RAG-Anything",
+ "description": "End-to-end academic document processing (MinerU + LightRAG)",
+ },
+ {
+ "id": "lightrag",
+ "name": "LightRAG",
+ "description": "Component-based pipeline with knowledge graph",
+ },
+ {
+ "id": "llamaindex",
+ "name": "LlamaIndex",
+ "description": "Fast vector-based retrieval",
+ },
+ {
+ "id": "academic",
+ "name": "Academic",
+ "description": "Academic documents with numbered item extraction",
+ },
+ ]
+
+
+def register_pipeline(name: str, factory: Callable):
+ """
+ Register a custom pipeline.
+
+ Args:
+ name: Pipeline name
+ factory: Factory function or class that creates the pipeline
+ """
+ _PIPELINES[name] = factory
+
+
+def has_pipeline(name: str) -> bool:
+ """
+ Check if a pipeline exists.
+
+ Args:
+ name: Pipeline name
+
+ Returns:
+ True if pipeline exists
+ """
+ return name in _PIPELINES
+
+
+# Backward compatibility with old plugin API
+def get_plugin(name: str) -> Dict[str, Callable]:
+ """
+ DEPRECATED: Use get_pipeline() instead.
+
+ Get a plugin by name (maps to pipeline API).
+ """
+ import warnings
+ warnings.warn(
+ "get_plugin() is deprecated, use get_pipeline() instead",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ pipeline = get_pipeline(name)
+ return {
+ "initialize": pipeline.initialize,
+ "search": pipeline.search,
+ "delete": getattr(pipeline, "delete", lambda kb: True),
+ }
+
+
+def list_plugins() -> List[Dict[str, str]]:
+ """
+ DEPRECATED: Use list_pipelines() instead.
+ """
+ import warnings
+ warnings.warn(
+ "list_plugins() is deprecated, use list_pipelines() instead",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return list_pipelines()
+
+
+def has_plugin(name: str) -> bool:
+ """
+ DEPRECATED: Use has_pipeline() instead.
+ """
+ import warnings
+ warnings.warn(
+ "has_plugin() is deprecated, use has_pipeline() instead",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return has_pipeline(name)
+
diff --git a/src/services/rag/pipeline.py b/src/services/rag/pipeline.py
new file mode 100644
index 000000000..6c20d8f06
--- /dev/null
+++ b/src/services/rag/pipeline.py
@@ -0,0 +1,155 @@
+"""
+RAG Pipeline
+============
+
+Composable RAG pipeline with fluent API.
+"""
+
+import asyncio
+from typing import Any, Dict, List, Optional
+
+from src.logging import get_logger
+from .types import Document, Chunk
+from .components.base import Component
+
+
+class RAGPipeline:
+ """
+ Composable RAG pipeline.
+
+ Build custom RAG pipelines using a fluent API:
+
+ pipeline = (
+ RAGPipeline("custom")
+ .parser(PDFParser())
+ .chunker(SemanticChunker())
+ .embedder(OpenAIEmbedder())
+ .indexer(GraphIndexer())
+ .retriever(HybridRetriever())
+ )
+
+ await pipeline.initialize("kb_name", ["doc1.pdf"])
+ result = await pipeline.search("query", "kb_name")
+ """
+
+ def __init__(self, name: str = "default"):
+ """
+ Initialize RAG pipeline.
+
+ Args:
+ name: Pipeline name for logging
+ """
+ self.name = name
+ self.logger = get_logger(f"Pipeline:{name}")
+ self._parser: Optional[Component] = None
+ self._chunkers: List[Component] = []
+ self._embedder: Optional[Component] = None
+ self._indexers: List[Component] = []
+ self._retriever: Optional[Component] = None
+
+ # Fluent API methods
+ def parser(self, p: Component) -> "RAGPipeline":
+ """Set the document parser."""
+ self._parser = p
+ return self
+
+ def chunker(self, c: Component) -> "RAGPipeline":
+ """Add a chunker to the pipeline."""
+ self._chunkers.append(c)
+ return self
+
+ def embedder(self, e: Component) -> "RAGPipeline":
+ """Set the embedder."""
+ self._embedder = e
+ return self
+
+ def indexer(self, i: Component) -> "RAGPipeline":
+ """Add an indexer to the pipeline."""
+ self._indexers.append(i)
+ return self
+
+ def retriever(self, r: Component) -> "RAGPipeline":
+ """Set the retriever."""
+ self._retriever = r
+ return self
+
+ async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
+ """
+ Run full initialization pipeline.
+
+ Args:
+ kb_name: Knowledge base name
+ file_paths: List of file paths to process
+ **kwargs: Additional arguments passed to components
+
+ Returns:
+ True if successful
+ """
+ self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")
+
+ if not self._parser:
+ raise ValueError("No parser configured. Use .parser() to set one.")
+
+ # Stage 1: Parse documents
+ self.logger.info("Stage 1: Parsing documents...")
+ documents = []
+ for path in file_paths:
+ doc = await self._parser.process(path, **kwargs)
+ documents.append(doc)
+
+ # Stage 2: Chunk (sequential - later chunkers see earlier results)
+ if self._chunkers:
+ self.logger.info("Stage 2: Chunking...")
+ for chunker in self._chunkers:
+ for doc in documents:
+ new_chunks = await chunker.process(doc, **kwargs)
+ doc.chunks.extend(new_chunks)
+
+ # Stage 3: Embed
+ if self._embedder:
+ self.logger.info("Stage 3: Embedding...")
+ for doc in documents:
+ await self._embedder.process(doc, **kwargs)
+
+ # Stage 4: Index (can run in parallel)
+ if self._indexers:
+ self.logger.info("Stage 4: Indexing...")
+ await asyncio.gather(*[
+ indexer.process(kb_name, documents, **kwargs)
+ for indexer in self._indexers
+ ])
+
+ self.logger.info(f"KB '{kb_name}' initialized successfully")
+ return True
+
+ async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:
+ """
+ Search the knowledge base.
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ **kwargs: Additional arguments passed to retriever
+
+ Returns:
+ Search results dictionary
+ """
+ if not self._retriever:
+ raise ValueError("No retriever configured. Use .retriever() to set one.")
+
+ return await self._retriever.process(query, kb_name=kb_name, **kwargs)
+
+ async def delete(self, kb_name: str) -> bool:
+ """
+ Delete a knowledge base.
+
+ Args:
+ kb_name: Knowledge base name
+
+ Returns:
+ True if successful
+ """
+ self.logger.info(f"Deleting KB '{kb_name}'")
+ # Placeholder - actual deletion logic would depend on indexers
+ return True
+
diff --git a/src/services/rag/pipelines/__init__.py b/src/services/rag/pipelines/__init__.py
new file mode 100644
index 000000000..b2acff2e6
--- /dev/null
+++ b/src/services/rag/pipelines/__init__.py
@@ -0,0 +1,19 @@
+"""
+Pre-configured Pipelines
+========================
+
+Ready-to-use RAG pipelines for common use cases.
+"""
+
+from .raganything import RAGAnythingPipeline
+from .lightrag import LightRAGPipeline
+from .llamaindex import LlamaIndexPipeline
+from .academic import AcademicPipeline
+
+__all__ = [
+ "RAGAnythingPipeline",
+ "LightRAGPipeline",
+ "LlamaIndexPipeline",
+ "AcademicPipeline",
+]
+
diff --git a/src/services/rag/pipelines/academic.py b/src/services/rag/pipelines/academic.py
new file mode 100644
index 000000000..b538e8c64
--- /dev/null
+++ b/src/services/rag/pipelines/academic.py
@@ -0,0 +1,40 @@
+"""
+Academic Pipeline
+=================
+
+Pipeline optimized for academic documents with numbered item extraction.
+"""
+
+from ..pipeline import RAGPipeline
+from ..components.parsers import PDFParser
+from ..components.chunkers import SemanticChunker, NumberedItemExtractor
+from ..components.embedders import OpenAIEmbedder
+from ..components.indexers import GraphIndexer
+from ..components.retrievers import HybridRetriever
+
+
+def AcademicPipeline() -> RAGPipeline:
+ """
+ Create an academic document pipeline.
+
+ This pipeline uses:
+ - PDFParser with MinerU for multimodal parsing
+ - SemanticChunker for text chunking
+ - NumberedItemExtractor for extracting definitions, theorems, etc.
+ - OpenAIEmbedder for embedding generation
+ - GraphIndexer for knowledge graph indexing
+ - HybridRetriever for hybrid retrieval
+
+ Returns:
+ Configured RAGPipeline
+ """
+ return (
+ RAGPipeline("academic")
+ .parser(PDFParser(use_mineru=True))
+ .chunker(SemanticChunker())
+ .chunker(NumberedItemExtractor())
+ .embedder(OpenAIEmbedder())
+ .indexer(GraphIndexer())
+ .retriever(HybridRetriever())
+ )
+
diff --git a/src/services/rag/pipelines/lightrag.py b/src/services/rag/pipelines/lightrag.py
new file mode 100644
index 000000000..a2e6c26c2
--- /dev/null
+++ b/src/services/rag/pipelines/lightrag.py
@@ -0,0 +1,38 @@
+"""
+LightRAG Pipeline
+=================
+
+Component-based pipeline using LightRAG for knowledge graph indexing.
+"""
+
+from ..pipeline import RAGPipeline
+from ..components.parsers import PDFParser
+from ..components.chunkers import SemanticChunker
+from ..components.embedders import OpenAIEmbedder
+from ..components.indexers import GraphIndexer
+from ..components.retrievers import HybridRetriever
+
+
+def LightRAGPipeline() -> RAGPipeline:
+ """
+ Create a LightRAG-based pipeline.
+
+ This pipeline uses:
+ - PDFParser for document parsing
+ - SemanticChunker for text chunking
+ - OpenAIEmbedder for embedding generation
+ - GraphIndexer for knowledge graph indexing
+ - HybridRetriever for retrieval
+
+ Returns:
+ Configured RAGPipeline
+ """
+ return (
+ RAGPipeline("lightrag")
+ .parser(PDFParser())
+ .chunker(SemanticChunker())
+ .embedder(OpenAIEmbedder())
+ .indexer(GraphIndexer())
+ .retriever(HybridRetriever())
+ )
+
diff --git a/src/services/rag/pipelines/llamaindex.py b/src/services/rag/pipelines/llamaindex.py
new file mode 100644
index 000000000..e87f49e54
--- /dev/null
+++ b/src/services/rag/pipelines/llamaindex.py
@@ -0,0 +1,38 @@
+"""
+LlamaIndex Pipeline
+===================
+
+Component-based pipeline using vector indexing for fast retrieval.
+"""
+
+from ..pipeline import RAGPipeline
+from ..components.parsers import PDFParser
+from ..components.chunkers import SemanticChunker
+from ..components.embedders import OpenAIEmbedder
+from ..components.indexers import VectorIndexer
+from ..components.retrievers import DenseRetriever
+
+
+def LlamaIndexPipeline() -> RAGPipeline:
+ """
+ Create a LlamaIndex-style pipeline.
+
+ This pipeline uses:
+ - PDFParser for document parsing
+ - SemanticChunker for text chunking
+ - OpenAIEmbedder for embedding generation
+ - VectorIndexer for vector indexing
+ - DenseRetriever for dense retrieval
+
+ Returns:
+ Configured RAGPipeline
+ """
+ return (
+ RAGPipeline("llamaindex")
+ .parser(PDFParser())
+ .chunker(SemanticChunker())
+ .embedder(OpenAIEmbedder())
+ .indexer(VectorIndexer())
+ .retriever(DenseRetriever())
+ )
+
diff --git a/src/services/rag/pipelines/raganything.py b/src/services/rag/pipelines/raganything.py
new file mode 100644
index 000000000..fac2ff2a6
--- /dev/null
+++ b/src/services/rag/pipelines/raganything.py
@@ -0,0 +1,306 @@
+"""
+RAGAnything Pipeline
+====================
+
+End-to-end pipeline wrapping RAG-Anything for academic document processing.
+"""
+
+from pathlib import Path
+import sys
+from typing import Any, Dict, List, Optional
+
+from src.logging import get_logger
+from src.logging.adapters import LightRAGLogContext
+
+
+class RAGAnythingPipeline:
+ """
+ RAG-Anything end-to-end Pipeline.
+
+ Uses RAG-Anything's complete processing:
+ - MinerU PDF parsing (multimodal: images, tables, equations)
+ - LightRAG knowledge graph construction
+ - Hybrid retrieval (hybrid/local/global/naive modes)
+
+ This is a "monolithic" pipeline - best for academic documents.
+ """
+
+ name = "raganything"
+
+ def __init__(
+ self,
+ kb_base_dir: Optional[str] = None,
+ enable_image_processing: bool = True,
+ enable_table_processing: bool = True,
+ enable_equation_processing: bool = True,
+ ):
+ """
+ Initialize RAGAnything pipeline.
+
+ Args:
+ kb_base_dir: Base directory for knowledge bases
+ enable_image_processing: Enable image extraction and processing
+ enable_table_processing: Enable table extraction and processing
+ enable_equation_processing: Enable equation extraction and processing
+ """
+ self.logger = get_logger("RAGAnythingPipeline")
+ self.kb_base_dir = kb_base_dir or str(
+ Path(__file__).resolve().parent.parent.parent.parent.parent
+ / "data" / "knowledge_bases"
+ )
+ self.enable_image = enable_image_processing
+ self.enable_table = enable_table_processing
+ self.enable_equation = enable_equation_processing
+ self._instances: Dict[str, Any] = {}
+
+ def _setup_raganything_path(self):
+ """Add RAG-Anything to sys.path if available."""
+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent
+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"
+ if raganything_path.exists() and str(raganything_path) not in sys.path:
+ sys.path.insert(0, str(raganything_path))
+
+ def _get_rag_instance(self, kb_name: str):
+ """Get or create RAGAnything instance."""
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ working_dir = str(kb_dir / "rag_storage")
+
+ if working_dir in self._instances:
+ return self._instances[working_dir]
+
+ self._setup_raganything_path()
+
+ from lightrag.llm.openai import openai_complete_if_cache
+ from raganything import RAGAnything, RAGAnythingConfig
+ from src.services.llm import get_llm_client
+ from src.services.embedding import get_embedding_client
+
+ llm_client = get_llm_client()
+ embed_client = get_embedding_client()
+
+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ return openai_complete_if_cache(
+ llm_client.config.model,
+ prompt,
+ system_prompt=system_prompt,
+ history_messages=history_messages,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ **kwargs,
+ )
+
+ def vision_model_func(
+ prompt,
+ system_prompt=None,
+ history_messages=[],
+ image_data=None,
+ messages=None,
+ **kwargs,
+ ):
+ # Handle multimodal messages
+ if messages:
+ clean_kwargs = {
+ k: v for k, v in kwargs.items()
+ if k not in ["messages", "prompt", "system_prompt", "history_messages"]
+ }
+ return openai_complete_if_cache(
+ llm_client.config.model,
+ prompt="",
+ messages=messages,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ **clean_kwargs,
+ )
+ if image_data:
+ # Build image message
+ image_message = {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": prompt},
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},
+ },
+ ],
+ }
+ return openai_complete_if_cache(
+ llm_client.config.model,
+ prompt="",
+ messages=[image_message],
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ **kwargs,
+ )
+ return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+
+ config = RAGAnythingConfig(
+ working_dir=working_dir,
+ enable_image_processing=self.enable_image,
+ enable_table_processing=self.enable_table,
+ enable_equation_processing=self.enable_equation,
+ )
+
+ rag = RAGAnything(
+ config=config,
+ llm_model_func=llm_model_func,
+ vision_model_func=vision_model_func,
+ embedding_func=embed_client.get_embedding_func(),
+ )
+
+ self._instances[working_dir] = rag
+ return rag
+
+ async def initialize(
+ self,
+ kb_name: str,
+ file_paths: List[str],
+ extract_numbered_items: bool = True,
+ **kwargs,
+ ) -> bool:
+ """
+ Initialize KB using RAG-Anything's process_document_complete().
+
+ Args:
+ kb_name: Knowledge base name
+ file_paths: List of file paths to process
+ extract_numbered_items: Whether to extract numbered items after processing
+ **kwargs: Additional arguments
+
+ Returns:
+ True if successful
+ """
+ self.logger.info(f"Initializing KB '{kb_name}' with {len(file_paths)} files")
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ content_list_dir = kb_dir / "content_list"
+ content_list_dir.mkdir(parents=True, exist_ok=True)
+
+ with LightRAGLogContext(scene="knowledge_init"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ for idx, file_path in enumerate(file_paths, 1):
+ self.logger.info(f"Processing [{idx}/{len(file_paths)}]: {Path(file_path).name}")
+ await rag.process_document_complete(
+ file_path=file_path,
+ output_dir=str(content_list_dir),
+ parse_method="auto",
+ )
+
+ if extract_numbered_items:
+ await self._extract_numbered_items(kb_name)
+
+ self.logger.info(f"KB '{kb_name}' initialized successfully")
+ return True
+
+ async def _extract_numbered_items(self, kb_name: str):
+ """Extract numbered items using existing extraction logic."""
+ try:
+ import json
+ from src.services.llm import get_llm_client
+ from src.knowledge.extract_numbered_items import (
+ extract_numbered_items_with_llm_async,
+ )
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ content_list_dir = kb_dir / "content_list"
+
+ if not content_list_dir.exists():
+ self.logger.warning("No content_list directory found, skipping extraction")
+ return
+
+ # Load all content list files
+ all_content_items = []
+ for json_file in content_list_dir.glob("*.json"):
+ with open(json_file, "r", encoding="utf-8") as f:
+ content_items = json.load(f)
+ all_content_items.extend(content_items)
+
+ if not all_content_items:
+ self.logger.warning("No content items found for extraction")
+ return
+
+ self.logger.info(f"Extracting numbered items from {len(all_content_items)} content items")
+
+ llm_client = get_llm_client()
+ items = await extract_numbered_items_with_llm_async(
+ all_content_items,
+ api_key=llm_client.config.api_key,
+ base_url=llm_client.config.base_url,
+ )
+
+ # Save numbered items
+ if items:
+ output_file = kb_dir / "numbered_items.json"
+ with open(output_file, "w", encoding="utf-8") as f:
+ json.dump(items, f, ensure_ascii=False, indent=2)
+ self.logger.info(f"Extracted {len(items)} numbered items")
+
+ except ImportError as e:
+ self.logger.warning(f"Could not import extraction module: {e}")
+ except Exception as e:
+ self.logger.error(f"Failed to extract numbered items: {e}")
+
+ async def search(
+ self,
+ query: str,
+ kb_name: str,
+ mode: str = "hybrid",
+ only_need_context: bool = False,
+ **kwargs,
+ ) -> Dict[str, Any]:
+ """
+ Search using RAG-Anything's aquery().
+
+ Args:
+ query: Search query
+ kb_name: Knowledge base name
+ mode: Search mode (hybrid, local, global, naive)
+ only_need_context: Whether to only return context without answer
+ **kwargs: Additional arguments
+
+ Returns:
+ Search results dictionary
+ """
+ with LightRAGLogContext(scene="rag_search"):
+ rag = self._get_rag_instance(kb_name)
+ await rag._ensure_lightrag_initialized()
+
+ answer = await rag.aquery(query, mode=mode, only_need_context=only_need_context)
+ answer_str = answer if isinstance(answer, str) else str(answer)
+
+ return {
+ "query": query,
+ "answer": answer_str,
+ "content": answer_str,
+ "mode": mode,
+ "provider": "raganything",
+ }
+
+ async def delete(self, kb_name: str) -> bool:
+ """
+ Delete knowledge base.
+
+ Args:
+ kb_name: Knowledge base name
+
+ Returns:
+ True if successful
+ """
+ import shutil
+
+ kb_dir = Path(self.kb_base_dir) / kb_name
+ working_dir = str(kb_dir / "rag_storage")
+
+ # Remove from cache
+ if working_dir in self._instances:
+ del self._instances[working_dir]
+
+ # Delete directory
+ if kb_dir.exists():
+ shutil.rmtree(kb_dir)
+ self.logger.info(f"Deleted KB '{kb_name}'")
+ return True
+
+ return False
+
diff --git a/src/services/rag/types.py b/src/services/rag/types.py
new file mode 100644
index 000000000..ea45a98fd
--- /dev/null
+++ b/src/services/rag/types.py
@@ -0,0 +1,74 @@
+"""
+RAG Types
+=========
+
+Data types for the RAG pipeline.
+"""
+
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+
+@dataclass
+class Chunk:
+ """
+ Document chunk.
+
+ Represents a portion of a document with optional metadata and embedding.
+ """
+
+ content: str
+ chunk_type: str = "text" # text, definition, theorem, equation, figure, table...
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ embedding: Optional[List[float]] = None
+
+ def __post_init__(self):
+ if self.metadata is None:
+ self.metadata = {}
+
+
+@dataclass
+class Document:
+ """
+ Parsed document.
+
+ Contains the full document content, metadata, and chunks.
+ """
+
+ content: str
+ file_path: str = ""
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ chunks: List[Chunk] = field(default_factory=list)
+ content_items: List[Dict] = field(default_factory=list) # MinerU format
+
+ def __post_init__(self):
+ if self.metadata is None:
+ self.metadata = {}
+ if self.chunks is None:
+ self.chunks = []
+ if self.content_items is None:
+ self.content_items = []
+
+ def add_chunk(self, chunk: Chunk):
+ """Add a chunk to the document."""
+ self.chunks.append(chunk)
+
+ def get_chunks_by_type(self, chunk_type: str) -> List[Chunk]:
+ """Get all chunks of a specific type."""
+ return [c for c in self.chunks if c.chunk_type == chunk_type]
+
+
+@dataclass
+class SearchResult:
+ """
+ Search result from RAG query.
+ """
+
+ query: str
+ answer: str
+ content: str
+ mode: str = "hybrid"
+ provider: str = "raganything"
+ chunks: List[Chunk] = field(default_factory=list)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
diff --git a/src/services/setup/__init__.py b/src/services/setup/__init__.py
new file mode 100644
index 000000000..a69741de8
--- /dev/null
+++ b/src/services/setup/__init__.py
@@ -0,0 +1,33 @@
+"""
+Setup Service
+=============
+
+System setup and initialization for DeepTutor.
+
+Usage:
+ from src.services.setup import init_user_directories, get_backend_port
+
+ # Initialize user directories
+ init_user_directories()
+
+ # Get server ports
+ backend_port = get_backend_port()
+ frontend_port = get_frontend_port()
+"""
+
+from .init import (
+ init_user_directories,
+ get_backend_port,
+ get_frontend_port,
+ get_ports,
+ print_port_config_tutorial,
+)
+
+__all__ = [
+ "init_user_directories",
+ "get_backend_port",
+ "get_frontend_port",
+ "get_ports",
+ "print_port_config_tutorial",
+]
+
diff --git a/src/core/setup.py b/src/services/setup/init.py
similarity index 95%
rename from src/core/setup.py
rename to src/services/setup/init.py
index 40f0d5e49..ef22da99f 100644
--- a/src/core/setup.py
+++ b/src/services/setup/init.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
System Setup and Initialization
Combines user directory initialization and port configuration management.
@@ -8,8 +9,8 @@ import json
from pathlib import Path
import sys
-from src.core.core import load_config_with_main
-from src.core.logging import get_logger
+from src.services.config import load_config_with_main
+from src.logging import get_logger
# Initialize logger for setup operations
_setup_logger = None
@@ -52,7 +53,12 @@ def init_user_directories(project_root: Path | None = None) -> None:
project_root: Project root directory (if None, will try to detect)
"""
if project_root is None:
- project_root = Path(__file__).parent.parent.parent
+ # Path(__file__) = src/services/setup/init.py
+ # .parent = src/services/setup/
+ # .parent.parent = src/services/
+ # .parent.parent.parent = src/
+ # .parent.parent.parent.parent = DeepTutor/ (project root)
+ project_root = Path(__file__).parent.parent.parent.parent
# Get user data directory from config
try:
@@ -253,7 +259,7 @@ def get_backend_port(project_root: Path | None = None) -> int:
SystemExit: If port is not configured
"""
if project_root is None:
- project_root = Path(__file__).parent.parent.parent
+ project_root = Path(__file__).parent.parent.parent.parent
try:
config = load_config_with_main(
@@ -289,7 +295,7 @@ def get_frontend_port(project_root: Path | None = None) -> int:
SystemExit: If port is not configured
"""
if project_root is None:
- project_root = Path(__file__).parent.parent.parent
+ project_root = Path(__file__).parent.parent.parent.parent
try:
config = load_config_with_main(
@@ -338,3 +344,4 @@ __all__ = [
"get_ports",
"print_port_config_tutorial",
]
+
diff --git a/src/services/tts/__init__.py b/src/services/tts/__init__.py
new file mode 100644
index 000000000..238327ebb
--- /dev/null
+++ b/src/services/tts/__init__.py
@@ -0,0 +1,17 @@
+"""
+TTS Service
+===========
+
+Text-to-Speech configuration for DeepTutor.
+
+Usage:
+ from src.services.tts import get_tts_config
+
+ config = get_tts_config()
+ # config = {"model": "tts-1", "api_key": "...", "base_url": "...", "voice": "alloy"}
+"""
+
+from .config import get_tts_config
+
+__all__ = ["get_tts_config"]
+
diff --git a/src/services/tts/config.py b/src/services/tts/config.py
new file mode 100644
index 000000000..94fb92417
--- /dev/null
+++ b/src/services/tts/config.py
@@ -0,0 +1,67 @@
+"""
+TTS Configuration
+=================
+
+Configuration management for Text-to-Speech services.
+"""
+
+import os
+from pathlib import Path
+from typing import Optional
+
+from dotenv import load_dotenv
+
+# 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)
+
+
+def _strip_value(value: Optional[str]) -> Optional[str]:
+ """Remove leading/trailing whitespace and quotes from string."""
+ if value is None:
+ return None
+ return value.strip().strip("\"'")
+
+
+def get_tts_config() -> dict:
+ """
+ Return complete environment configuration for TTS (Text-to-Speech).
+
+ Returns:
+ dict: Dictionary containing the following keys:
+ - model: TTS model name
+ - api_key: TTS API key
+ - base_url: TTS API endpoint URL
+ - voice: Default voice character
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ model = _strip_value(os.getenv("TTS_MODEL"))
+ api_key = _strip_value(os.getenv("TTS_API_KEY"))
+ base_url = _strip_value(os.getenv("TTS_URL"))
+ voice = _strip_value(os.getenv("TTS_VOICE", "alloy"))
+
+ # Validate required configuration
+ if not model:
+ raise ValueError(
+ "Error: TTS_MODEL not set, please configure it in .env file (e.g., tts-1 or tts-1-hd)"
+ )
+ if not api_key:
+ raise ValueError("Error: TTS_API_KEY not set, please configure it in .env file")
+ if not base_url:
+ raise ValueError(
+ "Error: TTS_URL not set, please configure it in .env file (e.g., https://api.openai.com/v1)"
+ )
+
+ return {
+ "model": model,
+ "api_key": api_key,
+ "base_url": base_url,
+ "voice": voice,
+ }
+
+
+__all__ = ["get_tts_config"]
+
diff --git a/src/tools/__init__.py b/src/tools/__init__.py
index 8ad379a13..96cfd3836 100644
--- a/src/tools/__init__.py
+++ b/src/tools/__init__.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Tools Package - Unified tool collection
diff --git a/src/tools/code_executor.py b/src/tools/code_executor.py
index 240eac6c9..b1338df93 100644
--- a/src/tools/code_executor.py
+++ b/src/tools/code_executor.py
@@ -22,7 +22,7 @@ RUN_CODE_ALLOWED_ROOTS_ENV = "RUN_CODE_ALLOWED_ROOTS"
DEFAULT_WORKSPACE_NAME = "run_code_workspace"
PROJECT_ROOT = Path(__file__).resolve().parents[2]
-from src.core.logging import get_logger
+from src.logging import get_logger
logger = get_logger("CodeExecutor")
@@ -30,7 +30,7 @@ logger = get_logger("CodeExecutor")
def _load_config() -> dict[str, Any]:
"""Load run_code configuration from main.yaml and module configs"""
try:
- from src.core.core import load_config_with_main
+ from src.services.config import load_config_with_main
# Try loading from solve_config (most common use case)
try:
diff --git a/src/tools/query_item_tool.py b/src/tools/query_item_tool.py
index b53085d6c..9ba7206b9 100644
--- a/src/tools/query_item_tool.py
+++ b/src/tools/query_item_tool.py
@@ -1,4 +1,5 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
"""
Query Numbered Item Tool - Query definitions, theorems, formulas, figures, etc.
"""
@@ -53,7 +54,7 @@ def query_numbered_item(
# Load configuration for max_results if not specified
if max_results is None:
try:
- from src.core.core import load_config_with_main
+ from src.services.config import load_config_with_main
project_root = Path(__file__).parent.parent.parent
config = load_config_with_main("main.yaml", project_root)
diff --git a/src/tools/rag_tool.py b/src/tools/rag_tool.py
index 0c88dfa76..4dc8a192a 100644
--- a/src/tools/rag_tool.py
+++ b/src/tools/rag_tool.py
@@ -1,13 +1,13 @@
#!/usr/bin/env python
"""
-RAG Query Tool - Plugin-based RAG system
-Supports multiple RAG implementations through a simple plugin system
+RAG Query Tool - Pipeline-based RAG system
+Supports multiple RAG implementations through a unified pipeline system
"""
import asyncio
import os
from pathlib import Path
-from typing import Dict, List
+from typing import Dict, List, Optional
from dotenv import load_dotenv
@@ -16,32 +16,30 @@ project_root = Path(__file__).parent.parent.parent
load_dotenv(project_root / "DeepTutor.env", override=False)
load_dotenv(project_root / ".env", override=False)
-from src.rag.plugin_loader import get_plugin, list_plugins, has_plugin
-
-
-from src.rag.plugin_loader import get_plugin, list_plugins, has_plugin
+# Import from new services/rag module
+from src.services.rag.factory import get_pipeline, list_pipelines, has_pipeline
# Default RAG provider (can be overridden via environment variable)
-DEFAULT_RAG_PROVIDER = os.getenv("RAG_PROVIDER", "lightrag")
+DEFAULT_RAG_PROVIDER = os.getenv("RAG_PROVIDER", "raganything")
async def rag_search(
query: str,
- kb_name: str | None = None,
+ kb_name: Optional[str] = None,
mode: str = "hybrid",
- provider: str | None = None,
+ provider: Optional[str] = None,
**kwargs,
) -> dict:
"""
- Query knowledge base using configurable RAG provider.
+ Query knowledge base using configurable RAG pipeline.
Args:
query: Query question
kb_name: Knowledge base name (optional, defaults to default knowledge base)
mode: Query mode (e.g., "hybrid", "local", "global", "naive")
- provider: RAG provider to use (defaults to RAG_PROVIDER env var or "lightrag")
- **kwargs: Additional parameters passed to the RAG provider
+ provider: RAG pipeline to use (defaults to RAG_PROVIDER env var or "raganything")
+ **kwargs: Additional parameters passed to the RAG pipeline
Returns:
dict: Dictionary containing query results
@@ -54,7 +52,7 @@ async def rag_search(
}
Raises:
- ValueError: If the specified RAG provider is not found
+ ValueError: If the specified RAG pipeline is not found
Exception: If the query fails
Example:
@@ -62,26 +60,26 @@ async def rag_search(
result = await rag_search("What is machine learning?", kb_name="textbook")
# Override provider
- result = await rag_search("What is ML?", kb_name="textbook", provider="chromadb")
+ result = await rag_search("What is ML?", kb_name="textbook", provider="lightrag")
"""
# Determine which provider to use
provider_name = provider or DEFAULT_RAG_PROVIDER
# Validate provider exists
- if not has_plugin(provider_name):
- available = [p["id"] for p in list_plugins()]
+ if not has_pipeline(provider_name):
+ available = [p["id"] for p in list_pipelines()]
raise ValueError(
- f"RAG provider '{provider_name}' not found. "
- f"Available providers: {available}. "
+ f"RAG pipeline '{provider_name}' not found. "
+ f"Available pipelines: {available}. "
f"Set RAG_PROVIDER in .env or pass provider parameter."
)
- # Get the plugin
- plugin = get_plugin(provider_name)
+ # Get the pipeline
+ pipeline = get_pipeline(provider_name)
- # Execute search using the plugin
+ # Execute search using the pipeline
try:
- result = await plugin["search"](
+ result = await pipeline.search(
query=query,
kb_name=kb_name,
mode=mode,
@@ -95,49 +93,51 @@ async def rag_search(
result["answer"] = result["content"]
if "content" not in result and "answer" in result:
result["content"] = result["answer"]
+ if "provider" not in result:
+ result["provider"] = provider_name
return result
except Exception as e:
- raise Exception(f"RAG search failed with provider '{provider_name}': {e}")
+ raise Exception(f"RAG search failed with pipeline '{provider_name}': {e}")
async def initialize_rag(
kb_name: str,
documents: List[str],
- provider: str | None = None
+ provider: Optional[str] = None
) -> bool:
"""
Initialize RAG with documents.
Args:
kb_name: Knowledge base name
- documents: List of document contents to index
- provider: RAG provider to use (defaults to RAG_PROVIDER env var)
+ documents: List of document file paths to index
+ provider: RAG pipeline to use (defaults to RAG_PROVIDER env var)
Returns:
True if successful
Example:
- documents = ["Document 1 content", "Document 2 content"]
+ documents = ["doc1.pdf", "doc2.pdf"]
success = await initialize_rag("my_kb", documents)
"""
provider_name = provider or DEFAULT_RAG_PROVIDER
- if not has_plugin(provider_name):
- raise ValueError(f"RAG provider '{provider_name}' not found")
+ if not has_pipeline(provider_name):
+ raise ValueError(f"RAG pipeline '{provider_name}' not found")
- plugin = get_plugin(provider_name)
- return await plugin["initialize"](kb_name=kb_name, documents=documents)
+ pipeline = get_pipeline(provider_name)
+ return await pipeline.initialize(kb_name=kb_name, file_paths=documents)
-async def delete_rag(kb_name: str, provider: str | None = None) -> bool:
+async def delete_rag(kb_name: str, provider: Optional[str] = None) -> bool:
"""
Delete a knowledge base.
Args:
kb_name: Knowledge base name
- provider: RAG provider to use (defaults to RAG_PROVIDER env var)
+ provider: RAG pipeline to use (defaults to RAG_PROVIDER env var)
Returns:
True if successful
@@ -147,32 +147,37 @@ async def delete_rag(kb_name: str, provider: str | None = None) -> bool:
"""
provider_name = provider or DEFAULT_RAG_PROVIDER
- if not has_plugin(provider_name):
- raise ValueError(f"RAG provider '{provider_name}' not found")
+ if not has_pipeline(provider_name):
+ raise ValueError(f"RAG pipeline '{provider_name}' not found")
- plugin = get_plugin(provider_name)
- return await plugin["delete"](kb_name=kb_name)
+ pipeline = get_pipeline(provider_name)
+ return await pipeline.delete(kb_name=kb_name)
def get_available_providers() -> List[Dict]:
"""
- Get list of available RAG providers.
+ Get list of available RAG pipelines.
Returns:
- List of provider information dictionaries
+ List of pipeline information dictionaries
Example:
providers = get_available_providers()
for p in providers:
print(f"{p['name']}: {p['description']}")
"""
- return list_plugins()
+ return list_pipelines()
def get_current_provider() -> str:
"""Get the currently configured RAG provider"""
# Read directly from environment to get the latest value (not cached)
- return os.getenv("RAG_PROVIDER", "lightrag")
+ return os.getenv("RAG_PROVIDER", "raganything")
+
+
+# Backward compatibility aliases
+get_available_plugins = get_available_providers
+list_providers = list_pipelines
if __name__ == "__main__":
@@ -183,7 +188,7 @@ if __name__ == "__main__":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
# List available providers
- print("Available RAG Providers:")
+ print("Available RAG Pipelines:")
for provider in get_available_providers():
print(f" - {provider['id']}: {provider['description']}")
print(f"\nCurrent provider: {get_current_provider()}\n")
diff --git a/src/tools/tex_chunker.py b/src/tools/tex_chunker.py
index 8d3d14c7b..2f97bc15d 100644
--- a/src/tools/tex_chunker.py
+++ b/src/tools/tex_chunker.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
TeX Chunker - LaTeX text chunking tool
diff --git a/src/tools/tex_downloader.py b/src/tools/tex_downloader.py
index c39262ef4..1035a34cc 100644
--- a/src/tools/tex_downloader.py
+++ b/src/tools/tex_downloader.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
"""
TeX Downloader - LaTeX source code download tool
diff --git a/tests/core/test_prompt_manager.py b/tests/core/test_prompt_manager.py
index 6c613ec4b..d7ed960e8 100644
--- a/tests/core/test_prompt_manager.py
+++ b/tests/core/test_prompt_manager.py
@@ -11,7 +11,7 @@ import sys
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))
-from src.core.prompt_manager import PromptManager, get_prompt_manager
+from src.services.prompt import PromptManager, get_prompt_manager
class TestPromptManager:
diff --git a/web/app/history/page.tsx b/web/app/history/page.tsx
new file mode 100644
index 000000000..83c8adb24
--- /dev/null
+++ b/web/app/history/page.tsx
@@ -0,0 +1,419 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import {
+ History,
+ Clock,
+ ChevronRight,
+ Calculator,
+ FileText,
+ Microscope,
+ MessageCircle,
+ Filter,
+ Search,
+ Calendar,
+ X,
+ MessageSquare,
+ Loader2,
+} from "lucide-react";
+import { apiUrl } from "@/lib/api";
+import { getTranslation } from "@/lib/i18n";
+import { useGlobal } from "@/context/GlobalContext";
+import ActivityDetail from "@/components/ActivityDetail";
+
+interface HistoryEntry {
+ id: string;
+ type: "solve" | "question" | "research" | "chat";
+ title: string;
+ summary: string;
+ timestamp: number;
+ content: any;
+}
+
+const TYPE_CONFIG = {
+ solve: {
+ icon: Calculator,
+ color: "blue",
+ bgColor: "bg-blue-100 dark:bg-blue-900/30",
+ textColor: "text-blue-600 dark:text-blue-400",
+ },
+ question: {
+ icon: FileText,
+ color: "purple",
+ bgColor: "bg-purple-100 dark:bg-purple-900/30",
+ textColor: "text-purple-600 dark:text-purple-400",
+ },
+ research: {
+ icon: Microscope,
+ color: "emerald",
+ bgColor: "bg-emerald-100 dark:bg-emerald-900/30",
+ textColor: "text-emerald-600 dark:text-emerald-400",
+ },
+ chat: {
+ icon: MessageCircle,
+ color: "amber",
+ bgColor: "bg-amber-100 dark:bg-amber-900/30",
+ textColor: "text-amber-600 dark:text-amber-400",
+ },
+};
+
+// Chat session interface
+interface ChatSession {
+ session_id: string;
+ title: string;
+ message_count: number;
+ last_message: string;
+ created_at: number;
+ updated_at: number;
+}
+
+export default function HistoryPage() {
+ const { uiSettings, loadChatSession } = useGlobal();
+ const t = (key: string) => getTranslation(uiSettings.language, key);
+ const router = useRouter();
+
+ const [entries, setEntries] = useState<HistoryEntry[]>([]);
+ const [chatSessions, setChatSessions] = useState<ChatSession[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [loadingSessionId, setLoadingSessionId] = useState<string | null>(null);
+ const [selectedEntry, setSelectedEntry] = useState<HistoryEntry | null>(null);
+ const [filterType, setFilterType] = useState<string>("all");
+ const [searchQuery, setSearchQuery] = useState("");
+
+ useEffect(() => {
+ fetchHistory();
+ }, [filterType]);
+
+ const fetchHistory = async () => {
+ setLoading(true);
+ try {
+ // Fetch regular activity history
+ if (filterType === "all" || filterType !== "chat") {
+ const typeParam = filterType !== "all" ? `&type=${filterType}` : "";
+ const res = await fetch(apiUrl(`/api/v1/dashboard/recent?limit=50${typeParam}`));
+ const data = await res.json();
+ setEntries(data);
+ } else {
+ setEntries([]);
+ }
+
+ // Fetch chat sessions
+ if (filterType === "all" || filterType === "chat") {
+ try {
+ const sessionsRes = await fetch(apiUrl("/api/v1/chat/sessions?limit=20"));
+ const sessionsData = await sessionsRes.json();
+ setChatSessions(sessionsData);
+ } catch (err) {
+ console.error("Failed to fetch chat sessions:", err);
+ setChatSessions([]);
+ }
+ } else {
+ setChatSessions([]);
+ }
+ } catch (err) {
+ console.error("Failed to fetch history:", err);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleLoadChatSession = async (sessionId: string) => {
+ setLoadingSessionId(sessionId);
+ try {
+ await loadChatSession(sessionId);
+ router.push("/");
+ } catch (err) {
+ console.error("Failed to load session:", err);
+ } finally {
+ setLoadingSessionId(null);
+ }
+ };
+
+ const filteredEntries = entries.filter((entry) => {
+ // Exclude chat type - they are shown in dedicated Chat History section
+ if (entry.type === "chat") return false;
+
+ if (!searchQuery.trim()) return true;
+ const query = searchQuery.toLowerCase();
+ return (
+ entry.title.toLowerCase().includes(query) ||
+ entry.summary?.toLowerCase().includes(query)
+ );
+ });
+
+ const groupEntriesByDate = (entries: HistoryEntry[]) => {
+ const groups: { [key: string]: HistoryEntry[] } = {};
+
+ entries.forEach((entry) => {
+ const date = new Date(entry.timestamp * 1000);
+ const today = new Date();
+ const yesterday = new Date(today);
+ yesterday.setDate(yesterday.getDate() - 1);
+
+ let dateKey: string;
+ if (date.toDateString() === today.toDateString()) {
+ dateKey = "Today";
+ } else if (date.toDateString() === yesterday.toDateString()) {
+ dateKey = "Yesterday";
+ } else {
+ dateKey = date.toLocaleDateString(uiSettings.language === "zh" ? "zh-CN" : "en-US", {
+ month: "long",
+ day: "numeric",
+ year: date.getFullYear() !== today.getFullYear() ? "numeric" : undefined,
+ });
+ }
+
+ if (!groups[dateKey]) {
+ groups[dateKey] = [];
+ }
+ groups[dateKey].push(entry);
+ });
+
+ return groups;
+ };
+
+ const groupedEntries = groupEntriesByDate(filteredEntries);
+
+ return (
+ <div className="animate-fade-in space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 tracking-tight flex items-center gap-3">
+ <History className="w-8 h-8 text-blue-600 dark:text-blue-400" />
+ {t("History")}
+ </h1>
+ <p className="text-slate-500 dark:text-slate-400 mt-2">
+ {t("All Activities")}
+ </p>
+ </div>
+ </div>
+
+ {/* Filters */}
+ <div className="flex flex-wrap items-center gap-4">
+ {/* Search */}
+ <div className="relative flex-1 min-w-[200px] max-w-md">
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
+ <input
+ type="text"
+ placeholder={`${t("Search")}...`}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="w-full pl-10 pr-4 py-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
+ />
+ {searchQuery && (
+ <button
+ onClick={() => setSearchQuery("")}
+ className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ )}
+ </div>
+
+ {/* Type Filter */}
+ <div className="flex items-center gap-2">
+ <Filter className="w-4 h-4 text-slate-400" />
+ <div className="flex bg-slate-100 dark:bg-slate-800 rounded-lg p-1">
+ {[
+ { value: "all", label: t("All") },
+ { value: "chat", label: t("Chat") },
+ { value: "solve", label: t("Solve") },
+ { value: "question", label: t("Question") },
+ { value: "research", label: t("Research") },
+ ].map((option) => (
+ <button
+ key={option.value}
+ onClick={() => setFilterType(option.value)}
+ className={`px-3 py-1.5 text-sm font-medium rounded-md transition-all ${
+ filterType === option.value
+ ? "bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
+ {loading ? (
+ <div className="p-12 text-center text-slate-400 dark:text-slate-500">
+ <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
+ {t("Loading")}...
+ </div>
+ ) : filteredEntries.length === 0 && chatSessions.length === 0 ? (
+ <div className="p-12 text-center">
+ <div className="w-16 h-16 bg-slate-50 dark:bg-slate-700 rounded-full flex items-center justify-center mx-auto mb-4">
+ <History className="w-8 h-8 text-slate-300 dark:text-slate-500" />
+ </div>
+ <p className="text-slate-500 dark:text-slate-400 font-medium">
+ {t("No history found")}
+ </p>
+ <p className="text-sm text-slate-400 dark:text-slate-500 mt-1">
+ {t("Your activities will appear here")}
+ </p>
+ </div>
+ ) : (
+ <div className="divide-y divide-slate-100 dark:divide-slate-700">
+ {Object.entries(groupedEntries).map(([dateKey, dateEntries]) => (
+ <div key={dateKey}>
+ {/* Date Header */}
+ <div className="px-5 py-3 bg-slate-50 dark:bg-slate-900/50 border-b border-slate-100 dark:border-slate-700">
+ <div className="flex items-center gap-2 text-sm font-medium text-slate-600 dark:text-slate-400">
+ <Calendar className="w-4 h-4" />
+ {dateKey}
+ </div>
+ </div>
+
+ {/* Entries for this date */}
+ {dateEntries.map((entry) => {
+ const config = TYPE_CONFIG[entry.type] || TYPE_CONFIG.chat;
+ const IconComponent = config.icon;
+
+ return (
+ <div
+ key={entry.id}
+ onClick={() => setSelectedEntry(entry)}
+ className="px-5 py-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors group cursor-pointer"
+ >
+ <div className="flex gap-4">
+ <div className="mt-0.5">
+ <div
+ className={`w-10 h-10 rounded-xl ${config.bgColor} flex items-center justify-center group-hover:scale-110 transition-transform duration-300`}
+ >
+ <IconComponent className={`w-5 h-5 ${config.textColor}`} />
+ </div>
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex justify-between items-start">
+ <span
+ className={`text-xs font-bold uppercase tracking-wider ${config.textColor} mb-1`}
+ >
+ {entry.type}
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500 flex items-center gap-1">
+ <Clock className="w-3 h-3" />
+ {new Date(entry.timestamp * 1000).toLocaleTimeString(
+ uiSettings.language === "zh" ? "zh-CN" : "en-US",
+ { hour: "2-digit", minute: "2-digit" }
+ )}
+ </span>
+ </div>
+ <h3 className="text-base font-semibold text-slate-900 dark:text-slate-100 truncate pr-4">
+ {entry.title}
+ </h3>
+ {entry.summary && (
+ <p className="text-sm text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
+ {entry.summary}
+ </p>
+ )}
+ </div>
+ <div className="self-center opacity-0 group-hover:opacity-100 transition-opacity">
+ <ChevronRight className="w-5 h-5 text-slate-400 dark:text-slate-500" />
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Chat Sessions Section */}
+ {chatSessions.length > 0 && (filterType === "all" || filterType === "chat") && (
+ <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
+ <div className="px-5 py-4 border-b border-slate-100 dark:border-slate-700 flex items-center gap-2">
+ <MessageSquare className="w-5 h-5 text-amber-500" />
+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">
+ {t("Chat History")}
+ </h2>
+ <span className="text-xs text-slate-400 ml-auto">
+ {chatSessions.length} {chatSessions.length === 1 ? "session" : "sessions"}
+ </span>
+ </div>
+ <div className="divide-y divide-slate-100 dark:divide-slate-700">
+ {chatSessions
+ .filter((session) => {
+ if (!searchQuery.trim()) return true;
+ const query = searchQuery.toLowerCase();
+ return (
+ session.title.toLowerCase().includes(query) ||
+ session.last_message?.toLowerCase().includes(query)
+ );
+ })
+ .map((session) => (
+ <div
+ key={session.session_id}
+ className="px-5 py-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors group"
+ >
+ <div className="flex gap-4">
+ <div className="mt-0.5">
+ <div className="w-10 h-10 rounded-xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
+ <MessageCircle className="w-5 h-5 text-amber-600 dark:text-amber-400" />
+ </div>
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex justify-between items-start">
+ <span className="text-xs font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400 mb-1">
+ Chat
+ </span>
+ <span className="text-xs text-slate-400 dark:text-slate-500 flex items-center gap-1">
+ <Clock className="w-3 h-3" />
+ {new Date(session.updated_at * 1000).toLocaleDateString(
+ uiSettings.language === "zh" ? "zh-CN" : "en-US"
+ )}
+ </span>
+ </div>
+ <h3 className="text-base font-semibold text-slate-900 dark:text-slate-100 truncate pr-4">
+ {session.title}
+ </h3>
+ <div className="flex items-center gap-2 mt-1">
+ <span className="text-xs text-slate-400 dark:text-slate-500">
+ {session.message_count} messages
+ </span>
+ {session.last_message && (
+ <p className="text-sm text-slate-500 dark:text-slate-400 truncate flex-1">
+ {session.last_message}
+ </p>
+ )}
+ </div>
+ </div>
+ <div className="self-center">
+ <button
+ onClick={() => handleLoadChatSession(session.session_id)}
+ disabled={loadingSessionId === session.session_id}
+ className="px-3 py-1.5 text-xs font-medium bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded-lg hover:bg-amber-200 dark:hover:bg-amber-900/50 transition-colors flex items-center gap-1.5 disabled:opacity-50"
+ >
+ {loadingSessionId === session.session_id ? (
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ ) : (
+ <MessageSquare className="w-3.5 h-3.5" />
+ )}
+ {t("Continue")}
+ </button>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Activity Detail Modal */}
+ {selectedEntry && (
+ <ActivityDetail
+ activity={selectedEntry}
+ onClose={() => setSelectedEntry(null)}
+ />
+ )}
+ </div>
+ );
+}
+
diff --git a/web/app/page.tsx b/web/app/page.tsx
index 4ed0755de..b78cafb28 100644
--- a/web/app/page.tsx
+++ b/web/app/page.tsx
@@ -1,425 +1,481 @@
"use client";
-import { useState, useEffect } from "react";
+import { useState, useEffect, useRef } from "react";
import {
- LayoutDashboard,
- History,
- ArrowRight,
- FileText,
- HelpCircle,
- Search,
- Clock,
- ChevronRight,
+ Send,
+ Loader2,
+ Bot,
+ User,
Database,
- BookOpen,
- Book,
+ Globe,
Calculator,
+ FileText,
Microscope,
- PenTool,
- Plus,
Lightbulb,
- LucideIcon,
+ Trash2,
+ ExternalLink,
+ BookOpen,
+ Sparkles,
+ Edit3,
+ GraduationCap,
+ PenTool,
} from "lucide-react";
import Link from "next/link";
-import ActivityDetail from "@/components/ActivityDetail";
-import SystemStatus from "@/components/SystemStatus";
+import ReactMarkdown from "react-markdown";
+import remarkMath from "remark-math";
+import rehypeKatex from "rehype-katex";
+import "katex/dist/katex.min.css";
+import { useGlobal } from "@/context/GlobalContext";
import { apiUrl } from "@/lib/api";
+import { processLatexContent } from "@/lib/latex";
import { getTranslation } from "@/lib/i18n";
-import { useGlobal } from "@/context/GlobalContext";
-
-// Icon mapping for data-driven UI
-const ICON_MAP: Record<string, LucideIcon> = {
- HelpCircle,
- FileText,
- Search,
- PenTool,
- BookOpen,
- Lightbulb,
- LayoutDashboard,
-};
-
-// Color mapping for Tailwind classes
-const COLOR_MAP: Record<string, string> = {
- blue: "text-blue-500",
- purple: "text-purple-500",
- emerald: "text-emerald-500",
- amber: "text-amber-500",
- indigo: "text-indigo-500",
- yellow: "text-yellow-500",
- slate: "text-slate-500",
-};
-
-// Fallback agent config (used if API fails)
-const FALLBACK_AGENT_CONFIG: Record<string, AgentConfig> = {
- solve: { icon: "HelpCircle", color: "blue", label_key: "Problem Solved" },
- question: {
- icon: "FileText",
- color: "purple",
- label_key: "Question Generated",
- },
- research: { icon: "Search", color: "emerald", label_key: "Research Report" },
- co_writer: { icon: "PenTool", color: "amber", label_key: "Co-Writer" },
- guide: { icon: "BookOpen", color: "indigo", label_key: "Guided Learning" },
- ideagen: { icon: "Lightbulb", color: "yellow", label_key: "Idea Generated" },
-};
-interface AgentConfig {
- icon: string;
- color: string;
- label_key: string;
-}
-
-interface Activity {
- id: string;
- type: "solve" | "question" | "research";
- title: string;
- summary: string;
- timestamp: number;
- content: any;
-}
-
-interface NotebookSummary {
- id: string;
+interface KnowledgeBase {
name: string;
- description: string;
- record_count: number;
- updated_at: number;
- color: string;
-}
-
-interface NotebookStats {
- total_notebooks: number;
- total_records: number;
- records_by_type: {
- solve: number;
- question: number;
- research: number;
- co_writer: number;
- };
- recent_notebooks: NotebookSummary[];
+ is_default?: boolean;
}
-export default function DashboardPage() {
- const { uiSettings } = useGlobal();
+export default function HomePage() {
+ const {
+ chatState,
+ setChatState,
+ sendChatMessage,
+ clearChatHistory,
+ newChatSession,
+ uiSettings,
+ } = useGlobal();
const t = (key: string) => getTranslation(uiSettings.language, key);
- const [activities, setActivities] = useState<Activity[]>([]);
- const [loading, setLoading] = useState(true);
- const [selectedActivity, setSelectedActivity] = useState<Activity | null>(
- null,
- );
- const [notebookStats, setNotebookStats] = useState<NotebookStats | null>(
- null,
- );
- const [agentConfig, setAgentConfig] = useState<Record<string, AgentConfig>>(
- FALLBACK_AGENT_CONFIG,
- );
- useEffect(() => {
- // Fetch agent configuration
- fetch(apiUrl("/api/v1/config/agents"))
- .then((res) => res.json())
- .then((data) => setAgentConfig(data))
- .catch((err) => {
- console.error("Failed to fetch agent config, using fallback:", err);
- });
+ const [inputMessage, setInputMessage] = useState("");
+ const [kbs, setKbs] = useState<KnowledgeBase[]>([]);
+ const chatEndRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
- // Fetch activities
- fetch(apiUrl("/api/v1/dashboard/recent?limit=10"))
+ // Fetch knowledge bases
+ useEffect(() => {
+ fetch(apiUrl("/api/v1/knowledge/list"))
.then((res) => res.json())
- .then((data) => setActivities(data))
- .catch((err) => {
- console.error(err);
+ .then((data) => {
+ setKbs(data);
+ if (!chatState.selectedKb) {
+ const defaultKb = data.find((kb: KnowledgeBase) => kb.is_default);
+ if (defaultKb) {
+ setChatState((prev) => ({ ...prev, selectedKb: defaultKb.name }));
+ } else if (data.length > 0) {
+ setChatState((prev) => ({ ...prev, selectedKb: data[0].name }));
+ }
+ }
})
- .finally(() => setLoading(false));
-
- // Fetch notebook statistics
- fetch(apiUrl("/api/v1/notebook/statistics"))
- .then((res) => res.json())
- .then((data) => setNotebookStats(data))
- .catch((err) => {
- console.error("Failed to fetch notebook stats:", err);
- });
+ .catch((err) => console.error("Failed to fetch KBs:", err));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- // Data-driven icon getter
- const getIcon = (type: string) => {
- const config = agentConfig[type];
- const IconComponent = ICON_MAP[config?.icon] || LayoutDashboard;
- const colorClass = COLOR_MAP[config?.color] || "text-slate-500";
- return <IconComponent className={`w-5 h-5 ${colorClass}`} />;
+ // Auto-scroll to bottom when new messages arrive
+ useEffect(() => {
+ if (chatEndRef.current) {
+ chatEndRef.current.scrollIntoView({ behavior: "smooth" });
+ }
+ }, [chatState.messages]);
+
+ const handleSend = () => {
+ if (!inputMessage.trim() || chatState.isLoading) return;
+ sendChatMessage(inputMessage);
+ setInputMessage("");
};
- // Data-driven label getter
- const getLabel = (type: string) => {
- const config = agentConfig[type];
- return t(config?.label_key || "Activity");
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSend();
+ }
};
- return (
- <div className="animate-fade-in space-y-8">
- {/* Header */}
- <div>
- <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 tracking-tight flex items-center gap-3">
- <LayoutDashboard className="w-8 h-8 text-blue-600 dark:text-blue-400" />
- {t("Dashboard")}
- </h1>
- <p className="text-slate-500 dark:text-slate-400 mt-2">
- {t("Overview of your recent learning activities")}
- </p>
- </div>
+ const quickActions = [
+ {
+ icon: Calculator,
+ label: t("Smart Problem Solving"),
+ href: "/solver",
+ color: "blue",
+ description: "Multi-agent reasoning",
+ },
+ {
+ icon: PenTool,
+ label: t("Generate Practice Questions"),
+ href: "/question",
+ color: "purple",
+ description: "Auto-validated quizzes",
+ },
+ {
+ icon: Microscope,
+ label: t("Deep Research Reports"),
+ href: "/research",
+ color: "emerald",
+ description: "Comprehensive analysis",
+ },
+ {
+ icon: Lightbulb,
+ label: t("Generate Novel Ideas"),
+ href: "/ideagen",
+ color: "amber",
+ description: "Brainstorm & synthesize",
+ },
+ {
+ icon: GraduationCap,
+ label: t("Guided Learning"),
+ href: "/guide",
+ color: "indigo",
+ description: "Step-by-step tutoring",
+ },
+ {
+ icon: Edit3,
+ label: t("Co-Writer"),
+ href: "/co_writer",
+ color: "pink",
+ description: "Collaborative writing",
+ },
+ ];
- <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
- {/* Left: Recent Activity Feed */}
- <div className="lg:col-span-2 space-y-6">
- <div className="flex items-center justify-between">
- <h2 className="text-lg font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
- <History className="w-5 h-5 text-slate-400 dark:text-slate-500" />
- {t("Recent Activity")}
- </h2>
- <Link
- href="#"
- className="text-sm text-blue-600 dark:text-blue-400 font-medium hover:underline flex items-center gap-1"
- >
- {t("View All")} <ChevronRight className="w-4 h-4" />
- </Link>
+ const hasMessages = chatState.messages.length > 0;
+
+ return (
+ <div className="h-[calc(100vh-4rem)] flex flex-col animate-fade-in">
+ {/* Empty State / Welcome Screen */}
+ {!hasMessages && (
+ <div className="flex-1 flex flex-col items-center justify-center px-4">
+ <div className="text-center max-w-2xl mx-auto mb-8">
+ <h1 className="text-4xl font-bold text-slate-900 dark:text-slate-100 mb-3 tracking-tight">
+ {t("Welcome to DeepTutor")}
+ </h1>
+ <p className="text-lg text-slate-500 dark:text-slate-400">
+ {t("How can I help you today?")}
+ </p>
</div>
- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 divide-y divide-slate-100 dark:divide-slate-700 overflow-hidden">
- {loading ? (
- <div className="p-8 text-center text-slate-400 dark:text-slate-500">
- {t("Loading activities...")}
- </div>
- ) : activities.length === 0 ? (
- <div className="p-12 text-center">
- <div className="w-16 h-16 bg-slate-50 dark:bg-slate-700 rounded-full flex items-center justify-center mx-auto mb-4">
- <History className="w-8 h-8 text-slate-300 dark:text-slate-500" />
- </div>
- <p className="text-slate-500 dark:text-slate-400">
- {t("No recent activity found")}
- </p>
- <p className="text-sm text-slate-400 dark:text-slate-500 mt-1">
- {t("Start solving problems or generating questions!")}
- </p>
+ {/* Input Box - Centered */}
+ <div className="w-full max-w-2xl mx-auto mb-12">
+ {/* Mode Toggles */}
+ <div className="flex items-center justify-between mb-3 px-1">
+ <div className="flex items-center gap-2">
+ {/* RAG Toggle */}
+ <button
+ onClick={() =>
+ setChatState((prev) => ({
+ ...prev,
+ enableRag: !prev.enableRag,
+ }))
+ }
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium transition-all ${
+ chatState.enableRag
+ ? "bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-700"
+ : "bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-slate-700 hover:bg-slate-200 dark:hover:bg-slate-700"
+ }`}
+ >
+ <Database className="w-3.5 h-3.5" />
+ {t("RAG")}
+ </button>
+
+ {/* Web Search Toggle */}
+ <button
+ onClick={() =>
+ setChatState((prev) => ({
+ ...prev,
+ enableWebSearch: !prev.enableWebSearch,
+ }))
+ }
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium transition-all ${
+ chatState.enableWebSearch
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-700"
+ : "bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-slate-700 hover:bg-slate-200 dark:hover:bg-slate-700"
+ }`}
+ >
+ <Globe className="w-3.5 h-3.5" />
+ {t("Web Search")}
+ </button>
</div>
- ) : (
- activities.map((activity) => (
- <div
- key={activity.id}
- onClick={() => setSelectedActivity(activity)}
- className="p-5 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors group cursor-pointer"
+
+ {/* KB Selector */}
+ {chatState.enableRag && (
+ <select
+ value={chatState.selectedKb}
+ onChange={(e) =>
+ setChatState((prev) => ({
+ ...prev,
+ selectedKb: e.target.value,
+ }))
+ }
+ className="text-sm bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg px-3 py-1.5 outline-none focus:border-blue-400 dark:text-slate-200"
>
- <div className="flex gap-4">
- <div className="mt-1">
- <div className="w-10 h-10 rounded-xl bg-slate-50 dark:bg-slate-700 border border-slate-100 dark:border-slate-600 flex items-center justify-center group-hover:scale-110 transition-transform duration-300">
- {getIcon(activity.type)}
- </div>
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex justify-between items-start">
- <p className="text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-slate-400 mb-1">
- {getLabel(activity.type)}
- </p>
- <span className="text-xs text-slate-400 dark:text-slate-500 flex items-center gap-1">
- <Clock className="w-3 h-3" />
- {new Date(
- activity.timestamp * 1000,
- ).toLocaleDateString()}
- </span>
- </div>
- <h3 className="text-base font-semibold text-slate-900 dark:text-slate-100 truncate pr-4">
- {activity.title}
- </h3>
- {activity.summary && (
- <p className="text-sm text-slate-500 dark:text-slate-400 mt-1 line-clamp-2">
- {activity.summary}
- </p>
- )}
- {activity.content?.kb_name && (
- <div className="mt-3 flex items-center gap-2">
- <span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 border border-slate-200 dark:border-slate-600">
- <Database className="w-3 h-3 mr-1" />
- {activity.content.kb_name}
- </span>
- </div>
- )}
- </div>
- <div className="self-center opacity-0 group-hover:opacity-100 transition-opacity">
- <ArrowRight className="w-5 h-5 text-slate-400 dark:text-slate-500" />
- </div>
+ {kbs.map((kb) => (
+ <option key={kb.name} value={kb.name}>
+ {kb.name}
+ </option>
+ ))}
+ </select>
+ )}
+ </div>
+
+ {/* Input Field */}
+ <div className="relative">
+ <input
+ ref={inputRef}
+ type="text"
+ className="w-full px-5 py-4 pr-14 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-2xl focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-500 text-slate-700 dark:text-slate-200 shadow-lg shadow-slate-200/50 dark:shadow-slate-900/50"
+ placeholder={t("Ask anything...")}
+ value={inputMessage}
+ onChange={(e) => setInputMessage(e.target.value)}
+ onKeyDown={handleKeyDown}
+ disabled={chatState.isLoading}
+ />
+ <button
+ onClick={handleSend}
+ disabled={chatState.isLoading || !inputMessage.trim()}
+ className="absolute right-2 top-2 bottom-2 aspect-square bg-blue-600 text-white rounded-xl flex items-center justify-center hover:bg-blue-700 disabled:opacity-50 disabled:hover:bg-blue-600 transition-all shadow-md shadow-blue-500/20"
+ >
+ {chatState.isLoading ? (
+ <Loader2 className="w-5 h-5 animate-spin" />
+ ) : (
+ <Send className="w-5 h-5" />
+ )}
+ </button>
+ </div>
+ </div>
+
+ {/* Quick Actions Grid */}
+ <div className="w-full max-w-3xl mx-auto">
+ <h3 className="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-4 text-center">
+ {t("Explore Modules")}
+ </h3>
+ <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
+ {quickActions.map((action, i) => (
+ <Link
+ key={i}
+ href={action.href}
+ className={`group p-4 rounded-2xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:shadow-lg hover:border-${action.color}-300 dark:hover:border-${action.color}-600 transition-all`}
+ >
+ <div
+ className={`w-10 h-10 rounded-xl bg-${action.color}-100 dark:bg-${action.color}-900/30 flex items-center justify-center mb-3 group-hover:scale-110 transition-transform`}
+ >
+ <action.icon
+ className={`w-5 h-5 text-${action.color}-600 dark:text-${action.color}-400`}
+ />
</div>
- </div>
- ))
- )}
+ <h4 className="font-semibold text-slate-900 dark:text-slate-100 text-sm mb-1">
+ {action.label}
+ </h4>
+ <p className="text-xs text-slate-500 dark:text-slate-400">
+ {action.description}
+ </p>
+ </Link>
+ ))}
+ </div>
</div>
</div>
+ )}
+
+ {/* Chat Interface - When there are messages */}
+ {hasMessages && (
+ <>
+ {/* Header Bar */}
+ <div className="flex items-center justify-between px-4 py-3 border-b border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-800/80 backdrop-blur-sm">
+ <div className="flex items-center gap-3">
+ {/* Mode Toggles */}
+ <button
+ onClick={() =>
+ setChatState((prev) => ({
+ ...prev,
+ enableRag: !prev.enableRag,
+ }))
+ }
+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium transition-all ${
+ chatState.enableRag
+ ? "bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300"
+ : "bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400"
+ }`}
+ >
+ <Database className="w-3 h-3" />
+ {t("RAG")}
+ </button>
- {/* Right: Quick Actions / Stats */}
- <div className="space-y-6">
- {/* Notebooks Overview */}
- <div className="bg-gradient-to-br from-indigo-600 to-purple-600 rounded-2xl p-6 text-white shadow-lg">
- <div className="flex items-center justify-between mb-4">
- <h3 className="font-bold text-lg flex items-center gap-2">
- <Book className="w-5 h-5" />
- {t("My Notebooks")}
- </h3>
- <Link
- href="/notebook"
- className="text-xs text-white/80 hover:text-white flex items-center gap-1"
+ <button
+ onClick={() =>
+ setChatState((prev) => ({
+ ...prev,
+ enableWebSearch: !prev.enableWebSearch,
+ }))
+ }
+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium transition-all ${
+ chatState.enableWebSearch
+ ? "bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300"
+ : "bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400"
+ }`}
>
- {t("View All")} <ChevronRight className="w-3 h-3" />
- </Link>
+ <Globe className="w-3 h-3" />
+ {t("Web Search")}
+ </button>
+
+ {chatState.enableRag && (
+ <select
+ value={chatState.selectedKb}
+ onChange={(e) =>
+ setChatState((prev) => ({
+ ...prev,
+ selectedKb: e.target.value,
+ }))
+ }
+ className="text-xs bg-slate-100 dark:bg-slate-800 border-0 rounded-lg px-2 py-1 outline-none dark:text-slate-200"
+ >
+ {kbs.map((kb) => (
+ <option key={kb.name} value={kb.name}>
+ {kb.name}
+ </option>
+ ))}
+ </select>
+ )}
</div>
- {notebookStats ? (
- <>
- <div className="grid grid-cols-2 gap-3 mb-4">
- <div className="bg-white/10 rounded-xl p-3">
- <div className="text-2xl font-bold">
- {notebookStats.total_notebooks}
+ <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>
+
+ {/* Messages Area */}
+ <div className="flex-1 overflow-y-auto px-4 py-6 space-y-6">
+ {chatState.messages.map((msg, idx) => (
+ <div
+ key={idx}
+ className="flex gap-4 w-full max-w-4xl mx-auto animate-in fade-in slide-in-from-bottom-2"
+ >
+ {msg.role === "user" ? (
+ <>
+ <div className="w-8 h-8 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center shrink-0">
+ <User className="w-4 h-4 text-slate-500 dark:text-slate-400" />
</div>
- <div className="text-xs text-white/70">
- {t("Notebooks")}
+ <div className="flex-1 bg-slate-100 dark:bg-slate-700 px-4 py-3 rounded-2xl rounded-tl-none text-slate-800 dark:text-slate-200">
+ {msg.content}
</div>
- </div>
- <div className="bg-white/10 rounded-xl p-3">
- <div className="text-2xl font-bold">
- {notebookStats.total_records}
+ </>
+ ) : (
+ <>
+ <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shrink-0 shadow-lg shadow-blue-500/30">
+ <Bot className="w-4 h-4 text-white" />
</div>
- <div className="text-xs text-white/70">{t("records")}</div>
- </div>
- </div>
-
- {/* Records by type */}
- <div className="space-y-2">
- <div className="flex items-center justify-between text-xs">
- <span className="flex items-center gap-1.5 text-white/80">
- <Calculator className="w-3 h-3" /> {t("Solve")}
- </span>
- <span className="font-medium">
- {notebookStats.records_by_type.solve}
- </span>
- </div>
- <div className="flex items-center justify-between text-xs">
- <span className="flex items-center gap-1.5 text-white/80">
- <FileText className="w-3 h-3" /> {t("Question")}
- </span>
- <span className="font-medium">
- {notebookStats.records_by_type.question}
- </span>
- </div>
- <div className="flex items-center justify-between text-xs">
- <span className="flex items-center gap-1.5 text-white/80">
- <Microscope className="w-3 h-3" /> {t("Research")}
- </span>
- <span className="font-medium">
- {notebookStats.records_by_type.research}
- </span>
- </div>
- <div className="flex items-center justify-between text-xs">
- <span className="flex items-center gap-1.5 text-white/80">
- <PenTool className="w-3 h-3" /> {t("Co-Writer")}
- </span>
- <span className="font-medium">
- {notebookStats.records_by_type.co_writer}
- </span>
- </div>
- </div>
-
- {/* Recent notebooks */}
- {notebookStats.recent_notebooks.length > 0 && (
- <div className="mt-4 pt-4 border-t border-white/20">
- <div className="text-xs text-white/60 mb-2">Recent</div>
- <div className="space-y-2">
- {notebookStats.recent_notebooks.slice(0, 3).map((nb) => (
- <Link
- key={nb.id}
- href="/notebook"
- className="flex items-center gap-2 p-2 bg-white/10 rounded-lg hover:bg-white/20 transition-colors"
- >
- <div
- className="w-6 h-6 rounded flex items-center justify-center"
- style={{ backgroundColor: nb.color }}
+ <div className="flex-1 space-y-3">
+ <div className="bg-white dark:bg-slate-800 px-5 py-4 rounded-2xl rounded-tl-none border border-slate-200 dark:border-slate-700 shadow-sm">
+ <div className="prose prose-slate dark:prose-invert prose-sm max-w-none">
+ <ReactMarkdown
+ remarkPlugins={[remarkMath]}
+ rehypePlugins={[rehypeKatex]}
>
- <BookOpen className="w-3 h-3 text-white" />
+ {processLatexContent(msg.content)}
+ </ReactMarkdown>
+ </div>
+
+ {/* Loading indicator */}
+ {msg.isStreaming && (
+ <div className="flex items-center gap-2 mt-3 text-blue-600 dark:text-blue-400 text-sm">
+ <Loader2 className="w-4 h-4 animate-spin" />
+ <span>{t("Generating response...")}</span>
</div>
- <div className="flex-1 min-w-0">
- <div className="text-sm font-medium truncate">
- {nb.name}
- </div>
- <div className="text-[10px] text-white/60">
- {nb.record_count} records
- </div>
+ )}
+ </div>
+
+ {/* Sources */}
+ {msg.sources &&
+ ((msg.sources.rag?.length ?? 0) + (msg.sources.web?.length ?? 0)) >
+ 0 && (
+ <div className="flex flex-wrap gap-2">
+ {msg.sources.rag?.map((source, i) => (
+ <div
+ key={`rag-${i}`}
+ className="flex items-center gap-1.5 px-2.5 py-1 bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-lg text-xs"
+ >
+ <BookOpen className="w-3 h-3" />
+ <span>{source.kb_name}</span>
+ </div>
+ ))}
+ {msg.sources.web?.slice(0, 3).map((source, i) => (
+ <a
+ key={`web-${i}`}
+ href={source.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-1.5 px-2.5 py-1 bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 rounded-lg text-xs hover:bg-emerald-100 dark:hover:bg-emerald-900/50 transition-colors"
+ >
+ <Globe className="w-3 h-3" />
+ <span className="max-w-[150px] truncate">
+ {source.title || source.url}
+ </span>
+ <ExternalLink className="w-3 h-3" />
+ </a>
+ ))}
</div>
- </Link>
- ))}
+ )}
</div>
- </div>
+ </>
)}
- </>
- ) : (
- <div className="text-center py-4">
- <BookOpen className="w-8 h-8 mx-auto mb-2 text-white/40" />
- <p className="text-sm text-white/60">{t("No notebooks yet")}</p>
- <Link
- href="/notebook"
- className="mt-2 inline-flex items-center gap-1 text-xs text-white/80 hover:text-white"
- >
- <Plus className="w-3 h-3" /> {t("Create your first notebook")}
- </Link>
+ </div>
+ ))}
+
+ {/* Status indicator */}
+ {chatState.isLoading && chatState.currentStage && (
+ <div className="flex gap-4 w-full max-w-4xl mx-auto">
+ <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shrink-0">
+ <Loader2 className="w-4 h-4 text-white animate-spin" />
+ </div>
+ <div className="flex-1 bg-slate-100 dark:bg-slate-800 px-4 py-3 rounded-2xl rounded-tl-none">
+ <div className="flex items-center gap-2 text-slate-600 dark:text-slate-300 text-sm">
+ <span className="relative flex h-2 w-2">
+ <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
+ <span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
+ </span>
+ {chatState.currentStage === "rag" &&
+ t("Searching knowledge base...")}
+ {chatState.currentStage === "web" &&
+ t("Searching the web...")}
+ {chatState.currentStage === "generating" &&
+ t("Generating response...")}
+ {!["rag", "web", "generating"].includes(
+ chatState.currentStage,
+ ) && chatState.currentStage}
+ </div>
+ </div>
</div>
)}
- </div>
- {/* System Status */}
- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 p-6">
- <h3 className="font-bold text-slate-900 dark:text-slate-100 mb-4">
- {t("System Status")}
- </h3>
- <SystemStatus />
+ <div ref={chatEndRef} />
</div>
- <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 p-6">
- <h3 className="font-bold text-slate-900 dark:text-slate-100 mb-4">
- {t("Quick Actions")}
- </h3>
- <div className="space-y-3">
- <Link
- href="/solver"
- className="block w-full p-3 rounded-xl bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 font-medium hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors text-sm flex items-center gap-3"
- >
- <div className="p-1.5 bg-white dark:bg-slate-700 rounded-lg shadow-sm">
- <HelpCircle className="w-4 h-4 text-blue-600 dark:text-blue-400" />
- </div>
- {t("Ask a Question")}
- </Link>
- <Link
- href="/question"
- className="block w-full p-3 rounded-xl bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 font-medium hover:bg-purple-100 dark:hover:bg-purple-900/50 transition-colors text-sm flex items-center gap-3"
- >
- <div className="p-1.5 bg-white dark:bg-slate-700 rounded-lg shadow-sm">
- <FileText className="w-4 h-4 text-purple-600 dark:text-purple-400" />
- </div>
- {t("Generate Quiz")}
- </Link>
- <Link
- href="/research"
- className="block w-full p-3 rounded-xl bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 font-medium hover:bg-emerald-100 dark:hover:bg-emerald-900/50 transition-colors text-sm flex items-center gap-3"
+ {/* Input Area - Fixed at bottom */}
+ <div className="border-t border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 px-4 py-4">
+ <div className="max-w-4xl mx-auto relative">
+ <input
+ ref={inputRef}
+ type="text"
+ className="w-full px-5 py-3.5 pr-14 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-500 text-slate-700 dark:text-slate-200"
+ placeholder={t("Type your message...")}
+ value={inputMessage}
+ onChange={(e) => setInputMessage(e.target.value)}
+ onKeyDown={handleKeyDown}
+ disabled={chatState.isLoading}
+ />
+ <button
+ onClick={handleSend}
+ disabled={chatState.isLoading || !inputMessage.trim()}
+ className="absolute right-2 top-2 bottom-2 aspect-square bg-blue-600 text-white rounded-lg flex items-center justify-center hover:bg-blue-700 disabled:opacity-50 disabled:hover:bg-blue-600 transition-all"
>
- <div className="p-1.5 bg-white dark:bg-slate-700 rounded-lg shadow-sm">
- <Search className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
- </div>
- {t("Start Research")}
- </Link>
+ {chatState.isLoading ? (
+ <Loader2 className="w-5 h-5 animate-spin" />
+ ) : (
+ <Send className="w-5 h-5" />
+ )}
+ </button>
</div>
</div>
- </div>
- </div>
-
- {selectedActivity && (
- <ActivityDetail
- activity={selectedActivity}
- onClose={() => setSelectedActivity(null)}
- />
+ </>
)}
</div>
);
diff --git a/web/components/Sidebar.tsx b/web/components/Sidebar.tsx
index 606bc5131..437752c7d 100644
--- a/web/components/Sidebar.tsx
+++ b/web/components/Sidebar.tsx
@@ -4,7 +4,8 @@ import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import {
- LayoutDashboard,
+ Home,
+ History,
BookOpen,
PenTool,
Calculator,
@@ -30,7 +31,8 @@ export default function Sidebar() {
{
name: t("Start"),
items: [
- { name: t("Dashboard"), href: "/", icon: LayoutDashboard },
+ { 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 },
],
diff --git a/web/context/GlobalContext.tsx b/web/context/GlobalContext.tsx
index ec6c7b365..ad4042ec5 100644
--- a/web/context/GlobalContext.tsx
+++ b/web/context/GlobalContext.tsx
@@ -203,6 +203,29 @@ interface IdeaGenState {
progress: { current: number; total: number } | null;
}
+// Chat Types
+interface ChatSource {
+ rag?: Array<{ kb_name: string; content: string }>;
+ web?: Array<{ url: string; title?: string; snippet?: string }>;
+}
+
+interface HomeChatMessage {
+ role: "user" | "assistant";
+ content: string;
+ sources?: ChatSource;
+ isStreaming?: boolean;
+}
+
+interface ChatState {
+ sessionId: string | null;
+ messages: HomeChatMessage[];
+ isLoading: boolean;
+ selectedKb: string;
+ enableRag: boolean;
+ enableWebSearch: boolean;
+ currentStage: string | null;
+}
+
interface GlobalContextType {
// Solver
solverState: SolverState;
@@ -242,6 +265,14 @@ interface GlobalContextType {
ideaGenState: IdeaGenState;
setIdeaGenState: React.Dispatch<React.SetStateAction<IdeaGenState>>;
+ // Chat
+ chatState: ChatState;
+ setChatState: React.Dispatch<React.SetStateAction<ChatState>>;
+ sendChatMessage: (message: string) => void;
+ clearChatHistory: () => void;
+ loadChatSession: (sessionId: string) => Promise<void>;
+ newChatSession: () => void;
+
// UI Settings
uiSettings: { theme: "light" | "dark"; language: "en" | "zh" };
refreshSettings: () => Promise<void>;
@@ -1308,6 +1339,222 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {
progress: null,
});
+ // --- Chat Logic ---
+ const [chatState, setChatState] = useState<ChatState>({
+ sessionId: null,
+ messages: [],
+ isLoading: false,
+ selectedKb: "",
+ enableRag: false,
+ enableWebSearch: false,
+ currentStage: null,
+ });
+ const chatWs = useRef<WebSocket | null>(null);
+
+ const sendChatMessage = (message: string) => {
+ if (!message.trim() || chatState.isLoading) return;
+
+ // Add user message
+ setChatState((prev) => ({
+ ...prev,
+ isLoading: true,
+ currentStage: "connecting",
+ messages: [...prev.messages, { role: "user", content: message }],
+ }));
+
+ // Close existing connection if any
+ if (chatWs.current) {
+ chatWs.current.close();
+ }
+
+ const ws = new WebSocket(wsUrl("/api/v1/chat"));
+ chatWs.current = ws;
+
+ let assistantMessage = "";
+
+ ws.onopen = () => {
+ // Build history from current messages (excluding the one just added)
+ const history = chatState.messages.map((msg) => ({
+ role: msg.role,
+ content: msg.content,
+ }));
+
+ ws.send(
+ JSON.stringify({
+ message,
+ session_id: chatState.sessionId,
+ history,
+ kb_name: chatState.selectedKb,
+ enable_rag: chatState.enableRag,
+ enable_web_search: chatState.enableWebSearch,
+ }),
+ );
+ };
+
+ ws.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+
+ if (data.type === "session") {
+ // Store session ID from backend
+ setChatState((prev) => ({
+ ...prev,
+ sessionId: data.session_id,
+ }));
+ } else if (data.type === "status") {
+ setChatState((prev) => ({
+ ...prev,
+ currentStage: data.stage || data.message,
+ }));
+ } else if (data.type === "stream") {
+ assistantMessage += data.content;
+ setChatState((prev) => {
+ const messages = [...prev.messages];
+ const lastMessage = messages[messages.length - 1];
+ if (lastMessage?.role === "assistant" && lastMessage?.isStreaming) {
+ // Update existing streaming message
+ messages[messages.length - 1] = {
+ ...lastMessage,
+ content: assistantMessage,
+ };
+ } else {
+ // Add new streaming message
+ messages.push({
+ role: "assistant",
+ content: assistantMessage,
+ isStreaming: true,
+ });
+ }
+ return { ...prev, messages, currentStage: "generating" };
+ });
+ } else if (data.type === "sources") {
+ setChatState((prev) => {
+ const messages = [...prev.messages];
+ const lastMessage = messages[messages.length - 1];
+ if (lastMessage?.role === "assistant") {
+ messages[messages.length - 1] = {
+ ...lastMessage,
+ sources: { rag: data.rag, web: data.web },
+ };
+ }
+ return { ...prev, messages };
+ });
+ } else if (data.type === "result") {
+ setChatState((prev) => {
+ const messages = [...prev.messages];
+ const lastMessage = messages[messages.length - 1];
+ if (lastMessage?.role === "assistant") {
+ messages[messages.length - 1] = {
+ ...lastMessage,
+ content: data.content,
+ isStreaming: false,
+ };
+ }
+ return {
+ ...prev,
+ messages,
+ isLoading: false,
+ currentStage: null,
+ };
+ });
+ ws.close();
+ } else if (data.type === "error") {
+ setChatState((prev) => ({
+ ...prev,
+ isLoading: false,
+ currentStage: null,
+ messages: [
+ ...prev.messages,
+ { role: "assistant", content: `Error: ${data.message}` },
+ ],
+ }));
+ ws.close();
+ }
+ };
+
+ ws.onerror = () => {
+ setChatState((prev) => ({
+ ...prev,
+ isLoading: false,
+ currentStage: null,
+ messages: [
+ ...prev.messages,
+ { role: "assistant", content: "Connection error. Please try again." },
+ ],
+ }));
+ };
+
+ ws.onclose = () => {
+ if (chatWs.current === ws) {
+ chatWs.current = null;
+ }
+ setChatState((prev) => ({
+ ...prev,
+ isLoading: false,
+ currentStage: null,
+ }));
+ };
+ };
+
+ const clearChatHistory = () => {
+ setChatState((prev) => ({
+ ...prev,
+ sessionId: null,
+ messages: [],
+ currentStage: null,
+ }));
+ };
+
+ const newChatSession = () => {
+ // Close any existing WebSocket
+ if (chatWs.current) {
+ chatWs.current.close();
+ chatWs.current = null;
+ }
+ // Reset to new session
+ setChatState((prev) => ({
+ ...prev,
+ sessionId: null,
+ messages: [],
+ isLoading: false,
+ currentStage: null,
+ }));
+ };
+
+ const loadChatSession = async (sessionId: string) => {
+ try {
+ const response = await fetch(apiUrl(`/api/v1/chat/sessions/${sessionId}`));
+ if (!response.ok) {
+ throw new Error("Session not found");
+ }
+ const session = await response.json();
+
+ // Convert session messages to HomeChatMessage format
+ const messages: HomeChatMessage[] = session.messages.map((msg: any) => ({
+ role: msg.role,
+ content: msg.content,
+ sources: msg.sources,
+ isStreaming: false,
+ }));
+
+ // Restore session settings
+ const settings = session.settings || {};
+
+ setChatState((prev) => ({
+ ...prev,
+ sessionId: session.session_id,
+ messages,
+ selectedKb: settings.kb_name || prev.selectedKb,
+ enableRag: settings.enable_rag ?? prev.enableRag,
+ enableWebSearch: settings.enable_web_search ?? prev.enableWebSearch,
+ isLoading: false,
+ currentStage: null,
+ }));
+ } catch (error) {
+ console.error("Failed to load session:", error);
+ throw error;
+ }
+ };
+
return (
<GlobalContext.Provider
value={{
@@ -1324,6 +1571,12 @@ export function GlobalProvider({ children }: { children: React.ReactNode }) {
startResearch,
ideaGenState,
setIdeaGenState,
+ chatState,
+ setChatState,
+ sendChatMessage,
+ clearChatHistory,
+ loadChatSession,
+ newChatSession,
uiSettings,
refreshSettings,
}}
diff --git a/web/lib/i18n.ts b/web/lib/i18n.ts
index 923e38312..78faf8c65 100644
--- a/web/lib/i18n.ts
+++ b/web/lib/i18n.ts
@@ -99,6 +99,41 @@ export const translations = {
"Ask a Question": "Ask a Question",
"Generate Quiz": "Generate Quiz",
"Start Research": "Start Research",
+
+ // Home Page
+ Home: "Home",
+ History: "History",
+ "Welcome to DeepTutor": "Welcome to DeepTutor",
+ "How can I help you today?": "How can I help you today?",
+ "Ask anything...": "Ask anything...",
+ "Type your message...": "Type your message...",
+ RAG: "RAG",
+ "Web Search": "Web Search",
+ "Select Knowledge Base": "Select Knowledge Base",
+ "Quick Actions": "Quick Actions",
+ "Explore Modules": "Explore Modules",
+ "Smart Problem Solving": "Smart Problem Solving",
+ "Generate Practice Questions": "Generate Practice Questions",
+ "Deep Research Reports": "Deep Research Reports",
+ "Generate Novel Ideas": "Generate Novel Ideas",
+ "Searching knowledge base...": "Searching knowledge base...",
+ "Searching the web...": "Searching the web...",
+ "Generating response...": "Generating response...",
+ "Clear Chat": "Clear Chat",
+ Sources: "Sources",
+ "From Knowledge Base": "From Knowledge Base",
+ "From Web": "From Web",
+ "New Chat": "New Chat",
+
+ // History Page
+ "Chat History": "Chat History",
+ "All Activities": "All Activities",
+ "Filter by type": "Filter by type",
+ All: "All",
+ Chat: "Chat",
+ "No history found": "No history found",
+ "Your activities will appear here": "Your activities will appear here",
+ Continue: "Continue",
},
zh: {
// Sidebar
@@ -194,6 +229,41 @@ export const translations = {
"Ask a Question": "提问问题",
"Generate Quiz": "生成测验",
"Start Research": "开始研究",
+
+ // Home Page
+ Home: "首页",
+ History: "历史记录",
+ "Welcome to DeepTutor": "欢迎使用 DeepTutor",
+ "How can I help you today?": "今天我能帮您什么?",
+ "Ask anything...": "问我任何问题...",
+ "Type your message...": "输入您的消息...",
+ RAG: "知识库检索",
+ "Web Search": "网络搜索",
+ "Select Knowledge Base": "选择知识库",
+ "Quick Actions": "快捷操作",
+ "Explore Modules": "探索模块",
+ "Smart Problem Solving": "智能问题解答",
+ "Generate Practice Questions": "生成练习题",
+ "Deep Research Reports": "深度研究报告",
+ "Generate Novel Ideas": "生成创新想法",
+ "Searching knowledge base...": "正在搜索知识库...",
+ "Searching the web...": "正在搜索网络...",
+ "Generating response...": "正在生成回复...",
+ "Clear Chat": "清空对话",
+ Sources: "来源",
+ "From Knowledge Base": "来自知识库",
+ "From Web": "来自网络",
+ "New Chat": "新对话",
+
+ // History Page
+ "Chat History": "聊天历史",
+ "All Activities": "所有活动",
+ "Filter by type": "按类型筛选",
+ All: "全部",
+ Chat: "聊天",
+ "No history found": "未找到历史记录",
+ "Your activities will appear here": "您的活动将显示在这里",
+ Continue: "继续对话",
},
};