DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: implement flexible RAG plugin system with UI
Tushar Khatribf21580e6c16
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.pyindex 268478709..328285927 100644--- a/src/api/routers/settings.py+++ b/src/api/routers/settings.py@@ -87,6 +87,14 @@ ENV_VAR_DEFINITIONS = {"default": "","sensitive": True,},+ # RAG Configuration+ "RAG_PROVIDER": {+ "description": "RAG provider to use (lightrag, chromadb, pinecone, etc.)",+ "category": "rag",+ "required": False,+ "default": "lightrag",+ "sensitive": False,+ },# TTS Configuration (OpenAI compatible API)"TTS_MODEL": {"description": "OpenAI TTS model (tts-1 for speed, tts-1-hd for quality)",@@ -153,6 +161,11 @@ ENV_CATEGORIES = {"description": "Text embedding model settings for semantic search and RAG","icon": "database",},+ "rag": {+ "name": "RAG Configuration",+ "description": "Retrieval-Augmented Generation provider settings",+ "icon": "search",+ },"tts": {"name": "TTS Configuration","description": "Text-to-Speech settings. Currently only supports Alibaba Cloud DashScope.",@@ -589,3 +602,31 @@ async def test_env_config():results["tts"]["error"] = str(e)return results+++# ==================== RAG Provider Configuration ====================++[email protected]("/rag/providers")+async def get_rag_providers():+ """+ Get list of available RAG providers.++ Returns:+ {+ "providers": [...],+ "current": "lightrag"+ }+ """+ try:+ from src.tools.rag_tool import get_available_providers, get_current_provider++ providers = get_available_providers()+ current = get_current_provider()++ return {+ "providers": providers,+ "current": current+ }+ except Exception as e:+ raise HTTPException(status_code=500, detail=f"Failed to get RAG providers: {str(e)}")diff --git a/src/rag/README.md b/src/rag/README.mdnew file mode 100644index 000000000..65faf686a--- /dev/null+++ b/src/rag/README.md@@ -0,0 +1,265 @@+# 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__.pynew file mode 100644index 000000000..250a0972c--- /dev/null+++ b/src/rag/__init__.py@@ -0,0 +1,4 @@+"""+RAG Plugin System+Provides flexible, pluggable RAG implementations+"""diff --git a/src/rag/plugin_loader.py b/src/rag/plugin_loader.pynew file mode 100644index 000000000..717074fae--- /dev/null+++ b/src/rag/plugin_loader.py@@ -0,0 +1,163 @@+"""+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__.pynew file mode 100644index 000000000..9f530a310--- /dev/null+++ b/src/rag/plugins/__init__.py@@ -0,0 +1,4 @@+"""+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.pynew file mode 100644index 000000000..8319d6658--- /dev/null+++ b/src/rag/plugins/_template.py@@ -0,0 +1,82 @@+"""+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.pynew file mode 100644index 000000000..b2aec05b0--- /dev/null+++ b/src/rag/plugins/lightrag.py@@ -0,0 +1,210 @@+"""+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")++ # Use KnowledgeBaseManager to get RAG storage path+ kb_manager = KnowledgeBaseManager(kb_base_dir)++ try:+ working_dir = str(kb_manager.get_rag_storage_path(kb_name))+ except ValueError as e:+ # If rag_storage doesn't exist, try using traditional path+ if "RAG storage not found" in str(e):+ if kb_name:+ kb_dir = Path(kb_base_dir) / kb_name+ else:+ kb_dir = Path(kb_base_dir) / kb_manager.get_default()+ working_dir = str(kb_dir / "rag_storage")++ # If still doesn't exist, provide friendly message+ if not Path(working_dir).exists():+ raise ValueError(+ "RAG storage not initialized. "+ "Please initialize the knowledge base first."+ )+ else:+ raise++ 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") -> Dict:+ """+ Search using LightRAG.++ Args:+ query: Search query+ kb_name: Knowledge base name+ mode: Search mode (hybrid, local, global, naive)++ 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)+ 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/tools/rag_tool.py b/src/tools/rag_tool.pyindex 98250e8b1..eea6bedf9 100644--- a/src/tools/rag_tool.py+++ b/src/tools/rag_tool.py@@ -1,243 +1,177 @@#!/usr/bin/env python"""-RAG Query Tool - Wrapper for RAG query functionality+RAG Query Tool - Plugin-based RAG system+Supports multiple RAG implementations through a simple plugin system"""import asyncio+import osfrom pathlib import Path-import sys--# Add parent directory to path (insert at front to prioritize project modules)-project_root = Path(__file__).parent.parent.parent-# Add raganything module path-raganything_path = project_root.parent / "raganything" / "RAG-Anything"-if raganything_path.exists():- sys.path.insert(0, str(raganything_path))+from typing import Dict, Listfrom dotenv import load_dotenv-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# Load environment variables+project_root = Path(__file__).parent.parent.parentload_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+++# Default RAG provider (can be overridden via environment variable)+DEFAULT_RAG_PROVIDER = os.getenv("RAG_PROVIDER", "lightrag")+async def rag_search(query: str,kb_name: str | None = None,mode: str = "hybrid",- api_key: str | None = None,- base_url: str | None = None,- kb_base_dir: str | None = None,+ provider: str | None = None,**kwargs,) -> dict:"""- Query knowledge base using RAG+ Query knowledge base using configurable RAG provider.Args:query: Query questionkb_name: Knowledge base name (optional, defaults to default knowledge base)- mode: Query mode, options: "local", "global", "hybrid", "naive" (default: "hybrid")- api_key: LLM API key (optional, defaults to reading from environment variables)- base_url: LLM API Base URL (optional, defaults to reading from environment variables)- kb_base_dir: Knowledge base base directory (default: "./knowledge_bases")- **kwargs: Other query parameters (e.g., only_need_context, only_need_prompt, etc.)+ 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 providerReturns:dict: Dictionary containing query results{"query": str,"answer": str,- "mode": str+ "content": str,+ "mode": str,+ "provider": str}++ Raises:+ ValueError: If the specified RAG provider is not found+ Exception: If the query fails++ Example:+ # Use default provider (from .env)+ 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")"""- # Get LLM configuration- try:- llm_config = get_llm_config()- except ValueError as e:- raise ValueError(f"LLM configuration error: {e!s}")-- # Get Embedding configuration- try:- embedding_config = get_embedding_config()- except ValueError as e:- raise ValueError(f"Embedding configuration error: {e!s}")-- # Override configuration with provided parameters (if provided)- llm_api_key = api_key or llm_config["api_key"]- llm_base_url = base_url or llm_config["base_url"]- llm_model = llm_config["model"]-- embedding_api_key = embedding_config["api_key"]- embedding_base_url = embedding_config["base_url"]- embedding_model = embedding_config["model"]- embedding_dim = embedding_config["dim"]- embedding_max_tokens = embedding_config["max_tokens"]-- # If knowledge base path not specified, try to get from config- if kb_base_dir is None:- try:- from src.core.core import get_path_from_config, load_config_with_main-- project_root = Path(__file__).parent.parent.parent- # Try loading from solve_config (most common)- config = load_config_with_main("solve_config.yaml", project_root)- kb_base_dir = get_path_from_config(config, "knowledge_bases_dir") or config.get(- "tools", {}- ).get("rag_tool", {}).get("kb_base_dir")- if kb_base_dir:- kb_base_dir = str(kb_base_dir)- except Exception:- pass-- # Fallback to default path- if kb_base_dir is None:- project_root = Path(__file__).parent.parent.parent- kb_base_dir = str(project_root / "data" / "knowledge_bases")-- # Use KnowledgeBaseManager to get RAG storage path+ # 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()]+ raise ValueError(+ f"RAG provider '{provider_name}' not found. "+ f"Available providers: {available}. "+ f"Set RAG_PROVIDER in .env or pass provider parameter."+ )++ # Get the plugin+ plugin = get_plugin(provider_name)++ # Execute search using the plugintry:- kb_manager = KnowledgeBaseManager(kb_base_dir)- working_dir = str(kb_manager.get_rag_storage_path(kb_name))- except ValueError as e:- # If rag_storage doesn't exist, try using traditional path- if "RAG storage not found" in str(e):- if kb_name:- kb_dir = Path(kb_base_dir) / kb_name- else:- kb_dir = Path(kb_base_dir) / kb_manager.get_default()- working_dir = str(kb_dir / "rag_storage")- # If still doesn't exist, provide friendly message- if not Path(working_dir).exists():- raise ValueError(- "Error: Knowledge base RAG storage not initialized\nHint: Please run init_knowledge_base.py to initialize the knowledge base"- )- else:- raise ValueError(f"Error: {e!s}")+ result = await plugin["search"](+ query=query,+ kb_name=kb_name,+ mode=mode,+ **kwargs+ )++ # Ensure consistent return format+ if "query" not in result:+ result["query"] = query+ if "answer" not in result and "content" in result:+ result["answer"] = result["content"]+ if "content" not in result and "answer" in result:+ result["content"] = result["answer"]++ return result+except Exception as e:- raise Exception(f"Error: Unable to access knowledge base - {e!s}")+ raise Exception(f"RAG search failed with provider '{provider_name}': {e}")- # Define LLM function- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):- return openai_complete_if_cache(- llm_model,- prompt,- system_prompt=system_prompt,- history_messages=history_messages,- api_key=llm_api_key,- base_url=llm_base_url,- **kwargs,- )- def vision_model_func(- prompt,- system_prompt=None,- history_messages=[],- image_data=None,- messages=None,- **kwargs,- ):- # If messages format is provided (for multimodal VLM enhanced query), use it directly- if messages:- # Remove 'messages' and other message-related params from kwargs to avoid duplicate parameter- 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_model,- prompt="", # Empty prompt when using messages- system_prompt=None,- history_messages=[],- messages=messages,- api_key=llm_api_key,- base_url=llm_base_url,- **clean_kwargs,- )- # Traditional single image format- if image_data:- # Remove message-related params from kwargs to avoid duplicate parameter- 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_model,- prompt="", # Empty prompt when using messages- system_prompt=None,- history_messages=[],- messages=[- {"role": "system", "content": system_prompt} if system_prompt else None,- (- {- "role": "user",- "content": [- {"type": "text", "text": prompt},- {- "type": "image_url",- "image_url": {"url": f"data:image/jpeg;base64,{image_data}"},- },- ],- }- if image_data- else {"role": "user", "content": prompt}- ),- ],- api_key=llm_api_key,- base_url=llm_base_url,- **clean_kwargs,- )- # Pure text format- return llm_model_func(prompt, system_prompt, history_messages, **kwargs)+async def initialize_rag(+ kb_name: str,+ documents: List[str],+ provider: str | None = 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)++ Returns:+ True if successful++ Example:+ documents = ["Document 1 content", "Document 2 content"]+ 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")++ plugin = get_plugin(provider_name)+ return await plugin["initialize"](kb_name=kb_name, documents=documents)- # Define embedding function- embedding_func = EmbeddingFunc(- embedding_dim=embedding_dim,- max_token_size=embedding_max_tokens,- func=lambda texts: openai_embed(- texts,- model=embedding_model,- api_key=embedding_api_key,- base_url=embedding_base_url,- ),- )- # Create RAG instance- config = RAGAnythingConfig(- working_dir=working_dir,- enable_image_processing=True,- enable_table_processing=True,- enable_equation_processing=True,- )+async def delete_rag(kb_name: str, provider: str | None = None) -> bool:+ """+ Delete a knowledge base.++ Args:+ kb_name: Knowledge base name+ provider: RAG provider to use (defaults to RAG_PROVIDER env var)++ Returns:+ True if successful++ Example:+ success = await delete_rag("old_kb")+ """+ provider_name = provider or DEFAULT_RAG_PROVIDER++ if not has_plugin(provider_name):+ raise ValueError(f"RAG provider '{provider_name}' not found")++ plugin = get_plugin(provider_name)+ return await plugin["delete"](kb_name=kb_name)- # Use log forwarding context manager- with LightRAGLogContext(scene="rag_tool"):- rag = RAGAnything(- config=config,- llm_model_func=llm_model_func,- # vision_model_func=vision_model_func,- embedding_func=embedding_func,- )- # Ensure initialization- await rag._ensure_lightrag_initialized()+def get_available_providers() -> List[Dict]:+ """+ Get list of available RAG providers.++ Returns:+ List of provider information dictionaries++ Example:+ providers = get_available_providers()+ for p in providers:+ print(f"{p['name']}: {p['description']}")+ """+ return list_plugins()- # Execute query- try:- answer = await rag.aquery(query, mode=mode, **kwargs)- answer_str = answer if isinstance(answer, str) else str(answer)- return {"query": query, "answer": answer_str, "mode": mode}- except Exception as e:- raise Exception(f"Query failed: {e!s}")+def get_current_provider() -> str:+ """Get the currently configured RAG provider"""+ return DEFAULT_RAG_PROVIDERif __name__ == "__main__":@@ -245,18 +179,23 @@ if __name__ == "__main__":if sys.platform == "win32":import io-sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")- # Test+ # List available providers+ print("Available RAG Providers:")+ for provider in get_available_providers():+ print(f" - {provider['id']}: {provider['description']}")+ print(f"\nCurrent provider: {get_current_provider()}\n")++ # Test searchresult = asyncio.run(rag_search("What is the lookup table (LUT) in FPGA?",kb_name="DE-all",mode="naive",- only_need_context=False,))print(f"Query: {result['query']}")print(f"Answer: {result['answer']}")+ print(f"Provider: {result.get('provider', 'unknown')}")diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsxindex b85cb785a..47f215218 100644--- a/web/app/settings/page.tsx+++ b/web/app/settings/page.tsx@@ -224,10 +224,21 @@ export default function SettingsPage() {string | null>(null);+ // RAG providers state+ const [ragProviders, setRagProviders] = useState<Array<{+ id: string;+ name: string;+ description: string;+ supported_modes: string[];+ }>>([]);+ const [currentRagProvider, setCurrentRagProvider] = useState<string>("lightrag");+ const [loadingRagProviders, setLoadingRagProviders] = useState(false);+useEffect(() => {fetchSettings();fetchSettings();fetchEnvConfig();+ fetchRagProviders();if (activeTab === "llm_providers") {fetchProviders();}@@ -248,6 +259,22 @@ export default function SettingsPage() {}};+ const fetchRagProviders = async () => {+ setLoadingRagProviders(true);+ try {+ const res = await fetch(apiUrl("/api/v1/settings/rag/providers"));+ if (res.ok) {+ const data = await res.json();+ setRagProviders(data.providers || []);+ setCurrentRagProvider(data.current || "lightrag");+ }+ } catch (err) {+ console.error("Failed to fetch RAG providers:", err);+ } finally {+ setLoadingRagProviders(false);+ }+ };+const fetchModels = async () => {if (!editingProvider || !editingProvider.base_url) return;setFetchingModels(true);@@ -815,7 +842,66 @@ export default function SettingsPage() {</div></section>- {/* 2. System Configuration */}+ {/* 2. RAG Provider Configuration */}+ <section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200">+ <div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">+ <Database className="w-4 h-4 text-slate-500 dark:text-slate-400" />+ <h2 className="font-semibold text-slate-900 dark:text-slate-100">+ {t("RAG Provider")}+ </h2>+ </div>+ <div className="p-6">+ <div>+ <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">+ {t("Active RAG System")}+ </label>+ <p className="text-xs text-slate-400 dark:text-slate-500 mb-3">+ {t("Choose the Retrieval-Augmented Generation system for knowledge base queries")}+ </p>+ {loadingRagProviders ? (+ <div className="flex items-center gap-2 text-sm text-slate-500">+ <Loader2 className="w-4 h-4 animate-spin" />+ <span>Loading providers...</span>+ </div>+ ) : (+ <div className="space-y-3">+ <select+ value={currentRagProvider}+ onChange={(e) => {+ const newProvider = e.target.value;+ setCurrentRagProvider(newProvider);+ // Update environment variable+ setEditedEnvVars(prev => ({+ ...prev,+ RAG_PROVIDER: newProvider+ }));+ }}+ className="w-full md:w-2/3 p-2.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-xl text-sm text-slate-900 dark:text-slate-100 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"+ >+ {ragProviders.map((provider) => (+ <option key={provider.id} value={provider.id}>+ {provider.name} - {provider.description}+ </option>+ ))}+ </select>+ {ragProviders.length > 0 && (+ <div className="text-xs text-slate-500 dark:text-slate-400 bg-slate-50 dark:bg-slate-700/50 p-3 rounded-lg">+ {ragProviders.find(p => p.id === currentRagProvider)?.description || ""}+ {ragProviders.find(p => p.id === currentRagProvider)?.supported_modes && (+ <div className="mt-2">+ <span className="font-medium">Supported modes:</span>{" "}+ {ragProviders.find(p => p.id === currentRagProvider)?.supported_modes.join(", ")}+ </div>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ </section>++ {/* 3. System Configuration */}<section className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden transition-colors duration-200"><div className="p-4 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2"><Server className="w-4 h-4 text-slate-500 dark:text-slate-400" />