~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
fix: library RAG search engine implementation and metadata handling
LearningCircuitb58dee492439
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pyindex 3533e13eb8..cb436c0ab5 100644--- a/src/local_deep_research/config/search_config.py+++ b/src/local_deep_research/config/search_config.py@@ -72,6 +72,14 @@ def get_search(# Get LLM instance (use provided or get fresh one)llm = llm_instance or get_llm(settings_snapshot=settings_snapshot)+ # Ensure username is in settings_snapshot for search engines that need it (e.g., library)+ if username and settings_snapshot is not None:+ # Create a copy to avoid modifying the original+ settings_snapshot = {**settings_snapshot, "_username": username}+ elif username:+ # Create new snapshot with username+ settings_snapshot = {"_username": username}+# Get search parametersparams = {"search_tool": tool,diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 1c1f1fc761..e96880b053 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -190,25 +190,12 @@ class LibraryRAGService:)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:+ # Expire all cached objects to get fresh data from database+ session.expire_all()+rag_index = (session.query(RAGIndex).filter_by(collection_name="library", is_current=True)@@ -275,7 +262,10 @@ class LibraryRAGService:page_content=text_doc.text_content,metadata={"source": text_doc.original_url,+ "source_id": text_doc_id, # Add document ID for source linking"title": text_doc.title or "Untitled",+ "document_title": text_doc.title+ or "Untitled", # Add for compatibility"authors": text_doc.authors,"published_date": str(text_doc.published_date)if text_doc.published_date@@ -307,9 +297,55 @@ class LibraryRAGService:if self.faiss_index is None:self.faiss_index = self._load_or_create_faiss_index()+ # If force_reindex, remove old chunks from FAISS before adding new ones+ if force_reindex:+ existing_ids = (+ set(self.faiss_index.docstore._dict.keys())+ if hasattr(self.faiss_index, "docstore")+ else set()+ )+ old_chunk_ids = [+ eid for eid in embedding_ids if eid in existing_ids+ ]+ if old_chunk_ids:+ logger.info(+ f"Force re-index: removing {len(old_chunk_ids)} existing chunks from FAISS"+ )+ self.faiss_index.delete(old_chunk_ids)++ # Filter out chunks that already exist in FAISS (unless force_reindex)+ if not force_reindex:+ existing_ids = (+ set(self.faiss_index.docstore._dict.keys())+ if hasattr(self.faiss_index, "docstore")+ else set()+ )+ new_chunks = []+ new_ids = []+ for chunk, chunk_id in zip(chunks, embedding_ids):+ if chunk_id not in existing_ids:+ new_chunks.append(chunk)+ new_ids.append(chunk_id)+ else:+ # force_reindex: add all chunks+ new_chunks = chunks+ new_ids = embedding_ids+# Add embeddings to FAISS index- logger.info(f"Adding {len(chunks)} embeddings to FAISS index")- self.faiss_index.add_documents(chunks, ids=embedding_ids)+ if new_chunks:+ if force_reindex:+ logger.info(+ f"Force re-index: adding {len(new_chunks)} chunks with updated metadata to FAISS index"+ )+ else:+ logger.info(+ f"Adding {len(new_chunks)} new embeddings to FAISS index ({len(chunks) - len(new_chunks)} already exist)"+ )+ self.faiss_index.add_documents(new_chunks, ids=new_ids)+ else:+ logger.info(+ f"All {len(chunks)} chunks already exist in FAISS index, skipping"+ )# Save FAISS indexindex_path = Path(self.rag_index_record.index_path)@@ -319,23 +355,38 @@ class LibraryRAGService:logger.info(f"Saved FAISS index to {index_path}")# Update LibraryTextDocument with RAG status+ # CRITICAL: Re-merge the object into the session since it might have been detached+ # by nested session contexts (e.g., from _store_chunks_to_db using same thread-local session)+ text_doc = session.merge(text_doc)++ was_already_indexed = (+ text_doc.rag_indexed+ ) # Check BEFORE updatingtext_doc.rag_indexed = Truetext_doc.chunk_count = len(chunks)text_doc.last_indexed_at = datetime.now(UTC)- # Update RAGIndex statistics+ # Update RAGIndex statistics (only if not already indexed)rag_index_obj = (session.query(RAGIndex).filter_by(id=self.rag_index_record.id).first())- if rag_index_obj:+ if rag_index_obj and not was_already_indexed:rag_index_obj.chunk_count += len(chunks)rag_index_obj.total_documents += 1rag_index_obj.last_updated_at = datetime.now(UTC)+ logger.info(+ f"Updated RAGIndex stats: chunk_count +{len(chunks)}, total_documents +1"+ )+ # Commit the changessession.commit()+ # CRITICAL: Expire all cached objects in this thread-local session+ # so subsequent operations in the same thread see fresh data+ session.expire_all()+logger.info(f"Successfully indexed document {text_doc_id} "f"with {len(chunks)} chunks"@@ -409,13 +460,14 @@ class LibraryRAGService:return resultsdef index_all_documents(- self, force_reindex: bool = False+ self, force_reindex: bool = False, progress_callback=None) -> Dict[str, Any]:"""Index all library text documents into RAG.Args:force_reindex: Whether to force reindexing already indexed documents+ progress_callback: Optional callback function called after each document with (current, total, doc_title, status)Returns:Dict with counts of successful, skipped, and failed documents@@ -440,8 +492,9 @@ class LibraryRAGService:}results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}+ total = len(text_docs)- for text_doc in text_docs:+ for idx, text_doc in enumerate(text_docs, 1):result = self.index_document(text_doc.id, force_reindex)if result["status"] == "success":@@ -458,6 +511,12 @@ class LibraryRAGService:})+ # Call progress callback if provided+ if progress_callback:+ progress_callback(+ idx, total, text_doc.title, result["status"]+ )+logger.info(f"Indexed all library documents: "f"{results['successful']} successful, "@@ -521,6 +580,9 @@ class LibraryRAGService:Dict with counts and metadata about indexed documents"""with get_user_db_session(self.username) as session:+ # Expire all cached objects to get fresh data from database+ session.expire_all()+# Count total text documentstotal_text_docs = session.query(LibraryTextDocument).count()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.pyindex 4c16acc62a..411d1de923 100644--- 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.py@@ -6,9 +6,8 @@ Provides semantic search over the user's personal research library using RAG.from typing import List, Dict, Any, Optionalfrom loguru import logger-import numpy as np-from .search_engine_base import BaseSearchEngine+from ..search_engine_base import BaseSearchEnginefrom ...research_library.services.library_rag_service import LibraryRAGServicefrom ...config.thread_settings import get_setting_from_snapshot@@ -18,14 +17,31 @@ 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):+ def __init__(+ self,+ llm: Optional[Any] = None,+ max_filtered_results: Optional[int] = None,+ max_results: int = 10,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):"""Initialize the Library RAG search engine.Args:+ llm: Language model for relevance filtering+ max_filtered_results: Maximum number of results to keep after filtering+ max_results: Maximum number of search resultssettings_snapshot: Settings snapshot from thread context+ **kwargs: Additional engine-specific parameters"""- super().__init__(settings_snapshot)+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )self.username = (settings_snapshot.get("_username") if settings_snapshot else None)@@ -88,60 +104,50 @@ class LibraryRAGSearchEngine(BaseSearchEngine):# Get RAG stats to check if there are any indexed documentsstats = rag_service.get_rag_stats()- if stats.get("total_indexed_documents", 0) == 0:+ if stats.get("indexed_documents", 0) == 0:logger.info("No documents indexed in library RAG")return []# Load the FAISS indexvector_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+ # Use FAISS vector store's built-in similarity search+ docs_with_scores = vector_store.similarity_search_with_score(+ query, k=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+ # Convert Document objects to search results formatresults = []- 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)+ for doc, score in docs_with_scores:+ # Extract metadata from Document object+ metadata = doc.metadata or {}+ doc_id = metadata.get("source_id")+ title = metadata.get(+ "document_title",+ f"Document {doc_id}" if doc_id else "Unknown",+ )++ # Content is stored in page_content+ snippet = (+ doc.page_content[:500] + "..."+ if len(doc.page_content) > 500+ else doc.page_content+ )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 "#",+ "title": title,+ "snippet": snippet,+ "url": f"/library/document/{doc_id}" if doc_id else "#",+ "link": f"/library/document/{doc_id}"+ if doc_id+ else "#", # Add "link" for source extraction"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,- },+ "relevance_score": float(+ 1 / (1 + score)+ ), # Convert distance to similarity+ "metadata": metadata,}- # Add metadata if available- if chunk.document_metadata:- result["metadata"].update(chunk.document_metadata)-results.append(result)logger.info(@@ -153,6 +159,76 @@ class LibraryRAGSearchEngine(BaseSearchEngine):logger.exception("Error searching library RAG")return []+ def _get_previews(+ self,+ query: str,+ limit: int = 10,+ llm_callback=None,+ extra_params: Optional[Dict[str, Any]] = None,+ ) -> List[Dict[str, Any]]:+ """+ Get preview results for the query.+ Delegates to the search method.+ """+ return self.search(query, limit, llm_callback, extra_params)++ def _get_full_content(+ self, relevant_items: List[Dict[str, Any]]+ ) -> List[Dict[str, Any]]:+ """+ Get full content for relevant library documents.+ Retrieves complete document text instead of just snippets.+ """+ # Check if we should get full content+ from ... import search_config++ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):+ logger.info("Snippet-only mode, skipping full content retrieval")+ return relevant_items++ if not self.username:+ logger.error("Cannot retrieve full content without username")+ return relevant_items++ try:+ from ...database.models.library import LibraryTextDocument+ from ...database.session_context import get_user_db_session++ # Retrieve full content for each document+ for item in relevant_items:+ doc_id = item.get("metadata", {}).get("document_id")+ if not doc_id:+ continue++ # Get full document text from database+ with get_user_db_session(self.username) as db_session:+ text_doc = (+ db_session.query(LibraryTextDocument)+ .filter_by(id=doc_id)+ .first()+ )++ if text_doc and text_doc.content:+ # Replace snippet with full content+ item["content"] = text_doc.content+ item["snippet"] = (+ text_doc.content[:500] + "..."+ if len(text_doc.content) > 500+ else text_doc.content+ )+ logger.debug(+ f"Retrieved full content for document {doc_id}"+ )++ return relevant_items++ except Exception:+ logger.exception("Error retrieving full content from library")+ return relevant_items+def close(self):"""Clean up resources."""pass