~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: add RAG indexing and library search engine
LearningCircuit6d4855cc2f24
diff --git a/src/local_deep_research/database/models/__init__.py b/src/local_deep_research/database/models/__init__.pyindex 873826fd72..06bc9d2709 100644--- a/src/local_deep_research/database/models/__init__.py+++ b/src/local_deep_research/database/models/__init__.py@@ -50,12 +50,14 @@ from .news import (# Import Library modelsfrom .library import (+ DocumentChunk,LibraryDocument,LibraryCollection,LibraryCollectionDocument,LibraryDownloadQueue,LibraryStatistics,LibraryTextDocument,+ RAGIndex,)from .download_tracker import (DownloadTracker,@@ -130,12 +132,14 @@ __all__ = ["SubscriptionType","SubscriptionStatus",# Library Models+ "DocumentChunk","LibraryDocument","LibraryCollection","LibraryCollectionDocument","LibraryDownloadQueue","LibraryStatistics","LibraryTextDocument",+ "RAGIndex",# Download Tracker Models"DownloadTracker","DownloadDuplicates",diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.pyindex ada0e3807d..5e5cc5d2b8 100644--- a/src/local_deep_research/database/models/library.py+++ b/src/local_deep_research/database/models/library.py@@ -192,6 +192,15 @@ class LibraryTextDocument(Base):Text, nullable=True) # Always store text content for quick access+ # RAG/Search indexing+ rag_indexed = Column(+ Boolean, default=False+ ) # Whether this document has been indexed for RAG+ chunk_count = Column(Integer, default=0) # Number of chunks created+ last_indexed_at = Column(+ UtcDateTime, nullable=True+ ) # Last time RAG index was updated+# Timestampscreated_at = Column(UtcDateTime, default=utcnow(), nullable=False)updated_at = Column(@@ -220,6 +229,75 @@ class LibraryTextDocument(Base):return f"<LibraryTextDocument(title='{self.title[:50] if self.title else 'Untitled'}', method={self.extraction_method}, size={self.file_size})>"+class DocumentChunk(Base):+ """+ Universal chunk storage for RAG across all sources.+ Stores text chunks in encrypted database for semantic search.+ """++ __tablename__ = "document_chunks"++ id = Column(Integer, primary_key=True, autoincrement=True)++ # Chunk identification+ chunk_hash = Column(+ String(64), nullable=False, unique=True, index=True+ ) # SHA256 for deduplication++ # Source tracking+ source_type = Column(+ String(20), nullable=False, index=True+ ) # 'library', 'local_file'+ source_id = Column(+ Integer, nullable=True+ ) # LibraryTextDocument.id if library source+ source_path = Column(+ Text, nullable=True+ ) # File path if local collection source+ collection_name = Column(+ String(100), nullable=False, index=True+ ) # 'library', 'personal_notes', 'project_docs', etc.++ # Chunk content (encrypted in SQLCipher DB)+ chunk_text = Column(Text, nullable=False) # The actual chunk text+ chunk_index = Column(Integer, nullable=False) # Position in source document+ start_char = Column(Integer, nullable=False) # Start character position+ end_char = Column(Integer, nullable=False) # End character position+ word_count = Column(Integer, nullable=False) # Number of words in chunk++ # Embedding metadata+ embedding_id = Column(+ String(36), nullable=False, unique=True, index=True+ ) # UUID for FAISS vector mapping+ embedding_model = Column(+ String(100), nullable=False+ ) # e.g., 'all-MiniLM-L6-v2'+ embedding_model_type = Column(+ String(50), nullable=False+ ) # 'sentence_transformers', 'ollama'+ embedding_dimension = Column(Integer, nullable=True) # Vector dimension++ # Document metadata (for context)+ document_title = Column(Text, nullable=True) # Title of source document+ document_metadata = Column(+ JSON, nullable=True+ ) # Additional metadata from source++ # Timestamps+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)+ last_accessed = Column(UtcDateTime, nullable=True)++ # Indexes for efficient queries+ __table_args__ = (+ Index("idx_chunk_source", "source_type", "source_id"),+ Index("idx_chunk_collection", "collection_name", "created_at"),+ Index("idx_chunk_embedding", "embedding_id"),+ )++ def __repr__(self):+ return f"<DocumentChunk(collection='{self.collection_name}', source_type='{self.source_type}', index={self.chunk_index}, words={self.word_count})>"++class LibraryCollection(Base):"""User-defined collections for organizing documents.@@ -362,3 +440,71 @@ class LibraryStatistics(Base):def __repr__(self):return f"<LibraryStatistics(documents={self.total_documents}, size={self.total_size_bytes})>"+++class RAGIndex(Base):+ """+ Tracks FAISS indices for RAG collections.+ Each collection+embedding_model combination has its own FAISS index.+ """++ __tablename__ = "rag_indices"++ id = Column(Integer, primary_key=True, autoincrement=True)++ # Collection and model identification+ collection_name = Column(+ String(100), nullable=False, index=True+ ) # 'library', 'personal_notes', etc.+ embedding_model = Column(+ String(100), nullable=False+ ) # e.g., 'all-MiniLM-L6-v2'+ embedding_model_type = Column(+ String(50), nullable=False+ ) # 'sentence_transformers', 'ollama'+ embedding_dimension = Column(Integer, nullable=False) # Vector dimension++ # Index file location+ index_path = Column(Text, nullable=False) # Path to .faiss file+ index_hash = Column(+ String(64), nullable=False, unique=True, index=True+ ) # SHA256 of collection+model for uniqueness++ # Chunking parameters used+ chunk_size = Column(Integer, nullable=False)+ chunk_overlap = Column(Integer, nullable=False)++ # Index statistics+ chunk_count = Column(Integer, default=0) # Number of chunks in this index+ total_documents = Column(Integer, default=0) # Number of source documents++ # Status+ status = Column(+ String(50), nullable=False, default="active"+ ) # active, rebuilding, deprecated+ is_current = Column(+ Boolean, default=True+ ) # Whether this is the current index for this collection++ # Timestamps+ created_at = Column(UtcDateTime, default=utcnow(), nullable=False)+ last_updated_at = Column(+ UtcDateTime, default=utcnow(), onupdate=utcnow(), nullable=False+ )+ last_used_at = Column(+ UtcDateTime, nullable=True+ ) # Last time index was searched++ # Ensure one active index per collection+model+ __table_args__ = (+ UniqueConstraint(+ "collection_name",+ "embedding_model",+ "embedding_model_type",+ name="uix_collection_model",+ ),+ Index("idx_collection_current", "collection_name", "is_current"),+ )++ def __repr__(self):+ return f"<RAGIndex(collection='{self.collection_name}', model='{self.embedding_model}', chunks={self.chunk_count})>"diff --git a/src/local_deep_research/research_library/__init__.py b/src/local_deep_research/research_library/__init__.pyindex bebd6803f4..031a06d589 100644--- a/src/local_deep_research/research_library/__init__.py+++ b/src/local_deep_research/research_library/__init__.py@@ -10,6 +10,14 @@ This module provides functionality for:from .services.download_service import DownloadServicefrom .services.library_service import LibraryService+from .services.library_rag_service import LibraryRAGServicefrom .routes.library_routes import library_bp+from .routes.rag_routes import rag_bp-__all__ = ["DownloadService", "LibraryService", "library_bp"]+__all__ = [+ "DownloadService",+ "LibraryService",+ "LibraryRAGService",+ "library_bp",+ "rag_bp",+]diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pynew file mode 100644index 0000000000..ac86b22de0--- /dev/null+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -0,0 +1,258 @@+"""+RAG Management API Routes++Provides endpoints for managing RAG indexing of library documents:+- Configure embedding models+- Index documents+- Get RAG statistics+- Bulk operations with progress tracking+"""++from flask import Blueprint, jsonify, request, Response, render_template+from flask_login import current_user+from loguru import logger+import json++from ...web.auth.decorators import login_required+from ...utilities.db_utils import get_settings_manager+from ..services.library_rag_service import LibraryRAGService++rag_bp = Blueprint("rag", __name__, url_prefix="/library")+++def get_rag_service() -> LibraryRAGService:+ """Get RAG service instance with current user's settings."""+ settings = get_settings_manager()++ # Get embedding configuration from settings or use defaults+ embedding_model = settings.get_setting(+ "local_search_embedding_model", "all-MiniLM-L6-v2"+ )+ embedding_provider = settings.get_setting(+ "local_search_embedding_provider", "sentence_transformers"+ )+ chunk_size = settings.get_setting("local_search_chunk_size", 1000)+ chunk_overlap = settings.get_setting("local_search_chunk_overlap", 200)++ return LibraryRAGService(+ username=current_user.username,+ embedding_model=embedding_model,+ embedding_provider=embedding_provider,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ )+++# Page Routes+++@rag_bp.route("/rag-manager")+@login_required+def rag_manager_page():+ """Render the RAG Manager page."""+ return render_template("pages/rag_manager.html")+++# API Routes+++@rag_bp.route("/api/rag/models", methods=["GET"])+@login_required+def get_available_models():+ """Get list of available embedding models."""+ try:+ rag_service = get_rag_service()+ models = rag_service.get_available_models()++ return jsonify({"success": True, "models": models})+ except Exception as e:+ logger.exception("Error getting available models")+ return jsonify({"success": False, "error": str(e)}), 500+++@rag_bp.route("/api/rag/info", methods=["GET"])+@login_required+def get_index_info():+ """Get information about the current RAG index."""+ try:+ rag_service = get_rag_service()+ info = rag_service.get_current_index_info()++ if info is None:+ return jsonify(+ {"success": True, "info": None, "message": "No index found"}+ )++ return jsonify({"success": True, "info": info})+ except Exception as e:+ logger.exception("Error getting index info")+ return jsonify({"success": False, "error": str(e)}), 500+++@rag_bp.route("/api/rag/stats", methods=["GET"])+@login_required+def get_rag_stats():+ """Get RAG statistics for the library."""+ try:+ rag_service = get_rag_service()+ stats = rag_service.get_rag_stats()++ return jsonify({"success": True, "stats": stats})+ except Exception as e:+ logger.exception("Error getting RAG stats")+ return jsonify({"success": False, "error": str(e)}), 500+++@rag_bp.route("/api/rag/index-document", methods=["POST"])+@login_required+def index_document():+ """Index a single document."""+ try:+ data = request.get_json()+ text_doc_id = data.get("text_doc_id")+ force_reindex = data.get("force_reindex", False)++ if not text_doc_id:+ return jsonify(+ {"success": False, "error": "text_doc_id is required"}+ ), 400++ rag_service = get_rag_service()+ result = rag_service.index_document(text_doc_id, force_reindex)++ if result["status"] == "error":+ return jsonify(+ {"success": False, "error": result.get("error")}+ ), 400++ return jsonify({"success": True, "result": result})+ except Exception as e:+ logger.exception(f"Error indexing document {text_doc_id}")+ return jsonify({"success": False, "error": str(e)}), 500+++@rag_bp.route("/api/rag/remove-document", methods=["POST"])+@login_required+def remove_document():+ """Remove a document from RAG."""+ try:+ data = request.get_json()+ text_doc_id = data.get("text_doc_id")++ if not text_doc_id:+ return jsonify(+ {"success": False, "error": "text_doc_id is required"}+ ), 400++ rag_service = get_rag_service()+ result = rag_service.remove_document_from_rag(text_doc_id)++ if result["status"] == "error":+ return jsonify(+ {"success": False, "error": result.get("error")}+ ), 400++ return jsonify({"success": True, "result": result})+ except Exception as e:+ logger.exception(f"Error removing document {text_doc_id}")+ return jsonify({"success": False, "error": str(e)}), 500+++@rag_bp.route("/api/rag/index-research", methods=["POST"])+@login_required+def index_research():+ """Index all documents from a research."""+ try:+ data = request.get_json()+ research_id = data.get("research_id")+ force_reindex = data.get("force_reindex", False)++ if not research_id:+ return jsonify(+ {"success": False, "error": "research_id is required"}+ ), 400++ rag_service = get_rag_service()+ results = rag_service.index_research_documents(+ research_id, force_reindex+ )++ return jsonify({"success": True, "results": results})+ except Exception as e:+ logger.exception(f"Error indexing research {research_id}")+ return jsonify({"success": False, "error": str(e)}), 500+++@rag_bp.route("/api/rag/index-all", methods=["POST"])+@login_required+def index_all():+ """Index all library documents with Server-Sent Events progress."""+ force_reindex = request.args.get("force_reindex", "false").lower() == "true"++ def generate():+ """Generator function for SSE progress updates."""+ try:+ rag_service = get_rag_service()++ # Send initial status+ yield f"data: {json.dumps({'type': 'start', 'message': 'Starting bulk indexing...'})}\n\n"++ results = rag_service.index_all_documents(force_reindex)++ # Send completion status+ yield f"data: {json.dumps({'type': 'complete', 'results': results})}\n\n"++ except Exception as e:+ logger.exception("Error in bulk indexing")+ yield f"data: {json.dumps({'type': 'error', 'error': str(e)})}\n\n"++ return Response(generate(), mimetype="text/event-stream")+++@rag_bp.route("/api/rag/configure", methods=["POST"])+@login_required+def configure_rag():+ """+ Change RAG configuration (embedding model, chunk size, etc.).+ This will create a new index with the new configuration.+ """+ try:+ data = request.get_json()+ embedding_model = data.get("embedding_model")+ embedding_provider = data.get("embedding_provider")+ chunk_size = data.get("chunk_size")+ chunk_overlap = data.get("chunk_overlap")++ if not all(+ [embedding_model, embedding_provider, chunk_size, chunk_overlap]+ ):+ return jsonify(+ {+ "success": False,+ "error": "All configuration parameters are required",+ }+ ), 400++ # Create new RAG service with new configuration+ new_rag_service = LibraryRAGService(+ username=current_user.username,+ embedding_model=embedding_model,+ embedding_provider=embedding_provider,+ chunk_size=int(chunk_size),+ chunk_overlap=int(chunk_overlap),+ )++ # Get or create new index with this configuration+ rag_index = new_rag_service._get_or_create_rag_index()++ return jsonify(+ {+ "success": True,+ "message": "Configuration updated. You can now index documents with the new settings.",+ "index_hash": rag_index.index_hash,+ }+ )++ except Exception as e:+ logger.exception("Error configuring RAG")+ return jsonify({"success": False, "error": str(e)}), 500diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pynew file mode 100644index 0000000000..d0a6bcafeb--- /dev/null+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -0,0 +1,578 @@+"""+Library RAG Service++Handles indexing and searching library documents using RAG:+- Index text documents into vector database+- Chunk documents for semantic search+- Generate embeddings using local models+- Manage FAISS indices per research+- Track RAG status in library+"""++from datetime import UTC, datetime+from pathlib import Path+from typing import Any, Dict, List, Optional++from langchain_core.documents import Document+from langchain_text_splitters import RecursiveCharacterTextSplitter+from loguru import logger++from ...database.models.library import (+ DocumentChunk,+ LibraryTextDocument,+ RAGIndex,+)+from ...database.session_context import get_user_db_session+from ...web_search_engines.engines.search_engine_local import (+ LocalEmbeddingManager,+)+import hashlib+from faiss import IndexFlatL2+from langchain_community.vectorstores import FAISS+from langchain_community.docstore.in_memory import InMemoryDocstore+++class LibraryRAGService:+ """Service for managing RAG indexing of library documents."""++ def __init__(+ self,+ username: str,+ embedding_model: str = "all-MiniLM-L6-v2",+ embedding_provider: str = "sentence_transformers",+ chunk_size: int = 1000,+ chunk_overlap: int = 200,+ ):+ """+ Initialize library RAG service for a user.++ Args:+ username: Username for database access+ embedding_model: Name of the embedding model to use+ embedding_provider: Provider type ('sentence_transformers' or 'ollama')+ chunk_size: Size of text chunks for splitting+ chunk_overlap: Overlap between consecutive chunks+ """+ self.username = username+ self.embedding_model = embedding_model+ self.embedding_provider = embedding_provider+ self.chunk_size = chunk_size+ self.chunk_overlap = chunk_overlap++ # Initialize text splitter+ self.text_splitter = RecursiveCharacterTextSplitter(+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ length_function=len,+ separators=["\n\n", "\n", ". ", " ", ""],+ )++ # Initialize embedding manager with library collection+ # We'll use a settings snapshot that includes the username+ settings_snapshot = {+ "_username": username,+ "local_search_embedding_model": embedding_model,+ "local_search_embedding_provider": embedding_provider,+ "local_search_chunk_size": chunk_size,+ "local_search_chunk_overlap": chunk_overlap,+ }+ self.embedding_manager = LocalEmbeddingManager(settings_snapshot)++ # Initialize or load FAISS index for library collection+ self.faiss_index = None+ self.rag_index_record = None++ def _get_index_hash(+ self,+ collection_name: str,+ embedding_model: str,+ embedding_model_type: str,+ ) -> str:+ """Generate hash for index identification."""+ hash_input = (+ f"{collection_name}:{embedding_model}:{embedding_model_type}"+ )+ return hashlib.sha256(hash_input.encode()).hexdigest()++ def _get_index_path(self, index_hash: str) -> Path:+ """Get path for FAISS index file."""+ # Store in user's cache directory+ cache_dir = (+ Path.home() / ".cache" / "local_deep_research" / "rag_indices"+ )+ cache_dir.mkdir(parents=True, exist_ok=True)+ return cache_dir / f"{index_hash}.faiss"++ def _get_or_create_rag_index(self) -> RAGIndex:+ """Get or create RAGIndex record for the current configuration."""+ with get_user_db_session(self.username) as session:+ index_hash = self._get_index_hash(+ "library", self.embedding_model, self.embedding_provider+ )++ # Try to get existing index+ rag_index = (+ session.query(RAGIndex).filter_by(index_hash=index_hash).first()+ )++ if not rag_index:+ # Create new index record+ index_path = self._get_index_path(index_hash)++ # Get embedding dimension by embedding a test string+ test_embedding = self.embedding_manager.embeddings.embed_query(+ "test"+ )+ embedding_dim = len(test_embedding)++ rag_index = RAGIndex(+ collection_name="library",+ embedding_model=self.embedding_model,+ embedding_model_type=self.embedding_provider,+ embedding_dimension=embedding_dim,+ index_path=str(index_path),+ index_hash=index_hash,+ chunk_size=self.chunk_size,+ chunk_overlap=self.chunk_overlap,+ chunk_count=0,+ total_documents=0,+ status="active",+ is_current=True,+ )+ session.add(rag_index)+ session.commit()+ session.refresh(rag_index)+ logger.info(f"Created new RAG index: {index_hash}")++ return rag_index++ def _load_or_create_faiss_index(self) -> FAISS:+ """Load existing FAISS index or create new one."""+ rag_index = self._get_or_create_rag_index()+ self.rag_index_record = rag_index++ index_path = Path(rag_index.index_path)++ if index_path.exists():+ try:+ # Load existing FAISS index+ faiss_index = FAISS.load_local(+ str(index_path.parent),+ self.embedding_manager.embeddings,+ index_name=index_path.stem,+ allow_dangerous_deserialization=True,+ normalize_L2=True,+ )+ logger.info(f"Loaded existing FAISS index from {index_path}")+ return faiss_index+ except Exception as e:+ logger.warning(+ f"Failed to load FAISS index: {e}, creating new one"+ )++ # Create new FAISS index+ logger.info(+ f"Creating new FAISS index with dimension {rag_index.embedding_dimension}"+ )+ index = IndexFlatL2(rag_index.embedding_dimension)+ faiss_index = FAISS(+ self.embedding_manager.embeddings,+ index=index,+ docstore=InMemoryDocstore(), # Minimal - chunks in DB+ index_to_docstore_id={},+ normalize_L2=True,+ )+ return faiss_index++ def get_available_models(self) -> Dict[str, List[str]]:+ """Get list of available embedding models."""+ return {+ "sentence_transformers": [+ "all-MiniLM-L6-v2", # Default, fast, 384 dim+ "all-mpnet-base-v2", # Better quality, 768 dim+ "multi-qa-MiniLM-L6-cos-v1", # Optimized for Q&A+ "paraphrase-multilingual-MiniLM-L12-v2", # Multilingual+ ],+ "ollama": [+ "nomic-embed-text",+ "mxbai-embed-large",+ "all-minilm",+ ],+ }++ def get_current_index_info(self) -> Optional[Dict[str, Any]]:+ """Get information about the current RAG index."""+ with get_user_db_session(self.username) as session:+ rag_index = (+ session.query(RAGIndex)+ .filter_by(collection_name="library", is_current=True)+ .first()+ )++ if not rag_index:+ return None++ return {+ "embedding_model": rag_index.embedding_model,+ "embedding_model_type": rag_index.embedding_model_type,+ "embedding_dimension": rag_index.embedding_dimension,+ "chunk_size": rag_index.chunk_size,+ "chunk_overlap": rag_index.chunk_overlap,+ "chunk_count": rag_index.chunk_count,+ "total_documents": rag_index.total_documents,+ "created_at": rag_index.created_at.isoformat(),+ "last_updated_at": rag_index.last_updated_at.isoformat(),+ }++ def index_document(+ self, text_doc_id: int, force_reindex: bool = False+ ) -> Dict[str, Any]:+ """+ Index a single library text document into RAG.++ Args:+ text_doc_id: ID of the LibraryTextDocument to index+ force_reindex: Whether to force reindexing even if already indexed++ Returns:+ Dict with status, chunk_count, and any errors+ """+ with get_user_db_session(self.username) as session:+ # Get the text document+ text_doc = (+ session.query(LibraryTextDocument)+ .filter_by(id=text_doc_id)+ .first()+ )++ if not text_doc:+ return {"status": "error", "error": "Document not found"}++ # Check if already indexed+ if text_doc.rag_indexed and not force_reindex:+ return {+ "status": "skipped",+ "message": "Document already indexed",+ "chunk_count": text_doc.chunk_count,+ }++ # Validate text content+ if not text_doc.text_content:+ return {+ "status": "error",+ "error": "Document has no text content",+ }++ try:+ # Create LangChain Document from text+ doc = Document(+ page_content=text_doc.text_content,+ metadata={+ "source": text_doc.original_url,+ "title": text_doc.title or "Untitled",+ "authors": text_doc.authors,+ "published_date": str(text_doc.published_date)+ if text_doc.published_date+ else None,+ "doi": text_doc.doi,+ "arxiv_id": text_doc.arxiv_id,+ "pmid": text_doc.pmid,+ "pmcid": text_doc.pmcid,+ "extraction_method": text_doc.extraction_method,+ "word_count": text_doc.word_count,+ },+ )++ # Split into chunks+ chunks = self.text_splitter.split_documents([doc])+ logger.info(+ f"Split document {text_doc_id} into {len(chunks)} chunks"+ )++ # Store chunks in database using embedding manager+ embedding_ids = self.embedding_manager._store_chunks_to_db(+ chunks=chunks,+ collection_name="library", # Library collection+ source_type="library",+ source_id=text_doc_id,+ )++ # Load or create FAISS index+ if self.faiss_index is None:+ self.faiss_index = self._load_or_create_faiss_index()++ # Add embeddings to FAISS index+ logger.info(f"Adding {len(chunks)} embeddings to FAISS index")+ self.faiss_index.add_documents(chunks, ids=embedding_ids)++ # Save FAISS index+ index_path = Path(self.rag_index_record.index_path)+ self.faiss_index.save_local(+ str(index_path.parent), index_name=index_path.stem+ )+ logger.info(f"Saved FAISS index to {index_path}")++ # Update LibraryTextDocument with RAG status+ text_doc.rag_indexed = True+ text_doc.chunk_count = len(chunks)+ text_doc.last_indexed_at = datetime.now(UTC)++ # Update RAGIndex statistics+ rag_index_obj = (+ session.query(RAGIndex)+ .filter_by(id=self.rag_index_record.id)+ .first()+ )+ if rag_index_obj:+ rag_index_obj.chunk_count += len(chunks)+ rag_index_obj.total_documents += 1+ rag_index_obj.last_updated_at = datetime.now(UTC)++ session.commit()++ logger.info(+ f"Successfully indexed document {text_doc_id} "+ f"with {len(chunks)} chunks"+ )++ return {+ "status": "success",+ "chunk_count": len(chunks),+ "embedding_ids": embedding_ids,+ }++ except Exception as e:+ logger.exception(+ f"Error indexing document {text_doc_id}: {str(e)}"+ )+ return {"status": "error", "error": str(e)}++ def index_research_documents(+ self, research_id: str, force_reindex: bool = False+ ) -> Dict[str, Any]:+ """+ Index all text documents from a research into RAG.++ Args:+ research_id: ID of the research+ force_reindex: Whether to force reindexing already indexed documents++ Returns:+ Dict with counts of successful, skipped, and failed documents+ """+ with get_user_db_session(self.username) as session:+ # Get all text documents for this research+ text_docs = (+ session.query(LibraryTextDocument)+ .filter_by(research_id=research_id)+ .all()+ )++ if not text_docs:+ return {+ "status": "error",+ "error": "No text documents found for research",+ }++ results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}++ for text_doc in text_docs:+ result = self.index_document(text_doc.id, force_reindex)++ if result["status"] == "success":+ results["successful"] += 1+ elif result["status"] == "skipped":+ results["skipped"] += 1+ else:+ results["failed"] += 1+ results["errors"].append(+ {+ "doc_id": text_doc.id,+ "title": text_doc.title,+ "error": result.get("error"),+ }+ )++ logger.info(+ f"Indexed research {research_id}: "+ f"{results['successful']} successful, "+ f"{results['skipped']} skipped, "+ f"{results['failed']} failed"+ )++ return results++ def index_all_documents(+ self, force_reindex: bool = False+ ) -> Dict[str, Any]:+ """+ Index all library text documents into RAG.++ Args:+ force_reindex: Whether to force reindexing already indexed documents++ Returns:+ Dict with counts of successful, skipped, and failed documents+ """+ with get_user_db_session(self.username) as session:+ # Get all text documents+ query = session.query(LibraryTextDocument)++ if not force_reindex:+ # Only index documents that haven't been indexed yet+ query = query.filter_by(rag_indexed=False)++ text_docs = query.all()++ if not text_docs:+ return {+ "status": "info",+ "message": "No documents to index",+ "successful": 0,+ "skipped": 0,+ "failed": 0,+ }++ results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}++ for text_doc in text_docs:+ result = self.index_document(text_doc.id, force_reindex)++ if result["status"] == "success":+ results["successful"] += 1+ elif result["status"] == "skipped":+ results["skipped"] += 1+ else:+ results["failed"] += 1+ results["errors"].append(+ {+ "doc_id": text_doc.id,+ "title": text_doc.title,+ "error": result.get("error"),+ }+ )++ logger.info(+ f"Indexed all library documents: "+ f"{results['successful']} successful, "+ f"{results['skipped']} skipped, "+ f"{results['failed']} failed"+ )++ return results++ def remove_document_from_rag(self, text_doc_id: int) -> Dict[str, Any]:+ """+ Remove a document's chunks from RAG.++ Args:+ text_doc_id: ID of the LibraryTextDocument to remove++ Returns:+ Dict with status and count of removed chunks+ """+ with get_user_db_session(self.username) as session:+ # Get the text document+ text_doc = (+ session.query(LibraryTextDocument)+ .filter_by(id=text_doc_id)+ .first()+ )++ if not text_doc:+ return {"status": "error", "error": "Document not found"}++ try:+ # Delete chunks from database+ deleted_count = self.embedding_manager._delete_chunks_from_db(+ collection_name="library",+ source_id=text_doc_id,+ )++ # Update LibraryTextDocument RAG status+ text_doc.rag_indexed = False+ text_doc.chunk_count = 0+ text_doc.last_indexed_at = None+ session.commit()++ logger.info(+ f"Removed {deleted_count} chunks for document {text_doc_id}"+ )++ return {"status": "success", "deleted_count": deleted_count}++ except Exception as e:+ logger.exception(+ f"Error removing document {text_doc_id}: {str(e)}"+ )+ return {"status": "error", "error": str(e)}++ def get_rag_stats(self) -> Dict[str, Any]:+ """+ Get RAG statistics for the library.++ Returns:+ Dict with counts and metadata about indexed documents+ """+ with get_user_db_session(self.username) as session:+ # Count total text documents+ total_text_docs = session.query(LibraryTextDocument).count()++ # Count indexed documents+ indexed_docs = (+ session.query(LibraryTextDocument)+ .filter_by(rag_indexed=True)+ .count()+ )++ # Count total chunks+ total_chunks = (+ session.query(DocumentChunk)+ .filter_by(collection_name="library", source_type="library")+ .count()+ )++ # Get embedding model info from chunks+ chunk_sample = (+ session.query(DocumentChunk)+ .filter_by(collection_name="library")+ .first()+ )++ embedding_info = {}+ if chunk_sample:+ embedding_info = {+ "model": chunk_sample.embedding_model,+ "model_type": chunk_sample.embedding_model_type,+ "dimension": chunk_sample.embedding_dimension,+ }++ return {+ "total_text_documents": total_text_docs,+ "indexed_documents": indexed_docs,+ "unindexed_documents": total_text_docs - indexed_docs,+ "total_chunks": total_chunks,+ "embedding_info": embedding_info,+ "chunk_size": self.chunk_size,+ "chunk_overlap": self.chunk_overlap,+ }++ def search_library(+ self, query: str, limit: int = 10, score_threshold: float = 0.0+ ) -> List[Dict[str, Any]]:+ """+ Search library documents using semantic search.++ Args:+ query: Search query+ limit: Maximum number of results+ score_threshold: Minimum similarity score++ Returns:+ List of results with content, metadata, and similarity scores+ """+ # This will be implemented when we integrate with the search system+ # For now, raise NotImplementedError+ raise NotImplementedError(+ "Library search will be implemented in the search integration phase"+ )diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex 054b68cd49..055ee6d797 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -283,6 +283,16 @@ class LibraryService:and hasattr(text_doc, "text_content")and text_doc.text_content)+ has_rag_indexed = bool(+ text_doc+ and hasattr(text_doc, "rag_indexed")+ and text_doc.rag_indexed+ )+ rag_chunk_count = (+ text_doc.chunk_count+ if text_doc and hasattr(text_doc, "chunk_count")+ else 0+ )all_documents.append({@@ -331,6 +341,8 @@ class LibraryService:"has_pdf": has_pdf,"has_text_rag": has_text_rag,"has_text_db": has_text_db,+ "has_rag_indexed": has_rag_indexed,+ "rag_chunk_count": rag_chunk_count,# Sort key"_sort_date": doc.downloaded_at,}@@ -414,6 +426,8 @@ class LibraryService:has_pdf = False # No PDF for text-only documentshas_text_rag = bool(text_doc.file_path)has_text_db = bool(text_doc.text_content)+ has_rag_indexed = bool(text_doc.rag_indexed)+ rag_chunk_count = text_doc.chunk_count or 0all_documents.append({@@ -465,6 +479,8 @@ class LibraryService:"has_pdf": has_pdf,"has_text_rag": has_text_rag,"has_text_db": has_text_db,+ "has_rag_indexed": has_rag_indexed,+ "rag_chunk_count": rag_chunk_count,# Sort key"_sort_date": text_doc.extracted_at,}diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 2918f349b7..861c06871a 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -447,11 +447,15 @@ def register_blueprints(app):app.register_blueprint(api_blueprint) # Already has url_prefix='/api/v1'# Register Research Library blueprint- from ..research_library import library_bp+ from ..research_library import library_bp, rag_bpapp.register_blueprint(library_bp) # Already has url_prefix='/library'logger.info("Research Library routes registered successfully")+ # Register RAG Management blueprint+ app.register_blueprint(rag_bp) # Already has url_prefix='/library'+ logger.info("RAG Management routes registered successfully")+# After registration, update CSRF exemptionsif hasattr(app, "extensions") and "csrf" in app.extensions:csrf = app.extensions["csrf"]diff --git a/src/local_deep_research/web/static/js/rag_manager.js b/src/local_deep_research/web/static/js/rag_manager.jsnew file mode 100644index 0000000000..7491277dbd--- /dev/null+++ b/src/local_deep_research/web/static/js/rag_manager.js@@ -0,0 +1,400 @@+/**+ * RAG Manager JavaScript+ * Handles the RAG Manager UI interactions and API calls+ */++// Model descriptions+const MODEL_DESCRIPTIONS = {+ 'sentence_transformers': {+ 'all-MiniLM-L6-v2': 'Fast, lightweight model (384 dimensions). Good for general use.',+ 'all-mpnet-base-v2': 'Higher quality, slower (768 dimensions). Best accuracy.',+ 'multi-qa-MiniLM-L6-cos-v1': 'Optimized for question-answering tasks.',+ 'paraphrase-multilingual-MiniLM-L12-v2': 'Supports multiple languages.'+ },+ 'ollama': {+ 'nomic-embed-text': 'Local embedding model via Ollama.',+ 'mxbai-embed-large': 'Large embedding model for better quality.',+ 'all-minilm': 'MiniLM model via Ollama.'+ }+};++// Available models by provider+let availableModels = {};++/**+ * Safe fetch wrapper with URL validation+ */+async function safeFetch(url, options = {}) {+ // Internal URLs starting with '/' are safe+ if (!url.startsWith('/')) {+ if (!URLValidator.isSafeUrl(url)) {+ throw new Error(`Blocked unsafe URL: ${url}`);+ }+ }+ return fetch(url, options);+}++/**+ * Initialize the page+ */+document.addEventListener('DOMContentLoaded', function() {+ loadAvailableModels();+ loadCurrentIndexInfo();+ loadStats();++ // Setup provider change handler+ document.getElementById('embedding-provider').addEventListener('change', updateModelOptions);++ // Setup config form submission+ document.getElementById('rag-config-form').addEventListener('submit', handleConfigSubmit);+});++/**+ * Load available embedding models+ */+async function loadAvailableModels() {+ try {+ const response = await safeFetch('/library/api/rag/models');+ const data = await response.json();++ if (data.success) {+ availableModels = data.models;+ updateModelOptions();+ } else {+ showError('Failed to load available models: ' + data.error);+ }+ } catch (error) {+ console.error('Error loading models:', error);+ showError('Failed to load available models');+ }+}++/**+ * Update model dropdown based on selected provider+ */+function updateModelOptions() {+ const provider = document.getElementById('embedding-provider').value;+ const modelSelect = document.getElementById('embedding-model');+ const descriptionSpan = document.getElementById('model-description');++ // Clear existing options+ modelSelect.innerHTML = '';++ // Add models for selected provider+ const models = availableModels[provider] || [];+ models.forEach(model => {+ const option = document.createElement('option');+ option.value = model;+ option.textContent = model;+ modelSelect.appendChild(option);+ });++ // Update description+ updateModelDescription();++ // Add change handler for model selection+ modelSelect.addEventListener('change', updateModelDescription);+}++/**+ * Update model description text+ */+function updateModelDescription() {+ const provider = document.getElementById('embedding-provider').value;+ const model = document.getElementById('embedding-model').value;+ const descriptionSpan = document.getElementById('model-description');++ const description = MODEL_DESCRIPTIONS[provider]?.[model] || '';+ descriptionSpan.textContent = description;+}++/**+ * Load current index information+ */+async function loadCurrentIndexInfo() {+ const infoContainer = document.getElementById('current-index-info');++ try {+ const response = await safeFetch('/library/api/rag/info');+ const data = await response.json();++ if (data.success) {+ if (data.info) {+ renderIndexInfo(data.info);+ } else {+ infoContainer.innerHTML = `+ <div class="ldr-alert ldr-alert-info">+ <i class="fas fa-info-circle"></i> No RAG index exists yet. Configure settings and index documents to get started.+ </div>+ `;+ }+ } else {+ infoContainer.innerHTML = `+ <div class="ldr-alert ldr-alert-danger">+ Error loading index info: ${data.error}+ </div>+ `;+ }+ } catch (error) {+ console.error('Error loading index info:', error);+ infoContainer.innerHTML = `+ <div class="ldr-alert ldr-alert-danger">+ Failed to load index information+ </div>+ `;+ }+}++/**+ * Render index information+ */+function renderIndexInfo(info) {+ const infoContainer = document.getElementById('current-index-info');++ infoContainer.innerHTML = `+ <div class="ldr-info-item">+ <span class="ldr-info-label">Embedding Model:</span>+ <span class="ldr-info-value">${info.embedding_model}</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Provider:</span>+ <span class="ldr-info-value">${info.embedding_model_type}</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Vector Dimension:</span>+ <span class="ldr-info-value">${info.embedding_dimension}</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Chunk Size:</span>+ <span class="ldr-info-value">${info.chunk_size} characters</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Chunk Overlap:</span>+ <span class="ldr-info-value">${info.chunk_overlap} characters</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Total Chunks:</span>+ <span class="ldr-info-value">${info.chunk_count}</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Documents:</span>+ <span class="ldr-info-value">${info.total_documents}</span>+ </div>+ <div class="ldr-info-item">+ <span class="ldr-info-label">Last Updated:</span>+ <span class="ldr-info-value">${new Date(info.last_updated_at).toLocaleString()}</span>+ </div>+ `;+}++/**+ * Load RAG statistics+ */+async function loadStats() {+ const statsContainer = document.getElementById('rag-stats');++ try {+ const response = await safeFetch('/library/api/rag/stats');+ const data = await response.json();++ if (data.success) {+ renderStats(data.stats);+ } else {+ statsContainer.innerHTML = `+ <div class="ldr-alert ldr-alert-danger">+ Error loading statistics: ${data.error}+ </div>+ `;+ }+ } catch (error) {+ console.error('Error loading stats:', error);+ statsContainer.innerHTML = `+ <div class="ldr-alert ldr-alert-danger">+ Failed to load statistics+ </div>+ `;+ }+}++/**+ * Render statistics+ */+function renderStats(stats) {+ const statsContainer = document.getElementById('rag-stats');++ statsContainer.innerHTML = `+ <div class="ldr-stat-card">+ <span class="ldr-stat-value">${stats.total_text_documents}</span>+ <span class="ldr-stat-label">Total Text Documents</span>+ </div>+ <div class="ldr-stat-card">+ <span class="ldr-stat-value">${stats.indexed_documents}</span>+ <span class="ldr-stat-label">Indexed</span>+ </div>+ <div class="ldr-stat-card ldr-warning">+ <span class="ldr-stat-value">${stats.unindexed_documents}</span>+ <span class="ldr-stat-label">Not Indexed</span>+ </div>+ <div class="ldr-stat-card">+ <span class="ldr-stat-value">${stats.total_chunks}</span>+ <span class="ldr-stat-label">Total Chunks</span>+ </div>+ `;+}++/**+ * Handle configuration form submission+ */+async function handleConfigSubmit(event) {+ event.preventDefault();++ const formData = {+ embedding_provider: document.getElementById('embedding-provider').value,+ embedding_model: document.getElementById('embedding-model').value,+ chunk_size: parseInt(document.getElementById('chunk-size').value),+ chunk_overlap: parseInt(document.getElementById('chunk-overlap').value)+ };++ try {+ const response = await safeFetch('/library/api/rag/configure', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(formData)+ });++ const data = await response.json();++ if (data.success) {+ showSuccess('Configuration updated successfully! You can now index documents with the new settings.');+ loadCurrentIndexInfo();+ } else {+ showError('Failed to update configuration: ' + data.error);+ }+ } catch (error) {+ console.error('Error updating configuration:', error);+ showError('Failed to update configuration');+ }+}++/**+ * Index all documents+ */+async function indexAllDocuments(forceReindex) {+ const progressContainer = document.getElementById('progress-container');+ const progressBar = document.getElementById('progress-bar');+ const progressLog = document.getElementById('progress-log');++ // Show progress container+ progressContainer.style.display = 'block';+ progressBar.style.width = '0%';+ progressBar.textContent = '0%';+ progressLog.innerHTML = '';++ // Add initial log entry+ addLogEntry('Starting indexing process...', 'info');++ try {+ const eventSource = new EventSource(`/library/api/rag/index-all?force_reindex=${forceReindex}`);++ eventSource.onmessage = function(event) {+ const data = JSON.parse(event.data);++ if (data.type === 'start') {+ addLogEntry(data.message, 'info');+ progressBar.style.width = '10%';+ progressBar.textContent = '10%';+ } else if (data.type === 'complete') {+ const results = data.results;+ addLogEntry(`Indexing complete!`, 'success');+ addLogEntry(`✓ Successfully indexed: ${results.successful}`, 'success');+ if (results.skipped > 0) {+ addLogEntry(`⊘ Skipped (already indexed): ${results.skipped}`, 'info');+ }+ if (results.failed > 0) {+ addLogEntry(`✗ Failed: ${results.failed}`, 'error');+ results.errors.forEach(err => {+ addLogEntry(` - ${err.title}: ${err.error}`, 'error');+ });+ }++ progressBar.style.width = '100%';+ progressBar.textContent = '100%';+ progressBar.classList.remove('ldr-progress-bar-animated');++ // Refresh stats+ setTimeout(() => {+ refreshStats();+ }, 1000);++ eventSource.close();+ } else if (data.type === 'error') {+ addLogEntry(`Error: ${data.error}`, 'error');+ progressBar.classList.remove('ldr-progress-bar-animated');+ progressBar.classList.add('ldr-bg-danger');+ eventSource.close();+ }+ };++ eventSource.onerror = function(error) {+ console.error('EventSource error:', error);+ addLogEntry('Connection error occurred', 'error');+ progressBar.classList.remove('ldr-progress-bar-animated');+ progressBar.classList.add('ldr-bg-danger');+ eventSource.close();+ };++ } catch (error) {+ console.error('Error indexing documents:', error);+ addLogEntry(`Error: ${error.message}`, 'error');+ }+}++/**+ * Add log entry to progress log+ */+function addLogEntry(message, type = 'info') {+ const progressLog = document.getElementById('progress-log');+ const entry = document.createElement('div');+ entry.className = `ldr-log-entry ldr-${type}`;+ entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;+ progressLog.appendChild(entry);+ progressLog.scrollTop = progressLog.scrollHeight;+}++/**+ * Refresh statistics+ */+function refreshStats() {+ loadStats();+ loadCurrentIndexInfo();+}++/**+ * Show success message+ */+function showSuccess(message) {+ alert('Success: ' + message);+}++/**+ * Show error message+ */+function showError(message) {+ alert('Error: ' + message);+}++/**+ * Filter documents list+ */+function filterDocuments(filter) {+ // Update button states+ document.querySelectorAll('.ldr-filter-controls .ldr-btn').forEach(btn => {+ btn.classList.remove('ldr-active');+ });+ event.target.classList.add('ldr-active');++ // TODO: Implement document filtering+ console.log('Filter documents by:', filter);+}diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 7ac44e0b21..4ac4774f96 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -38,6 +38,9 @@<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'"><i class="fas fa-download"></i> Download Manager</button>+ <button class="btn btn-info" onclick="window.location.href='/library/rag-manager'">+ <i class="fas fa-brain"></i> RAG Manager+ </button><div class="library-stats"><span class="stat-item"><i class="fas fa-file-pdf"></i>@@ -209,6 +212,11 @@<i class="fas fa-database"></i> Text in DB</div>{% endif %}+ {% if doc.has_rag_indexed %}+ <div class="storage-badge storage-badge-rag-indexed" title="{{ doc.rag_chunk_count }} chunks indexed">+ <i class="fas fa-brain"></i> RAG Indexed ({{ doc.rag_chunk_count }} chunks)+ </div>+ {% endif %}{% if not doc.has_pdf and not doc.has_text_rag and not doc.has_text_db %}<div class="storage-badge storage-badge-none"><i class="fas fa-exclamation-triangle"></i> Not Downloaded@@ -679,6 +687,11 @@color: white;}+.storage-badge-rag-indexed {+ background: #6f42c1;+ color: white;+}+.storage-badge-none {background: #ff9800;color: white;diff --git a/src/local_deep_research/web/templates/pages/rag_manager.html b/src/local_deep_research/web/templates/pages/rag_manager.htmlnew file mode 100644index 0000000000..e7de4323a9--- /dev/null+++ b/src/local_deep_research/web/templates/pages/rag_manager.html@@ -0,0 +1,359 @@+{% extends "base.html" %}++{% block title %}RAG Manager{% endblock %}++{% block content %}+<div class="ldr-library-container">+ <div class="ldr-library-header">+ <h1>RAG Manager</h1>+ <p class="ldr-subtitle">Manage semantic search indexing for your library documents</p>+ </div>++ <!-- Configuration Panel -->+ <div class="ldr-rag-config-panel">+ <h2><i class="fas fa-cog"></i> Configuration</h2>++ <div class="ldr-config-grid">+ <!-- Current Index Info -->+ <div class="ldr-config-section">+ <h3>Current Index</h3>+ <div id="current-index-info" class="ldr-info-box">+ <div class="ldr-loading-spinner">+ <i class="fas fa-spinner fa-spin"></i> Loading...+ </div>+ </div>+ </div>++ <!-- Embedding Model Selection -->+ <div class="ldr-config-section">+ <h3>Embedding Configuration</h3>+ <form id="rag-config-form">+ <div class="ldr-form-group">+ <label for="embedding-provider">Provider</label>+ <select id="embedding-provider" class="ldr-form-control">+ <option value="sentence_transformers">Sentence Transformers</option>+ <option value="ollama">Ollama</option>+ </select>+ </div>++ <div class="ldr-form-group">+ <label for="embedding-model">Model</label>+ <select id="embedding-model" class="ldr-form-control">+ <!-- Options loaded dynamically -->+ </select>+ <small class="ldr-form-text ldr-text-muted">+ <span id="model-description"></span>+ </small>+ </div>++ <div class="ldr-form-row">+ <div class="ldr-form-group ldr-col-md-6">+ <label for="chunk-size">Chunk Size</label>+ <input type="number" id="chunk-size" class="ldr-form-control" value="1000" min="100" max="5000" step="100">+ <small class="ldr-form-text ldr-text-muted">Characters per chunk</small>+ </div>+ <div class="ldr-form-group ldr-col-md-6">+ <label for="chunk-overlap">Chunk Overlap</label>+ <input type="number" id="chunk-overlap" class="ldr-form-control" value="200" min="0" max="1000" step="50">+ <small class="ldr-form-text ldr-text-muted">Overlap between chunks</small>+ </div>+ </div>++ <button type="submit" class="ldr-btn ldr-btn-primary">+ <i class="fas fa-save"></i> Apply Configuration+ </button>+ <small class="ldr-form-text ldr-text-muted ldr-mt-2">+ Note: Changing configuration will create a new index. Existing indexed documents will need to be re-indexed.+ </small>+ </form>+ </div>+ </div>+ </div>++ <!-- Statistics Panel -->+ <div class="ldr-rag-stats-panel">+ <h2><i class="fas fa-chart-bar"></i> Statistics</h2>+ <div id="rag-stats" class="ldr-stats-grid">+ <div class="ldr-loading-spinner">+ <i class="fas fa-spinner fa-spin"></i> Loading statistics...+ </div>+ </div>+ </div>++ <!-- Bulk Operations Panel -->+ <div class="ldr-rag-operations-panel">+ <h2><i class="fas fa-tasks"></i> Bulk Operations</h2>++ <div class="ldr-operations-grid">+ <button class="ldr-btn ldr-btn-success ldr-btn-lg" onclick="indexAllDocuments(false)">+ <i class="fas fa-play"></i> Index Unindexed Documents+ </button>+ <button class="ldr-btn ldr-btn-warning ldr-btn-lg" onclick="indexAllDocuments(true)">+ <i class="fas fa-redo"></i> Re-Index All Documents+ </button>+ <button class="ldr-btn ldr-btn-info ldr-btn-lg" onclick="refreshStats()">+ <i class="fas fa-sync"></i> Refresh Statistics+ </button>+ </div>++ <!-- Progress Display -->+ <div id="progress-container" class="ldr-mt-4" style="display: none;">+ <h3>Indexing Progress</h3>+ <div class="ldr-progress">+ <div id="progress-bar" class="ldr-progress-bar ldr-progress-bar-striped ldr-progress-bar-animated" role="progressbar" style="width: 0%">+ 0%+ </div>+ </div>+ <div id="progress-log" class="ldr-log-container ldr-mt-3"></div>+ </div>+ </div>++ <!-- Document List -->+ <div class="ldr-rag-documents-panel">+ <h2><i class="fas fa-list"></i> Library Documents</h2>++ <div class="ldr-filter-controls ldr-mb-3">+ <div class="ldr-btn-group" role="group">+ <button type="button" class="ldr-btn ldr-btn-outline-primary ldr-active" onclick="filterDocuments('all')">+ All Documents+ </button>+ <button type="button" class="ldr-btn ldr-btn-outline-success" onclick="filterDocuments('indexed')">+ Indexed+ </button>+ <button type="button" class="ldr-btn ldr-btn-outline-warning" onclick="filterDocuments('unindexed')">+ Not Indexed+ </button>+ </div>+ </div>++ <div id="documents-list" class="ldr-documents-list">+ <div class="ldr-loading-spinner">+ <i class="fas fa-spinner fa-spin"></i> Loading documents...+ </div>+ </div>+ </div>+</div>++<style>+.ldr-library-container {+ padding: 20px;+ max-width: 1400px;+ margin: 0 auto;+}++.ldr-library-header {+ margin-bottom: 30px;+}++.ldr-library-header .ldr-subtitle {+ color: #666;+ font-size: 1.1em;+ margin-top: 10px;+}++.ldr-rag-config-panel,+.ldr-rag-stats-panel,+.ldr-rag-operations-panel,+.ldr-rag-documents-panel {+ background: white;+ border-radius: 8px;+ padding: 25px;+ margin-bottom: 25px;+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);+}++.ldr-rag-config-panel h2,+.ldr-rag-stats-panel h2,+.ldr-rag-operations-panel h2,+.ldr-rag-documents-panel h2 {+ margin-bottom: 20px;+ color: #333;+ font-size: 1.5em;+}++.ldr-config-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 30px;+}++@media (max-width: 992px) {+ .ldr-config-grid {+ grid-template-columns: 1fr;+ }+}++.ldr-config-section {+ background: #f8f9fa;+ padding: 20px;+ border-radius: 6px;+}++.ldr-config-section h3 {+ margin-bottom: 15px;+ font-size: 1.2em;+ color: #555;+}++.ldr-info-box {+ background: white;+ padding: 15px;+ border-radius: 4px;+ border-left: 4px solid #007bff;+}++.ldr-info-box .ldr-info-item {+ display: flex;+ justify-content: space-between;+ padding: 8px 0;+ border-bottom: 1px solid #eee;+}++.ldr-info-box .ldr-info-item:last-child {+ border-bottom: none;+}++.ldr-info-box .ldr-info-label {+ font-weight: 600;+ color: #555;+}++.ldr-info-box .ldr-info-value {+ color: #333;+}++.ldr-stats-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 20px;+}++.ldr-stat-card {+ background: #f8f9fa;+ padding: 20px;+ border-radius: 6px;+ text-align: center;+ border-left: 4px solid #28a745;+}++.ldr-stat-card.ldr-warning {+ border-left-color: #ffc107;+}++.ldr-stat-card .ldr-stat-value {+ font-size: 2.5em;+ font-weight: bold;+ color: #333;+ display: block;+}++.ldr-stat-card .ldr-stat-label {+ color: #666;+ margin-top: 10px;+ font-size: 0.9em;+}++.ldr-operations-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));+ gap: 20px;+}++.ldr-loading-spinner {+ text-align: center;+ padding: 40px;+ color: #666;+ font-size: 1.2em;+}++.ldr-log-container {+ max-height: 300px;+ overflow-y: auto;+ background: #f8f9fa;+ padding: 15px;+ border-radius: 4px;+ font-family: monospace;+ font-size: 0.9em;+}++.ldr-log-entry {+ padding: 5px 0;+ border-bottom: 1px solid #eee;+}++.ldr-log-entry:last-child {+ border-bottom: none;+}++.ldr-log-entry.ldr-success {+ color: #28a745;+}++.ldr-log-entry.ldr-error {+ color: #dc3545;+}++.ldr-log-entry.ldr-info {+ color: #17a2b8;+}++.ldr-documents-list {+ margin-top: 20px;+}++.ldr-filter-controls {+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.ldr-document-item {+ background: #f8f9fa;+ padding: 15px;+ margin-bottom: 10px;+ border-radius: 6px;+ display: flex;+ justify-content: space-between;+ align-items: center;+}++.ldr-document-info {+ flex: 1;+}++.ldr-document-title {+ font-weight: 600;+ color: #333;+ margin-bottom: 5px;+}++.ldr-document-meta {+ font-size: 0.9em;+ color: #666;+}++.ldr-document-actions {+ display: flex;+ gap: 10px;+}++.ldr-badge-indexed {+ background: #28a745;+ color: white;+ padding: 4px 8px;+ border-radius: 4px;+ font-size: 0.85em;+}++.ldr-badge-unindexed {+ background: #6c757d;+ color: white;+ padding: 4px 8px;+ border-radius: 4px;+ font-size: 0.85em;+}+</style>++<script src="/static/js/security/url-validator.js"></script>+<script src="/static/js/rag_manager.js"></script>+{% endblock %}diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.pynew file mode 100644index 0000000000..4c16acc62a--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py@@ -0,0 +1,158 @@+"""+Library RAG Search Engine++Provides semantic search over the user's personal research library using RAG.+"""++from typing import List, Dict, Any, Optional+from loguru import logger+import numpy as np++from .search_engine_base import BaseSearchEngine+from ...research_library.services.library_rag_service import LibraryRAGService+from ...config.thread_settings import get_setting_from_snapshot+++class LibraryRAGSearchEngine(BaseSearchEngine):+ """+ Search engine that queries the user's research library using RAG/semantic search.+ """++ def __init__(self, settings_snapshot: Optional[Dict[str, Any]] = None):+ """+ Initialize the Library RAG search engine.++ Args:+ settings_snapshot: Settings snapshot from thread context+ """+ super().__init__(settings_snapshot)+ self.username = (+ settings_snapshot.get("_username") if settings_snapshot else None+ )++ if not self.username:+ logger.warning(+ "Library RAG search engine initialized without username"+ )++ # Get RAG configuration from settings+ self.embedding_model = get_setting_from_snapshot(+ "local_search_embedding_model",+ settings_snapshot,+ "all-MiniLM-L6-v2",+ )+ self.embedding_provider = get_setting_from_snapshot(+ "local_search_embedding_provider",+ settings_snapshot,+ "sentence_transformers",+ )+ self.chunk_size = get_setting_from_snapshot(+ "local_search_chunk_size", settings_snapshot, 1000+ )+ self.chunk_overlap = get_setting_from_snapshot(+ "local_search_chunk_overlap", settings_snapshot, 200+ )++ def search(+ self,+ query: str,+ limit: int = 10,+ llm_callback=None,+ extra_params: Optional[Dict[str, Any]] = None,+ ) -> List[Dict[str, Any]]:+ """+ Search the library using semantic search.++ Args:+ query: Search query+ limit: Maximum number of results to return+ llm_callback: Optional LLM callback for processing results+ extra_params: Additional search parameters++ Returns:+ List of search results with title, url, snippet, etc.+ """+ if not self.username:+ logger.error("Cannot search library without username")+ return []++ try:+ # Initialize RAG service+ rag_service = LibraryRAGService(+ username=self.username,+ embedding_model=self.embedding_model,+ embedding_provider=self.embedding_provider,+ chunk_size=self.chunk_size,+ chunk_overlap=self.chunk_overlap,+ )++ # Get RAG stats to check if there are any indexed documents+ stats = rag_service.get_rag_stats()+ if stats.get("total_indexed_documents", 0) == 0:+ logger.info("No documents indexed in library RAG")+ return []++ # Load the FAISS index+ vector_store = rag_service._load_or_create_faiss_index()++ # Perform similarity search+ query_vector = rag_service.embeddings.embed_query(query)+ distances, indices = vector_store.index.search(+ np.array([query_vector], dtype=np.float32), limit+ )++ # Get chunk IDs from FAISS index+ embedding_ids = [+ vector_store.index_to_docstore_id[idx] for idx in indices[0]+ ]++ # Load chunks from database+ chunks = rag_service._load_chunks_from_db(embedding_ids)++ # Convert chunks to search results format+ results = []+ for i, chunk in enumerate(chunks):+ if chunk is None:+ continue++ # Calculate relevance score (inverse of distance, normalized)+ distance = distances[0][i]+ score = 1 / (1 + distance)++ result = {+ "title": chunk.document_title+ or f"Document {chunk.source_id}",+ "snippet": chunk.chunk_text[:500] + "..."+ if len(chunk.chunk_text) > 500+ else chunk.chunk_text,+ "url": f"/library/document/{chunk.source_id}"+ if chunk.source_id+ else "#",+ "source": "library",+ "relevance_score": float(score),+ "metadata": {+ "document_id": chunk.source_id,+ "chunk_index": chunk.chunk_index,+ "word_count": chunk.word_count,+ "embedding_model": chunk.embedding_model,+ },+ }++ # Add metadata if available+ if chunk.document_metadata:+ result["metadata"].update(chunk.document_metadata)++ results.append(result)++ logger.info(+ f"Library RAG search returned {len(results)} results for query: {query}"+ )+ return results++ except Exception:+ logger.exception("Error searching library RAG")+ return []++ def close(self):+ """Clean up resources."""+ passdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.pyindex dd782c02de..912a3e9c51 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py@@ -4,10 +4,11 @@ import osimport timeimport uuidfrom concurrent.futures import ProcessPoolExecutor-from datetime import datetime+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any, Dict, Iterable, List, Optional+import numpy as npfrom faiss import IndexFlatL2from langchain_community.docstore.in_memory import InMemoryDocstorefrom langchain_community.document_loaders import (@@ -32,6 +33,8 @@ from loguru import loggerfrom ...config import search_configfrom ...config.thread_settings import get_setting_from_snapshot+from ...database.models.library import DocumentChunk+from ...database.session_context import get_user_db_sessionfrom ...utilities.url_utils import normalize_urlfrom ..search_engine_base import BaseSearchEngine@@ -136,6 +139,11 @@ class LocalEmbeddingManager:self.cache_dir = Path(cache_dir)self.settings_snapshot = settings_snapshot or {}+ # Username for database access (extracted from settings if available)+ self.username = (+ settings_snapshot.get("_username") if settings_snapshot else None+ )+# Create cache directory if it doesn't existself.cache_dir.mkdir(parents=True, exist_ok=True)@@ -214,6 +222,216 @@ class LocalEmbeddingManager:model_name="sentence-transformers/all-MiniLM-L6-v2")+ def _store_chunks_to_db(+ self,+ chunks: List[Document],+ collection_name: str,+ source_path: Optional[str] = None,+ source_id: Optional[int] = None,+ source_type: str = "local_file",+ ) -> List[str]:+ """+ Store document chunks in the database.++ Args:+ chunks: List of LangChain Document chunks+ collection_name: Name of the collection (e.g., 'personal_notes', 'library')+ source_path: Path to source file (for local files)+ source_id: ID of source document (for library documents)+ source_type: Type of source ('local_file' or 'library')++ Returns:+ List of chunk embedding IDs (UUIDs) for FAISS mapping+ """+ if not self.username:+ logger.warning(+ "No username available, cannot store chunks in database"+ )+ return []++ chunk_ids = []++ try:+ with get_user_db_session(self.username) as session:+ for idx, chunk in enumerate(chunks):+ # Generate unique hash for chunk+ chunk_text = chunk.page_content+ chunk_hash = hashlib.sha256(chunk_text.encode()).hexdigest()++ # Generate unique embedding ID+ embedding_id = uuid.uuid4().hex++ # Extract metadata+ metadata = chunk.metadata or {}+ document_title = metadata.get(+ "filename", metadata.get("title", "Unknown")+ )++ # Calculate word count+ word_count = len(chunk_text.split())++ # Get character positions from metadata if available+ start_char = metadata.get("start_char", 0)+ end_char = metadata.get("end_char", len(chunk_text))++ # Check if chunk already exists+ existing_chunk = (+ session.query(DocumentChunk)+ .filter_by(chunk_hash=chunk_hash)+ .first()+ )++ if existing_chunk:+ # Update existing chunk+ existing_chunk.last_accessed = datetime.now(UTC)+ chunk_ids.append(existing_chunk.embedding_id)+ logger.debug(+ f"Chunk already exists, reusing: {existing_chunk.embedding_id}"+ )+ else:+ # Create new chunk+ db_chunk = DocumentChunk(+ chunk_hash=chunk_hash,+ source_type=source_type,+ source_id=source_id,+ source_path=str(source_path)+ if source_path+ else None,+ collection_name=collection_name,+ chunk_text=chunk_text,+ chunk_index=idx,+ start_char=start_char,+ end_char=end_char,+ word_count=word_count,+ embedding_id=embedding_id,+ embedding_model=self.embedding_model,+ embedding_model_type=self.embedding_model_type,+ document_title=document_title,+ document_metadata=metadata,+ )+ session.add(db_chunk)+ chunk_ids.append(embedding_id)++ session.commit()+ logger.info(+ f"Stored {len(chunk_ids)} chunks to database for collection '{collection_name}'"+ )++ except Exception:+ logger.exception(+ f"Error storing chunks to database for collection '{collection_name}'"+ )+ return []++ return chunk_ids++ def _load_chunks_from_db(+ self, chunk_ids: List[str], username: Optional[str] = None+ ) -> List[Dict[str, Any]]:+ """+ Load chunks from database by their embedding IDs.++ Args:+ chunk_ids: List of embedding IDs to load+ username: Username for database access (uses self.username if not provided)++ Returns:+ List of chunk dictionaries with content and metadata+ """+ username = username or self.username+ if not username:+ logger.warning(+ "No username available, cannot load chunks from database"+ )+ return []++ chunks = []++ try:+ with get_user_db_session(username) as session:+ db_chunks = (+ session.query(DocumentChunk)+ .filter(DocumentChunk.embedding_id.in_(chunk_ids))+ .all()+ )++ for db_chunk in db_chunks:+ # Update last accessed time+ db_chunk.last_accessed = datetime.now(UTC)++ chunks.append(+ {+ "id": db_chunk.embedding_id,+ "content": db_chunk.chunk_text,+ "metadata": {+ "source_type": db_chunk.source_type,+ "source_path": db_chunk.source_path,+ "source_id": db_chunk.source_id,+ "collection": db_chunk.collection_name,+ "chunk_index": db_chunk.chunk_index,+ "word_count": db_chunk.word_count,+ "title": db_chunk.document_title,+ **db_chunk.document_metadata,+ },+ }+ )++ session.commit() # Commit the last_accessed updates++ except Exception:+ logger.exception("Error loading chunks from database")+ return []++ return chunks++ def _delete_chunks_from_db(+ self,+ collection_name: str,+ source_path: Optional[str] = None,+ source_id: Optional[int] = None,+ ) -> int:+ """+ Delete chunks from database.++ Args:+ collection_name: Name of the collection+ source_path: Path to source file (for local files)+ source_id: ID of source document (for library documents)++ Returns:+ Number of chunks deleted+ """+ if not self.username:+ logger.warning(+ "No username available, cannot delete chunks from database"+ )+ return 0++ try:+ with get_user_db_session(self.username) as session:+ query = session.query(DocumentChunk).filter_by(+ collection_name=collection_name+ )++ if source_path:+ query = query.filter_by(source_path=str(source_path))+ if source_id:+ query = query.filter_by(source_id=source_id)++ count = query.delete()+ session.commit()++ logger.info(+ f"Deleted {count} chunks from database for collection '{collection_name}'"+ )+ return count++ except Exception:+ logger.exception(+ f"Error deleting chunks from database for collection '{collection_name}'"+ )+ return 0+def _load_or_create_vector_store(self):"""Load the vector store from disk or create it if needed"""vector_store_path = self._get_vector_store_path()@@ -445,10 +663,11 @@ class LocalEmbeddingManager:# Embed a test query to figure out embedding length.test_embedding = self.embeddings.embed_query("hello world")index = IndexFlatL2(len(test_embedding))+ # Use minimal docstore - chunks are stored in databaseself.vector_stores[folder_hash] = FAISS(self.embeddings,index=index,- docstore=InMemoryDocstore(),+ docstore=InMemoryDocstore(), # Minimal - just for FAISS compatibilityindex_to_docstore_id={},normalize_L2=True,)@@ -460,12 +679,25 @@ class LocalEmbeddingManager:f"Created {len(splits)} chunks from {len(modified_files)} files")- # Create vector store- ids = []+ # Store chunks in database and get embedding IDs+ embedding_ids = []if splits:- logger.info(f"Adding {len(splits)} chunks to vector store")- ids = [uuid.uuid4().hex for _ in splits]- self.vector_stores[folder_hash].add_documents(splits, ids=ids)+ logger.info(f"Storing {len(splits)} chunks in database")+ # Get collection name from folder path (last folder name)+ collection_name = folder_path.name++ # Store chunks to database+ embedding_ids = self._store_chunks_to_db(+ chunks=splits,+ collection_name=collection_name,+ source_type="local_file",+ )++ logger.info(f"Adding {len(splits)} chunks to FAISS index")+ # Add embeddings to FAISS using the database-generated IDs+ self.vector_stores[folder_hash].add_documents(+ splits, ids=embedding_ids+ )# Update indexing time for individual files.index_time = time.time()@@ -476,15 +708,15 @@ class LocalEmbeddingManager:.get("indexed_files", {}).copy())- for split_id, split in zip(ids, splits, strict=False):+ for embedding_id, split in zip(embedding_ids, splits, strict=False):split_source = str(Path(split.metadata["source"]).relative_to(folder_path))id_list = indexed_files.setdefault(split_source, [])- id_list.append(split_id)+ id_list.append(embedding_id)# Check for any files that were removed and remove them from the- # vector store.+ # vector store and database.delete_ids = []delete_paths = []for relative_path, chunk_ids in indexed_files.items():@@ -494,9 +726,22 @@ class LocalEmbeddingManager:if delete_ids:logger.info(f"Deleting {len(delete_paths)} non-existent files from the "- f"index."+ f"index and database.")+ # Delete from FAISS indexself.vector_stores[folder_hash].delete(delete_ids)++ # Delete from database+ collection_name = folder_path.name+ for delete_path in delete_paths:+ full_path = str(folder_path / delete_path)+ deleted_count = self._delete_chunks_from_db(+ collection_name=collection_name,+ source_path=full_path,+ )+ logger.debug(+ f"Deleted {deleted_count} chunks for {delete_path} from database"+ )for path in delete_paths:del indexed_files[path]@@ -609,25 +854,62 @@ class LocalEmbeddingManager:vector_store = self.vector_stores[folder_hash]try:- docs_with_scores = (- vector_store.similarity_search_with_relevance_scores(- query, k=limit- )+ # Get query embedding+ query_vector = self.embeddings.embed_query(query)++ # Search FAISS index for similar vectors+ # Returns: (distances, indices) where indices are FAISS internal indices+ distances, indices = vector_store.index.search(+ np.array([query_vector], dtype=np.float32), limit)- for doc, similarity in docs_with_scores:- # Skip results below the threshold- if similarity < score_threshold:- continue+ # Convert distances to similarity scores (L2 distance -> similarity)+ # For L2: smaller distance = more similar+ # Convert to similarity: 1 / (1 + distance)+ similarities = 1 / (1 + distances[0])- result = {- "content": doc.page_content,- "metadata": doc.metadata,- "similarity": float(similarity),- "folder": folder_path,- }+ # Get embedding IDs from FAISS mapping+ embedding_ids = []+ valid_indices = []+ for idx, faiss_idx in enumerate(indices[0]):+ if faiss_idx == -1: # FAISS returns -1 for empty results+ continue+ if faiss_idx in vector_store.index_to_docstore_id:+ embedding_id = vector_store.index_to_docstore_id[+ faiss_idx+ ]+ embedding_ids.append(embedding_id)+ valid_indices.append(idx)++ # Load chunks from database+ if embedding_ids:+ db_chunks = self._load_chunks_from_db(+ embedding_ids, self.username+ )- all_results.append(result)+ # Create results from database chunks+ for idx, chunk in zip(valid_indices, db_chunks):+ similarity = float(similarities[idx])++ # Skip results below the threshold+ if similarity < score_threshold:+ continue++ # Extract metadata from chunk+ metadata = chunk.get("document_metadata", {})+ if "source" not in metadata and chunk.get(+ "source_path"+ ):+ metadata["source"] = chunk["source_path"]++ result = {+ "content": chunk["chunk_text"],+ "metadata": metadata,+ "similarity": similarity,+ "folder": folder_path,+ }++ all_results.append(result)except Exception:logger.exception(f"Error searching in {folder_path}")diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.pyindex 6a4aae6b4d..c03a47e54f 100644--- a/src/local_deep_research/web_search_engines/search_engines_config.py+++ b/src/local_deep_research/web_search_engines/search_engines_config.py@@ -210,6 +210,35 @@ def search_config(logger.info("Registered local document collections as search engines")+ # Register Library RAG as a search engine+ library_enabled = _get_setting(+ "search.engine.library.enabled",+ True,+ db_session=db_session,+ settings_snapshot=settings_snapshot,+ username=username,+ )++ if library_enabled:+ search_engines["library"] = {+ "module_path": "local_deep_research.web_search_engines.engines.search_engine_library",+ "class_name": "LibraryRAGSearchEngine",+ "requires_llm": True,+ "default_params": {},+ "description": "Search your personal research library documents using semantic search",+ "strengths": [+ "Searches your curated library of research papers and documents",+ "Uses semantic search for better relevance",+ "Returns documents you've already saved and reviewed",+ ],+ "weaknesses": [+ "Limited to documents already in your library",+ "Requires documents to be indexed first",+ ],+ "reliability": "High - searches your personal collection",+ }+ logger.info("Registered Library RAG as search engine")+return search_engines