~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
Added local rag search
LearningCircuit53b27c3857d8
diff --git a/.gitignore b/.gitignoreindex d2faea943f..fbead17789 100644--- a/.gitignore+++ b/.gitignore@@ -48,4 +48,8 @@ report.mdlogs/# Database-research_history.db\ No newline at end of file+research_history.db++# Data+.cache\ No newline at end of filediff --git a/README.md b/README.mdindex 89b1e1680d..845933eb97 100644--- a/README.md+++ b/README.md@@ -28,15 +28,25 @@ A powerful AI-powered research assistant that performs deep, iterative analysis- Transparent data handling- 🌐 **Enhanced Search Integration**- - Wikipedia integration for factual knowledge (default)+ - **Auto-selection of search sources**: The "auto" search engine intelligently analyzes your query and selects the most appropriate search engine based on the query content+ - Wikipedia integration for factual knowledge- arXiv integration for scientific papers and academic research- DuckDuckGo integration for web searches (may experience rate limiting)- SerpAPI integration for Google search results (requires API key)- The Guardian integration for news articles and journalism (requires API key)+ - **Local RAG search for private documents** - search your own documents with vector embeddings- Full webpage content retrieval- Source filtering and validation- Configurable search parameters+- 📑 **Local Document Search (RAG)**+ - Vector embedding-based search of your local documents+ - Create custom document collections for different topics+ - Privacy-preserving - your documents stay on your machine+ - Intelligent chunking and retrieval+ - Compatible with various document formats (PDF, text, markdown, etc.)+ - Automatic integration with meta-search for unified queries+## Installation1. Clone the repository:@@ -68,7 +78,10 @@ GUARDIAN_API_KEY=your-guardian-api-key-here # For The Guardian search```## Usage-Terminal usage (not recommended): python main.py+Terminal usage:+```bash+python main.py+```### Web Interface@@ -104,90 +117,184 @@ TIME_PERIOD = "y"SAFE_SEARCH = TrueSEARCH_SNIPPETS_ONLY = False-# Choose search tool: "wiki", "arxiv", "duckduckgo", "guardian", or "serp" (serp requires API key)-search_tool = "wiki" # Change this variable to switch between search options+# Choose search tool: "wiki", "arxiv", "duckduckgo", "guardian", "serp", "local_all", or "auto"+search_tool = "auto" # "auto" will intelligently select the best search engine for your query```-### Search Engine Options--The system supports multiple search engines that can be selected by changing the `search_tool` variable in `config.py`:+## Local Document Search (RAG)-- **Wikipedia** (`wiki`): Default option. Best for general knowledge, facts, and overview information-- **arXiv** (`arxiv`): Great for scientific and academic research, accessing preprints and papers-- **DuckDuckGo** (`duckduckgo`): General web search that doesn't require an API key (Note: May experience rate limiting issues)-- **The Guardian** (`guardian`): Quality journalism and news articles (requires an API key)-- **SerpAPI** (`serp`): Google search results (requires an API key)+The system includes powerful local document search capabilities using Retrieval-Augmented Generation (RAG). This allows you to search and retrieve content from your own document collections.-> **Note:** Due to recent DuckDuckGo rate limiting issues, Wikipedia is now the default search engine.+### Setting Up Local Collections-> **Support Free Knowledge:** If you frequently use the search engines in this tool, please consider making a donation to these organizations. They provide valuable services and rely on user support to maintain their operations:-> - [Donate to Wikipedia](https://donate.wikimedia.org)-> - [Support The Guardian](https://support.theguardian.com)-> - [Support arXiv](https://arxiv.org/about/give)-> - [Donate to DuckDuckGo](https://duckduckgo.com/donations)+Create a file named `local_collections.py` in the project root directory:-#### Using arXiv Search+```python+# local_collections.py+import os+from typing import Dict, Any++# Registry of local document collections+LOCAL_COLLECTIONS = {+ # Research Papers Collection+ "research_papers": {+ "name": "Research Papers",+ "description": "Academic research papers and articles",+ "paths": [os.path.abspath("local_search_files/research_papers")], # Use absolute paths+ "enabled": True,+ "embedding_model": "all-MiniLM-L6-v2",+ "embedding_device": "cpu",+ "embedding_model_type": "sentence_transformers",+ "max_results": 20,+ "max_filtered_results": 5,+ "chunk_size": 800, # Smaller chunks for academic content+ "chunk_overlap": 150,+ "cache_dir": ".cache/local_search/research_papers"+ },++ # Personal Notes Collection+ "personal_notes": {+ "name": "Personal Notes",+ "description": "Personal notes and documents",+ "paths": [os.path.abspath("local_search_files/personal_notes")], # Use absolute paths+ "enabled": True,+ "embedding_model": "all-MiniLM-L6-v2",+ "embedding_device": "cpu",+ "embedding_model_type": "sentence_transformers",+ "max_results": 30,+ "max_filtered_results": 10,+ "chunk_size": 500, # Smaller chunks for notes+ "chunk_overlap": 100,+ "cache_dir": ".cache/local_search/personal_notes"+ }+}++# Configuration for local search integration+LOCAL_SEARCH_CONFIG = {+ # General embedding options+ "DEFAULT_EMBEDDING_MODEL": "all-MiniLM-L6-v2",+ "DEFAULT_EMBEDDING_DEVICE": "cpu", # "cpu" or "cuda" for GPU acceleration+ "DEFAULT_EMBEDDING_MODEL_TYPE": "sentence_transformers", # or "ollama"++ # Ollama settings (only used if model type is "ollama")+ # Note: You must run 'ollama pull nomic-embed-text' first if using Ollama for embeddings+ "OLLAMA_BASE_URL": "http://localhost:11434",+ "OLLAMA_EMBEDDING_MODEL": "nomic-embed-text",++ # Default indexing options+ "FORCE_REINDEX": False, # Force reindexing on startup+ "CACHE_DIR": ".cache/local_search", # Base directory for cache+}++def register_local_collections(search_engines_dict: Dict[str, Any]) -> None:+ """+ Register all enabled local collections as search engines.++ Args:+ search_engines_dict: The main search engines dictionary to update+ """+ for collection_id, collection in LOCAL_COLLECTIONS.items():+ if collection.get("enabled", True):+ # Skip if already defined (don't override)+ if collection_id in search_engines_dict:+ continue++ # Validate paths exist+ paths = collection.get("paths", [])+ valid_paths = []+ for path in paths:+ if os.path.exists(path) and os.path.isdir(path):+ valid_paths.append(path)+ else:+ print(f"Warning: Collection '{collection_id}' contains non-existent folder: {path}")++ # Log warning if no valid paths+ if not valid_paths and paths:+ print(f"Warning: Collection '{collection_id}' has no valid folders. It will be registered but won't return results.")++ # Create a search engine entry for this collection+ search_engines_dict[collection_id] = {+ "module_path": "web_search_engines.engines.search_engine_local",+ "class_name": "LocalSearchEngine",+ "requires_api_key": False,+ "reliability": 0.9, # High reliability for local documents+ "strengths": ["personal documents", "offline access",+ collection.get("description", "local documents")],+ "weaknesses": ["requires indexing", "limited to specific folders"],+ "default_params": {+ "folder_paths": collection.get("paths", []),+ "embedding_model": collection.get(+ "embedding_model",+ LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_MODEL"]+ ),+ "embedding_device": collection.get(+ "embedding_device",+ LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_DEVICE"]+ ),+ "embedding_model_type": collection.get(+ "embedding_model_type",+ LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_MODEL_TYPE"]+ ),+ "chunk_size": collection.get("chunk_size", 1000),+ "chunk_overlap": collection.get("chunk_overlap", 200),+ "cache_dir": collection.get(+ "cache_dir",+ f"{LOCAL_SEARCH_CONFIG['CACHE_DIR']}/{collection_id}"+ ),+ "max_results": collection.get("max_results", 20),+ "max_filtered_results": collection.get("max_filtered_results", 5),+ "collection_name": collection.get("name", collection_id),+ "collection_description": collection.get("description", "")+ },+ "requires_llm": True+ }+```-To use the arXiv search for scientific and academic papers:+Create the directories for your collections:+```bash+mkdir -p local_search_files/research_papers+mkdir -p local_search_files/personal_notes+```-1. Ensure you have the arXiv package installed (included in requirements.txt):- ```bash- pip install arxiv- ```+Add your documents to these folders, and the system will automatically index them and make them available for searching.-2. Update the search tool in `config.py`:- ```python- search_tool = "arxiv"- ```+### Using Local Search-3. Configure arXiv-specific settings in `config.py` if needed.+You can use local search in several ways:-### Model Options+1. **Auto-selection**: Set `search_tool = "auto"` in `config.py` and the system will automatically use your local collections when appropriate for the query.-Choose your model based on available computing power and needs:+2. **Explicit Selection**: Set `search_tool = "research_papers"` to search only that specific collection.-```python-# Local Models (via Ollama):-- "mistral" # Recommended-- "deepseek-r1:7b" # Other option+3. **Search All Local Collections**: Set `search_tool = "local_all"` to search across all your local document collections.-# Cloud Models (requires API keys):-- "gpt-4o" # OpenAI's GPT-4-- "claude-3-5-sonnet-latest" # Anthropic's Claude 3-```+4. **Query Syntax**: Use `collection:collection_name your query` to target a specific collection within a query.-## Project Structure+### Search Engine Options-- `main.py` - Main entry point and CLI interface-- `search_system.py` - Core research and analysis system-- `citation_handler.py` - Manages citations and source tracking-- `report_generator.py` - Generates comprehensive research reports-- `config.py` - Configuration settings-- `utilities.py` - Helper functions and utilities-- `web_search_engines/` - Search engine implementations:- - `search_engine_base.py` - Base class for all search engines- - `search_engine_wikipedia.py` - Wikipedia search implementation- - `search_engine_arxiv.py` - arXiv search implementation- - `search_engine_ddg.py` - DuckDuckGo search implementation- - `search_engine_guardian.py` - The Guardian search implementation- - `search_engine_serpapi.py` - SerpAPI (Google) search implementation- - `meta_search_engine.py` - Intelligent search engine selector- - `search_engines_config.py` - Configuration for all search engines+The system supports multiple search engines that can be selected by changing the `search_tool` variable in `config.py`:-## Output Files+- **Auto** (`auto`): Intelligent search engine selector that analyzes your query and chooses the most appropriate source (Wikipedia, arXiv, local collections, etc.)+- **Wikipedia** (`wiki`): Best for general knowledge, facts, and overview information+- **arXiv** (`arxiv`): Great for scientific and academic research, accessing preprints and papers+- **DuckDuckGo** (`duckduckgo`): General web search that doesn't require an API key+- **The Guardian** (`guardian`): Quality journalism and news articles (requires an API key)+- **SerpAPI** (`serp`): Google search results (requires an API key)+- **Local Collections**: Any collections defined in your `local_collections.py` file-The system generates several output files:+> **Note:** The "auto" option will intelligently select the best search engine based on your query. For example, if you ask about physics research papers, it might select arXiv or your research_papers collection, while if you ask about current events, it might select The Guardian or DuckDuckGo.-1. `report.md` - Comprehensive research report (when using detailed mode)-2. `research_outputs/formatted_output_{query}.txt` - Detailed findings and analysis-3. Cached search results and intermediate analysis (in research_outputs/)+> **Support Free Knowledge:** If you frequently use the search engines in this tool, please consider making a donation to these organizations. They provide valuable services and rely on user support to maintain their operations:+> - [Donate to Wikipedia](https://donate.wikimedia.org)+> - [Support The Guardian](https://support.theguardian.com)+> - [Support arXiv](https://arxiv.org/about/give)+> - [Donate to DuckDuckGo](https://duckduckgo.com/donations)## LicenseThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.## Acknowledgments-- Built with [Ollama](https://ollama.ai) for local AI processing- Search powered by multiple sources:- [Wikipedia](https://www.wikipedia.org/) for factual knowledge (default search engine)@@ -198,6 +305,8 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file- Built on [LangChain](https://github.com/hwchase17/langchain) framework- Uses [justext](https://github.com/miso-belica/justext) for content extraction- [Playwright](https://playwright.dev) for web content retrieval+- Uses [FAISS](https://github.com/facebookresearch/faiss) for vector similarity search+- Uses [sentence-transformers](https://github.com/UKPLab/sentence-transformers) for embeddings## Contributingdiff --git a/citation_handler.py b/citation_handler.pyindex 15db344966..1b24166f92 100644--- a/citation_handler.py+++ b/citation_handler.py@@ -55,7 +55,7 @@ Question: {query}Sources:{formatted_sources}-Provide a detailed analysis with citations and always keep URLS. Example format: "According to the research [1], ..."+Provide a detailed analysis with citations and always keep URLS. Never make up sources. Example format: "According to the research [1], ...""""response = self.llm.invoke(prompt)@@ -91,7 +91,7 @@ Provide a detailed analysis with citations and always keep URLS. Example format:else:fact_check_response = ""- prompt = f"""Using the previous knowledge and new sources, answer the question. Include citations using numbers in square brackets [1], [2], etc. When citing, use the source number provided at the start of each source. Always keep URLS. Reflect information from sources critically.+ prompt = f"""Using the previous knowledge and new sources, answer the question. Include citations using numbers in square brackets [1], [2], etc. When citing, use the source number provided at the start of each source. Reflect information from sources critically.Previous Knowledge:{previous_knowledge}@@ -100,7 +100,7 @@ Provide a detailed analysis with citations and always keep URLS. Example format:New Sources:{formatted_sources}- Reflect information from sources critically based on: {fact_check_response}.+ Reflect information from sources critically based on: {fact_check_response}. Never invent sources.Provide a detailed answer with citations. Example format: "According to [1], ...""""diff --git a/config.py b/config.pyindex 1c491965a5..1d35d1d597 100644--- a/config.py+++ b/config.py@@ -10,8 +10,8 @@ import os# Load environment variablesload_dotenv()# Choose search tool: "serp" or "duckduckgo" (serp requires API key)-search_tool = "auto" # Change this variable to switch between search tools-+#search_tool = "auto" # Change this variable to switch between search tools+search_tool = "auto"# LLM Configuration@@ -37,7 +37,7 @@ SEARCH_SNIPPETS_ONLY = FalseSKIP_RELEVANCE_FILTER = False# Search Configuration (applies to both DDG and SerpAPI)-MAX_SEARCH_RESULTS = 30+MAX_SEARCH_RESULTS = 40MAX_FILTERED_RESULTS = 5SEARCH_REGION = "us"TIME_PERIOD = "y"diff --git a/full_duck_duck_go_search_results.py b/full_duck_duck_go_search_results.pynew file mode 100644index 0000000000..0c9b0b7719--- /dev/null+++ b/full_duck_duck_go_search_results.py@@ -0,0 +1,148 @@+import justext+from langchain_community.tools import DuckDuckGoSearchResults+from langchain.document_loaders import AsyncChromiumLoader, AsyncHtmlLoader+from langchain.document_transformers import BeautifulSoupTransformer+from langchain_core.language_models import BaseLLM+from typing import List, Dict+import json, os+from utilities import remove_think_tags+from datetime import datetime+import config++class FullDuckDuckGoSearchResults:+ def __init__(+ self,+ llm: BaseLLM, # Add LLM parameter+ output_format: str = "list",+ language: str = "English",+ max_results: int = 10,+ region: str = "wt-wt",+ time: str = "y",+ safesearch: str = "Moderate",+ ):+ self.llm = llm+ self.output_format = output_format+ self.language = language+ self.max_results = max_results+ self.region = region+ self.time = time+ self.safesearch = safesearch+ os.environ["USER_AGENT"] = "Local Deep Research/1.0"++ self.ddg_search = DuckDuckGoSearchResults(+ output_format=output_format,+ max_results=self.max_results,+ region=self.region,+ time=self.time,+ safesearch=self.safesearch,+ )+ self.bs_transformer = BeautifulSoupTransformer()+ self.tags_to_extract = ["p", "div", "span"]++ def check_urls(self, results: List[Dict], query: str) -> List[Dict]:+ if not results:+ return results++ # Prepare the prompt for URL evaluation+ urls_text = "\n".join(+ [+ f"URL: {r.get('link', '')}\n"+ f"Title: {r.get('title', '')}\n"+ f"Snippet: {r.get('snippet', '')}\n"+ for r in results+ ]+ )+ print(urls_text)+ now = datetime.now()+ current_time = now.strftime("%Y-%m-%d")+ prompt = f"""ONLY Return a JSON array. The response contains no letters. Evaluate these URLs for:+ 1. Timeliness (today: {current_time})+ 2. Factual accuracy (cross-reference major claims)+ 3. Source reliability (prefer official company websites, established news outlets)+ 4. Direct relevance to query: {query}++ For each source, analyze:+ - Publication date (if available)+ - Author/organization credibility+ - Whether claims are supported by other reliable sources+ - Primary vs secondary source status++ URLs to evaluate:+ {urls_text}++ Return a JSON array of indices (0-based) for sources that meet ALL criteria.+ ONLY Return a JSON array of indices (0-based) and nothing else. No letters.+ Example response: \n[0, 2, 4]\n\n"""++ try:+ # Get LLM's evaluation+ response = self.llm.invoke(prompt)+ # print(response)+ good_indices = json.loads(remove_think_tags(response.content))++ # Return only the results with good URLs+ return [r for i, r in enumerate(results) if i in good_indices]+ except Exception as e:+ print(f"URL filtering error: {e}")+ return []++ def remove_boilerplate(self, html: str) -> str:+ if not html or not html.strip():+ return ""+ paragraphs = justext.justext(html, justext.get_stoplist(self.language))+ cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])+ return cleaned++ def run(self, query: str):+ nr_full_text = 0+ # Step 1: Get search results from DuckDuckGo+ search_results = self.ddg_search.invoke(query)+ #print(type(search_results))+ if not isinstance(search_results, list):+ raise ValueError("Expected the search results in list format.")++ # Step 2: Filter URLs using LLM+ if config.QUALITY_CHECK_DDG_URLS:+ filtered_results = self.check_urls(search_results, query)+ else:+ filtered_results = search_results++ # Extract URLs from filtered results+ urls = [result.get("link") for result in filtered_results if result.get("link")]+ print(urls)+ if not urls:+ print("\n === NO VALID LINKS ===\n")+ return []++ # Step 3: Download the full HTML pages for filtered URLs+ loader = AsyncHtmlLoader(urls)+ html_docs = loader.load()++ # Step 4: Process the HTML using BeautifulSoupTransformer+ full_docs = self.bs_transformer.transform_documents(+ html_docs, tags_to_extract=self.tags_to_extract+ )++ # Step 5: Remove boilerplate from each document+ url_to_content = {}+ for doc in full_docs:+ nr_full_text = nr_full_text + 1+ source = doc.metadata.get("source")+ if source:+ cleaned_text = self.remove_boilerplate(doc.page_content)+ url_to_content[source] = cleaned_text++ # Attach the cleaned full content to each filtered result+ for result in filtered_results:+ link = result.get("link")+ result["full_content"] = url_to_content.get(link, None)++ print("FULL SEARCH WITH FILTERED URLS")+ print("Full text retrieved: ", nr_full_text)+ return filtered_results++ def invoke(self, query: str):+ return self.run(query)++ def __call__(self, query: str):+ return self.invoke(query)diff --git a/local_collections.py b/local_collections.pynew file mode 100644index 0000000000..e8ed7b9107--- /dev/null+++ b/local_collections.py@@ -0,0 +1,141 @@+# local_collections.py+"""+Configuration file for local document collections.+Each collection functions as an independent search engine.+"""++import os+from typing import Dict, Any++# Registry of local document collections+# Each collection appears as a separate search engine in the main configuration+LOCAL_COLLECTIONS = {+ # Project Documents Collection+ "project_docs": {+ "name": "Project Documents",+ "description": "Project documentation and specifications",+ "paths": [os.path.abspath("./local_search_files/project_documents")],+ "enabled": True,+ "embedding_model": "all-MiniLM-L6-v2",+ "embedding_device": "cpu",+ "embedding_model_type": "sentence_transformers",+ "max_results": 20,+ "max_filtered_results": 5,+ "chunk_size": 1000,+ "chunk_overlap": 200,+ "cache_dir": ".cache/local_search/project_docs"+ },++ # Research Papers Collection+ "research_papers": {+ "name": "Research Papers",+ "description": "Academic research papers and articles",+ "paths": [os.path.abspath("local_search_files/research_papers")],+ "enabled": True,+ "embedding_model": "all-MiniLM-L6-v2",+ "embedding_device": "cpu",+ "embedding_model_type": "sentence_transformers",+ "max_results": 20,+ "max_filtered_results": 5,+ "chunk_size": 800, # Smaller chunks for academic content+ "chunk_overlap": 150,+ "cache_dir": ".cache/local_search/research_papers"+ },++ # Personal Notes Collection+ "personal_notes": {+ "name": "Personal Notes",+ "description": "Personal notes and documents",+ "paths": [os.path.abspath("./local_search_files/personal_notes")],+ "enabled": True,+ "embedding_model": "all-MiniLM-L6-v2",+ "embedding_device": "cpu",+ "embedding_model_type": "sentence_transformers",+ "max_results": 30,+ "max_filtered_results": 10,+ "chunk_size": 500, # Smaller chunks for notes+ "chunk_overlap": 100,+ "cache_dir": ".cache/local_search/personal_notes"+ }+}++# Configuration for local search integration+LOCAL_SEARCH_CONFIG = {+ # General embedding options+ "DEFAULT_EMBEDDING_MODEL": "all-MiniLM-L6-v2",+ "DEFAULT_EMBEDDING_DEVICE": "cpu", # "cpu" or "cuda" for GPU acceleration+ "DEFAULT_EMBEDDING_MODEL_TYPE": "sentence_transformers", # or "ollama"++ # Ollama settings (only used if model type is "ollama")+ # Note: You must run 'ollama pull nomic-embed-text' first if using Ollama for embeddings+ "OLLAMA_BASE_URL": "http://localhost:11434",+ "OLLAMA_EMBEDDING_MODEL": "nomic-embed-text",++ # Default indexing options+ "FORCE_REINDEX": True, # Force reindexing on startup+ "CACHE_DIR": ".cache/local_search", # Base directory for cache+}++def register_local_collections(search_engines_dict: Dict[str, Any]) -> None:+ """+ Register all enabled local collections as search engines.++ Args:+ search_engines_dict: The main search engines dictionary to update+ """+ for collection_id, collection in LOCAL_COLLECTIONS.items():+ print(collection_id, collection)+ if collection.get("enabled", True):+ # Skip if already defined (don't override)+ if collection_id in search_engines_dict:+ continue++ # Validate paths exist+ paths = collection.get("paths", [])+ valid_paths = []+ for path in paths:+ if os.path.exists(path) and os.path.isdir(path):+ valid_paths.append(path)+ else:+ print(f"Warning: Collection '{collection_id}' contains non-existent folder: {path}")++ # Log warning if no valid paths+ if not valid_paths and paths:+ print(f"Warning: Collection '{collection_id}' has no valid folders. It will be registered but won't return results.")++ # Create a search engine entry for this collection+ search_engines_dict[collection_id] = {+ "module_path": "web_search_engines.engines.search_engine_local",+ "class_name": "LocalSearchEngine",+ "requires_api_key": False,+ "reliability": 0.9, # High reliability for local documents+ "strengths": ["personal documents", "offline access",+ collection.get("description", "local documents")],+ "weaknesses": ["requires indexing", "limited to specific folders"],+ "default_params": {+ "folder_paths": collection.get("paths", []),+ "embedding_model": collection.get(+ "embedding_model",+ LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_MODEL"]+ ),+ "embedding_device": collection.get(+ "embedding_device",+ LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_DEVICE"]+ ),+ "embedding_model_type": collection.get(+ "embedding_model_type",+ LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_MODEL_TYPE"]+ ),+ "chunk_size": collection.get("chunk_size", 1000),+ "chunk_overlap": collection.get("chunk_overlap", 200),+ "cache_dir": collection.get(+ "cache_dir",+ f"{LOCAL_SEARCH_CONFIG['CACHE_DIR']}/{collection_id}"+ ),+ "max_results": collection.get("max_results", 20),+ "max_filtered_results": collection.get("max_filtered_results", 5),+ "collection_name": collection.get("name", collection_id),+ "collection_description": collection.get("description", "")+ },+ "requires_llm": True+ }\ No newline at end of filediff --git a/requirements.txt b/requirements.txtindex ab046f71f5..781f47d1ec 100644--- a/requirements.txt+++ b/requirements.txt@@ -19,4 +19,7 @@ sqlalchemy>=1.4.23google-search-resultswikipediaarxiv>=1.4.3-PyPDF2>=2.0.0 # Optional - for extracting text from PDFs if needed\ No newline at end of file+PyPDF2>=2.0.0 # Optional - for extracting text from PDFs if needed++sentence-transformers # local search+faiss-cpu # faiss-gpu\ No newline at end of filediff --git a/test/download_stuff_for_local_test.py b/test/download_stuff_for_local_test.pynew file mode 100644index 0000000000..92211e0e0d--- /dev/null+++ b/test/download_stuff_for_local_test.py@@ -0,0 +1,29 @@+import arxiv+import os+max_results = 50+# Search for papers and limit to 400+search = arxiv.Search(+ query="machine learning",+ max_results=50+)+client = arxiv.Client()+from datasets import load_dataset++# Download papers+os.makedirs("./../local_search_files/research_papers", exist_ok=True)+for i, result in enumerate(client.results(search)):+ try:+ filename = f"./../local_search_files/research_papers/paper_{i}.pdf"+ result.download_pdf(filename=filename)+ print(f"Downloaded {i+1}/{max_results}: {result.title}")+ except Exception as e:+ print(f"Error downloading {result.title}: {e}")+++wiki = load_dataset("wikipedia", "20220301.en", split=f"train[:{max_results}]", trust_remote_code=True)+# Save to files+import os+os.makedirs("./../local_search_files/wiki_sample", exist_ok=True)+for i, article in enumerate(wiki):+ with open(f"./../local_search_files/wiki_sample/article_{i}.txt", "w") as f:+ f.write(article["title"] + "\n\n" + article["text"])\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_local.py b/web_search_engines/engines/search_engine_local.pynew file mode 100644index 0000000000..7fde606edd--- /dev/null+++ b/web_search_engines/engines/search_engine_local.py@@ -0,0 +1,901 @@+from typing import Dict, List, Any, Optional, Tuple, Union+import os+import json+import hashlib+import time+from datetime import datetime+from pathlib import Path+import tiktoken+import logging+import re+import pickle++from langchain_core.language_models import BaseLLM+from langchain_community.document_loaders import (+ PyPDFLoader,+ TextLoader,+ UnstructuredMarkdownLoader,+ UnstructuredWordDocumentLoader,+ CSVLoader,+ UnstructuredExcelLoader,+ DirectoryLoader+)+from langchain_community.document_loaders.base import BaseLoader+from langchain_text_splitters import RecursiveCharacterTextSplitter+from langchain_community.vectorstores import FAISS+from langchain_community.embeddings import (+ HuggingFaceEmbeddings,+ OllamaEmbeddings,+ SentenceTransformerEmbeddings+)++from web_search_engines.search_engine_base import BaseSearchEngine+import config++# Setup logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++class LocalEmbeddingManager:+ """Handles embedding generation and storage for local document search"""++ def __init__(+ self,+ embedding_model: str = "all-MiniLM-L6-v2",+ embedding_device: str = "cpu",+ embedding_model_type: str = "sentence_transformers", # or 'ollama'+ ollama_base_url: Optional[str] = None,+ chunk_size: int = 1000,+ chunk_overlap: int = 200,+ cache_dir: str = ".cache/local_search",+ ):+ """+ Initialize the embedding manager for local document search.++ Args:+ embedding_model: Name of the embedding model to use+ embedding_device: Device to run embeddings on ('cpu' or 'cuda')+ embedding_model_type: Type of embedding model ('sentence_transformers' or 'ollama')+ ollama_base_url: Base URL for Ollama API if using ollama embeddings+ chunk_size: Size of text chunks for splitting documents+ chunk_overlap: Overlap between chunks+ cache_dir: Directory to store embedding cache and index+ """++ self.embedding_model = embedding_model+ self.embedding_device = embedding_device+ self.embedding_model_type = embedding_model_type+ self.ollama_base_url = ollama_base_url+ self.chunk_size = chunk_size+ self.chunk_overlap = chunk_overlap+ self.cache_dir = Path(cache_dir)++ # Create cache directory if it doesn't exist+ self.cache_dir.mkdir(parents=True, exist_ok=True)++ # Initialize the embedding model+ self._embeddings = None++ # Initialize the text splitter+ self.text_splitter = RecursiveCharacterTextSplitter(+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap+ )++ # Track indexed folders and their metadata+ self.indexed_folders = self._load_indexed_folders()++ # Vector store cache+ self.vector_stores = {}+ @property+ def embeddings(self):+ """+ Lazily initialize embeddings when first accessed.+ This allows the LocalEmbeddingManager to be created without+ immediately loading models, which is helpful when no local search is performed.+ """+ if self._embeddings is None:+ logger.info("Initializing embeddings on first use")+ self._embeddings = self._initialize_embeddings()+ return self._embeddings++ def _initialize_embeddings(self):+ """Initialize the embedding model based on configuration"""+ try:+ if self.embedding_model_type == "ollama":+ # Use Ollama for embeddings+ if not self.ollama_base_url:+ self.ollama_base_url = "http://localhost:11434"++ logger.info(f"Initializing Ollama embeddings with model {self.embedding_model}")+ return OllamaEmbeddings(+ model=self.embedding_model,+ base_url=self.ollama_base_url+ )+ else:+ # Default: Use SentenceTransformers/HuggingFace+ logger.info(f"Initializing SentenceTransformerEmbeddings with model {self.embedding_model}")+ return SentenceTransformerEmbeddings(+ model_name=self.embedding_model,+ model_kwargs={"device": self.embedding_device}+ )+ except Exception as e:+ logger.error(f"Error initializing embeddings: {e}")+ logger.warning("Falling back to HuggingFaceEmbeddings with all-MiniLM-L6-v2")+ return HuggingFaceEmbeddings(+ model_name="sentence-transformers/all-MiniLM-L6-v2"+ )+ 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()++ # Check if vector store exists and is up to date+ if vector_store_path.exists() and not self._check_folders_modified():+ logger.info(f"Loading existing vector store from {vector_store_path}")+ try:+ vector_store = FAISS.load_local(+ str(vector_store_path),+ self.embeddings,+ allow_dangerous_deserialization=True+ )++ # Add this code to show document count+ doc_count = len(vector_store.index_to_docstore_id)+ logger.info(f"Loaded index with {doc_count} document chunks")++ return vector_store+ except Exception as e:+ logger.error(f"Error loading vector store: {e}")+ logger.info("Will create a new vector store")++ # Create a new vector store+ return self._create_vector_store()+ def _load_indexed_folders(self) -> Dict[str, Dict[str, Any]]:+ """Load metadata about indexed folders from disk"""+ index_metadata_path = self.cache_dir / "index_metadata.json"++ if index_metadata_path.exists():+ try:+ with open(index_metadata_path, "r") as f:+ return json.load(f)+ except Exception as e:+ logger.error(f"Error loading index metadata: {e}")++ return {}++ def _save_indexed_folders(self):+ """Save metadata about indexed folders to disk"""+ index_metadata_path = self.cache_dir / "index_metadata.json"++ try:+ with open(index_metadata_path, "w") as f:+ json.dump(self.indexed_folders, f, indent=2)+ except Exception as e:+ logger.error(f"Error saving index metadata: {e}")++ def _get_folder_hash(self, folder_path: str) -> str:+ """Generate a hash for a folder based on its path"""+ return hashlib.md5(folder_path.encode()).hexdigest()++ def _get_index_path(self, folder_path: str) -> Path:+ """Get the path where the index for a specific folder should be stored"""+ folder_hash = self._get_folder_hash(folder_path)+ return self.cache_dir / f"index_{folder_hash}"++ def _check_folder_modified(self, folder_path: str) -> bool:+ """Check if a folder has been modified since it was last indexed"""+ folder_path = Path(folder_path)++ if not folder_path.exists() or not folder_path.is_dir():+ return False++ folder_hash = self._get_folder_hash(str(folder_path))++ # If folder has never been indexed, it's considered modified+ if folder_hash not in self.indexed_folders:+ return True++ last_indexed = self.indexed_folders[folder_hash].get("last_indexed", 0)++ # Check if any file in the folder has been modified since last indexing+ for root, _, files in os.walk(folder_path):+ for file in files:+ file_path = Path(root) / file+ if file_path.stat().st_mtime > last_indexed:+ return True++ return False++ def get_file_loader(self, file_path: str) -> Optional[BaseLoader]:+ """Get an appropriate document loader for a file based on its extension"""+ file_path = Path(file_path)+ extension = file_path.suffix.lower()++ try:+ if extension == ".pdf":+ return PyPDFLoader(str(file_path))+ elif extension == ".txt":+ return TextLoader(str(file_path))+ elif extension in [".md", ".markdown"]:+ return UnstructuredMarkdownLoader(str(file_path))+ elif extension in [".doc", ".docx"]:+ return UnstructuredWordDocumentLoader(str(file_path))+ elif extension == ".csv":+ return CSVLoader(str(file_path))+ elif extension in [".xls", ".xlsx"]:+ return UnstructuredExcelLoader(str(file_path))+ else:+ # Try the text loader as a fallback for unknown extensions+ logger.warning(f"Unknown file extension for {file_path}, trying TextLoader")+ return TextLoader(str(file_path), encoding="utf-8")+ except Exception as e:+ logger.error(f"Error creating loader for {file_path}: {e}")+ return None++ def index_folder(self, folder_path: str, force_reindex: bool = False) -> bool:+ """+ Index all documents in a folder for vector search.++ Args:+ folder_path: Path to the folder to index+ force_reindex: Whether to force reindexing even if unchanged++ Returns:+ bool: True if indexing was successful, False otherwise+ """+ folder_path = Path(folder_path)++ # Validate folder+ if not folder_path.exists():+ logger.error(f"Folder not found: {folder_path}")+ return False++ if not folder_path.is_dir():+ logger.error(f"Path is not a directory: {folder_path}")+ return False++ folder_str = str(folder_path)+ folder_hash = self._get_folder_hash(folder_str)+ index_path = self._get_index_path(folder_str)++ # Check if folder needs to be reindexed+ if not force_reindex and not self._check_folder_modified(folder_str):+ logger.info(f"Folder {folder_path} has not been modified since last indexing")++ # Load the vector store from disk if not already loaded+ if folder_hash not in self.vector_stores:+ try:+ self.vector_stores[folder_hash] = FAISS.load_local(+ str(index_path),+ self.embeddings,+ allow_dangerous_deserialization=True+ )+ logger.info(f"Loaded index for {folder_path} from disk")+ except Exception as e:+ logger.error(f"Error loading index for {folder_path}: {e}")+ # If loading fails, force reindexing+ force_reindex = True+ else:+ logger.info(f"Using cached index for {folder_path}")++ # If no reindexing is needed and vector store loaded successfully+ if not force_reindex and folder_hash in self.vector_stores:+ return True++ logger.info(f"Indexing folder: {folder_path}")+ start_time = time.time()++ # Find documents to index+ all_docs = []+ file_count = 0+ error_count = 0++ for root, _, files in os.walk(folder_path):+ for file in files:+ file_path = Path(root) / file++ # Skip hidden files and directories+ if file.startswith(".") or any(part.startswith(".") for part in file_path.parts):+ continue++ # Get a loader for this file+ loader = self.get_file_loader(str(file_path))++ if loader:+ try:+ # Load the document+ docs = loader.load()++ # Add source path metadata+ for doc in docs:+ doc.metadata["source"] = str(file_path)+ doc.metadata["filename"] = file++ all_docs.extend(docs)+ file_count += 1+ except Exception as e:+ logger.error(f"Error loading {file_path}: {e}")+ error_count += 1++ if not all_docs:+ logger.warning(f"No documents found in {folder_path} or all documents failed to load")+ return False++ # Split documents into chunks+ logger.info(f"Splitting {len(all_docs)} documents into chunks")+ splits = self.text_splitter.split_documents(all_docs)+ logger.info(f"Created {len(splits)} chunks from {file_count} files")++ # Create vector store+ logger.info(f"Creating vector store with {len(splits)} chunks")+ vector_store = FAISS.from_documents(splits, self.embeddings)++ # Save the vector store to disk+ logger.info(f"Saving index to {index_path}")+ vector_store.save_local(str(index_path))++ # Update cache+ self.vector_stores[folder_hash] = vector_store++ # Update metadata+ self.indexed_folders[folder_hash] = {+ "path": folder_str,+ "last_indexed": time.time(),+ "file_count": file_count,+ "chunk_count": len(splits),+ "error_count": error_count,+ "embedding_model": self.embedding_model,+ "chunk_size": self.chunk_size,+ "chunk_overlap": self.chunk_overlap+ }++ # Save updated metadata+ self._save_indexed_folders()++ elapsed_time = time.time() - start_time+ logger.info(f"Indexed {file_count} files in {elapsed_time:.2f} seconds")++ return True++ def search(+ self,+ query: str,+ folder_paths: List[str],+ limit: int = 10,+ score_threshold: float = 0.0,+ ) -> List[Dict[str, Any]]:+ """+ Search for documents relevant to a query across specified folders.++ Args:+ query: The search query+ folder_paths: List of folder paths to search in+ limit: Maximum number of results to return+ score_threshold: Minimum similarity score threshold++ Returns:+ List of results with document content and metadata+ """+ # Add detailed debugging for each folder+ for folder_path in folder_paths:+ folder_hash = self._get_folder_hash(folder_path)+ index_path = self._get_index_path(folder_path)++ logger.info(f"Diagnostic for {folder_path}:")+ logger.info(f" - Folder hash: {folder_hash}")+ logger.info(f" - Index path: {index_path}")+ logger.info(f" - Index exists on disk: {index_path.exists()}")+ logger.info(f" - Is in indexed_folders: {folder_hash in self.indexed_folders}")++ if folder_hash in self.indexed_folders:+ meta = self.indexed_folders[folder_hash]+ logger.info(f" - Metadata: file_count={meta.get('file_count', 0)}, chunk_count={meta.get('chunk_count', 0)}")++ # Validate folders exist+ valid_folder_paths = []+ for path in folder_paths:+ if os.path.exists(path) and os.path.isdir(path):+ valid_folder_paths.append(path)+ else:+ logger.warning(f"Skipping non-existent folder in search: {path}")++ # If no valid folders, return empty results+ if not valid_folder_paths:+ logger.warning(f"No valid folders to search among: {folder_paths}")+ return []++ all_results = []++ for folder_path in valid_folder_paths:+ folder_hash = self._get_folder_hash(folder_path)++ # Skip folders that haven't been indexed+ if folder_hash not in self.indexed_folders:+ logger.warning(f"Folder {folder_path} has not been indexed")+ continue++ # Make sure the vector store is loaded+ if folder_hash not in self.vector_stores:+ index_path = self._get_index_path(folder_path)+ try:+ self.vector_stores[folder_hash] = FAISS.load_local(+ str(index_path),+ self.embeddings,+ allow_dangerous_deserialization=True+ )+ except Exception as e:+ logger.error(f"Error loading index for {folder_path}: {e}")+ continue++ # Search in this folder+ vector_store = self.vector_stores[folder_hash]++ try:+ docs_with_scores = vector_store.similarity_search_with_score(query, k=limit)++ for doc, score in docs_with_scores:+ # Convert score from distance to similarity (lower distance = higher similarity)+ # FAISS cosine distance is in [0, 2], where 0 is identical and 2 is opposite+ # Convert to a similarity score in [0, 1]+ similarity = 1.0 - (score / 2.0)++ # Skip results below the threshold+ if similarity < score_threshold:+ continue++ result = {+ "content": doc.page_content,+ "metadata": doc.metadata,+ "similarity": similarity,+ "folder": folder_path+ }++ all_results.append(result)+ except Exception as e:+ logger.error(f"Error searching in {folder_path}: {e}")++ # Sort by similarity (highest first)+ all_results.sort(key=lambda x: x["similarity"], reverse=True)++ # Limit to the requested number+ return all_results[:limit]++ def clear_cache(self):+ """Clear all cached vector stores from memory (not disk)"""+ self.vector_stores.clear()++ def get_indexed_folders_info(self) -> List[Dict[str, Any]]:+ """Get information about all indexed folders"""+ info = []++ for folder_hash, metadata in self.indexed_folders.items():+ folder_info = metadata.copy()++ # Add formatted last indexed time+ if "last_indexed" in folder_info:+ folder_info["last_indexed_formatted"] = datetime.fromtimestamp(+ folder_info["last_indexed"]+ ).strftime("%Y-%m-%d %H:%M:%S")++ # Check if index file exists+ index_path = self._get_index_path(folder_info["path"])+ folder_info["index_exists"] = index_path.exists()++ info.append(folder_info)++ return info+++class LocalSearchEngine(BaseSearchEngine):+ """Local document search engine with two-phase retrieval"""++ def __init__(+ self,+ folder_paths: List[str],+ llm: Optional[BaseLLM] = None,+ max_results: int = 10,+ max_filtered_results: Optional[int] = None,+ embedding_model: str = "all-MiniLM-L6-v2",+ embedding_device: str = "cpu",+ embedding_model_type: str = "sentence_transformers",+ ollama_base_url: Optional[str] = None,+ force_reindex: bool = False,+ chunk_size: int = 1000,+ chunk_overlap: int = 200,+ cache_dir: str = ".cache/local_search",+ collections: Optional[Dict[str, Dict[str, Any]]] = None,+ ):+ """+ Initialize the local search engine.++ Args:+ folder_paths: List of folder paths to search in+ llm: Language model for relevance filtering+ max_results: Maximum number of results to return+ max_filtered_results: Maximum results after filtering+ embedding_model: Name of the embedding model to use+ embedding_device: Device to run embeddings on ('cpu' or 'cuda')+ embedding_model_type: Type of embedding model+ ollama_base_url: Base URL for Ollama API+ force_reindex: Whether to force reindexing+ chunk_size: Size of text chunks for splitting documents+ chunk_overlap: Overlap between chunks+ cache_dir: Directory to store embedding cache and index+ collections: Dictionary of named collections with paths and descriptions+ """+ # Initialize the base search engine+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)++ # Validate folder paths+ self.folder_paths = folder_paths+ self.valid_folder_paths = []+ for path in folder_paths:+ if os.path.exists(path) and os.path.isdir(path):+ self.valid_folder_paths.append(path)+ else:+ logger.warning(f"Folder not found or is not a directory: {path}")++ # If no valid folders, log a clear message+ if not self.valid_folder_paths and folder_paths:+ logger.warning(f"No valid folders found among: {folder_paths}")+ logger.warning("This search engine will return no results until valid folders are configured")++ self.max_results = max_results+ self.collections = collections or {"default": {"paths": folder_paths, "description": "Default collection"}}++ # Initialize the embedding manager with only valid folders+ self.embedding_manager = LocalEmbeddingManager(+ embedding_model=embedding_model,+ embedding_device=embedding_device,+ embedding_model_type=embedding_model_type,+ ollama_base_url=ollama_base_url,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ cache_dir=cache_dir+ )++ # Index all folders+ self._index_folders(force_reindex)++ def _index_folders(self, force_reindex: bool = False):+ """Index all valid configured folders"""+ indexed = []+ failed = []+ skipped = []++ # Keep track of invalid folders+ for folder in self.folder_paths:+ if folder not in self.valid_folder_paths:+ skipped.append(folder)+ continue++ success = self.embedding_manager.index_folder(folder, force_reindex)+ if success:+ indexed.append(folder)+ else:+ failed.append(folder)++ if indexed:+ logger.info(f"Successfully indexed {len(indexed)} folders: {', '.join(indexed)}")++ if failed:+ logger.warning(f"Failed to index {len(failed)} folders: {', '.join(failed)}")++ if skipped:+ logger.warning(f"Skipped {len(skipped)} invalid folders: {', '.join(skipped)}")++ def _get_previews(self, query: str, collection_names: Optional[List[str]] = None) -> List[Dict[str, Any]]:+ """+ Get preview information for documents matching the query.++ Args:+ query: The search query+ collection_names: Specific collections to search within (if None, search all)++ Returns:+ List of preview dictionaries+ """+ # Determine which collections to search+ if collection_names:+ # Search only in specified collections+ collections_to_search = {name: self.collections[name] for name in collection_names+ if name in self.collections}+ if not collections_to_search:+ logger.warning(f"No valid collections found among: {collection_names}")+ return []+ else:+ # Search in all collections+ collections_to_search = self.collections++ # Extract all folder paths from the collections to search+ search_paths = []+ for collection_config in collections_to_search.values():+ if "paths" in collection_config:+ search_paths.extend(collection_config["paths"])++ logger.info(f"Searching local documents in collections: {list(collections_to_search.keys())}")++ # Filter out invalid paths+ valid_search_paths = [path for path in search_paths if path in self.valid_folder_paths]++ if not valid_search_paths:+ logger.warning(f"No valid folders to search in collections: {list(collections_to_search.keys())}")+ return []++ # Search across the valid selected folders+ raw_results = self.embedding_manager.search(+ query=query,+ folder_paths=valid_search_paths,+ limit=self.max_results,+ score_threshold=0.1 # Skip very low relevance results+ )++ if not raw_results:+ logger.info(f"No local documents found for query: {query}")+ return []++ # Convert to preview format+ previews = []+ for i, result in enumerate(raw_results):+ # Create a unique ID+ result_id = f"local-{i}-{hashlib.md5(result['content'][:50].encode()).hexdigest()}"++ # Extract filename and path+ source_path = result['metadata'].get('source', 'Unknown')+ filename = result['metadata'].get('filename', os.path.basename(source_path))++ # Create preview snippet (first ~200 chars of content)+ snippet = result['content'][:200] + "..." if len(result['content']) > 200 else result['content']++ # Determine which collection this document belongs to+ collection_name = "Unknown"+ folder_path = result['folder']+ for name, collection in self.collections.items():+ if any(folder_path.startswith(path) for path in collection.get("paths", [])):+ collection_name = name+ break++ # Format the preview+ preview = {+ "id": result_id,+ "title": filename,+ "snippet": snippet,+ "link": source_path,+ "similarity": result['similarity'],+ "folder": folder_path,+ "collection": collection_name,+ "collection_description": self.collections.get(collection_name, {}).get("description", ""),+ "_full_content": result['content'], # Store full content for later+ "_metadata": result['metadata'] # Store metadata for later+ }++ previews.append(preview)++ logger.info(f"Found {len(previews)} local document matches")+ return previews++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant documents.+ For local search, the full content is already available.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Check if we should add full content+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ logger.info("Snippet-only mode, skipping full content addition")+ return relevant_items++ # For local search, we already have the full content+ results = []+ for item in relevant_items:+ # Create a copy with full content+ result = item.copy()++ # Add full content if we have it+ if "_full_content" in item:+ result["content"] = item["_full_content"]+ result["full_content"] = item["_full_content"]++ # Remove temporary fields+ if "_full_content" in result:+ del result["_full_content"]++ # Add metadata if we have it+ if "_metadata" in item:+ result["document_metadata"] = item["_metadata"]++ # Remove temporary fields+ if "_metadata" in result:+ del result["_metadata"]++ results.append(result)++ return results++ def run(self, query: str, collection_names: Optional[List[str]] = None) -> List[Dict[str, Any]]:+ """+ Execute a search using the two-phase approach.++ Args:+ query: The search query+ collection_names: Specific collections to search within (if None, search all)++ Returns:+ List of search result dictionaries with full content+ """+ logger.info(f"---Execute a search using Local Documents---")++ # Check if we have any special collection parameters in the query+ collection_prefix = "collection:"+ remaining_query = query+ specified_collections = []++ # Parse query for collection specifications like "collection:research_papers query terms"+ query_parts = query.split()+ for part in query_parts:+ if part.lower().startswith(collection_prefix):+ collection_name = part[len(collection_prefix):].strip()+ if collection_name in self.collections:+ specified_collections.append(collection_name)+ # Remove this part from the query+ remaining_query = remaining_query.replace(part, "", 1).strip()++ # If collections were specified in the query, they override the parameter+ if specified_collections:+ collection_names = specified_collections+ query = remaining_query++ # Phase 1: Get previews (with collection filtering)+ previews = self._get_previews(query, collection_names)++ if not previews:+ return []++ # Phase 2: Filter for relevance+ relevant_items = self._filter_for_relevance(previews, query)++ if not relevant_items:+ return []++ # Phase 3: Get full content for relevant items+ if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:+ print("Returning snippet-only results as per config")+ results = relevant_items+ else:+ results = self._get_full_content(relevant_items)++ # Clean up temporary data+ self.embedding_manager.clear_cache()++ return results++ def get_collections_info(self) -> List[Dict[str, Any]]:+ """+ Get information about all collections, including indexing status.++ Returns:+ List of collection information dictionaries+ """+ collections_info = []++ for name, collection in self.collections.items():+ paths = collection.get("paths", [])+ description = collection.get("description", "")++ # Get indexing information for each path+ paths_info = []+ for path in paths:+ # Check if folder exists+ exists = os.path.exists(path) and os.path.isdir(path)++ # Check if folder is indexed+ folder_hash = self.embedding_manager._get_folder_hash(path)+ indexed = folder_hash in self.embedding_manager.indexed_folders++ # Get index details if available+ index_info = {}+ if indexed:+ index_info = self.embedding_manager.indexed_folders[folder_hash].copy()++ paths_info.append({+ "path": path,+ "exists": exists,+ "indexed": indexed,+ "index_info": index_info+ })++ collections_info.append({+ "name": name,+ "description": description,+ "paths": paths,+ "paths_info": paths_info,+ "document_count": sum(info.get("index_info", {}).get("file_count", 0) for info in paths_info),+ "chunk_count": sum(info.get("index_info", {}).get("chunk_count", 0) for info in paths_info),+ "all_indexed": all(info["indexed"] for info in paths_info if info["exists"])+ })++ return collections_info++ def reindex_collection(self, collection_name: str) -> bool:+ """+ Reindex a specific collection.++ Args:+ collection_name: Name of the collection to reindex++ Returns:+ True if reindexing was successful, False otherwise+ """+ if collection_name not in self.collections:+ logger.error(f"Collection '{collection_name}' not found")+ return False++ paths = self.collections[collection_name].get("paths", [])+ success = True++ for path in paths:+ if not self.embedding_manager.index_folder(path, force_reindex=True):+ success = False++ return success++ @classmethod+ def from_config(cls, config_dict: Dict[str, Any], llm: Optional[BaseLLM] = None) -> "LocalSearchEngine":+ """+ Create a LocalSearchEngine instance from a configuration dictionary.++ Args:+ config_dict: Configuration dictionary+ llm: Language model for relevance filtering++ Returns:+ Initialized LocalSearchEngine instance+ """+ # Required parameters+ folder_paths = []+ collections = config_dict.get("collections", {})++ # Extract all folder paths from collections+ for collection_config in collections.values():+ if "paths" in collection_config:+ folder_paths.extend(collection_config["paths"])++ # Fall back to folder_paths if no collections defined+ if not folder_paths:+ folder_paths = config_dict.get("folder_paths", [])+ # Create a default collection if using folder_paths+ if folder_paths:+ collections = {"default": {"paths": folder_paths, "description": "Default collection"}}++ # Optional parameters with defaults+ max_results = config_dict.get("max_results", 10)+ max_filtered_results = config_dict.get("max_filtered_results")+ embedding_model = config_dict.get("embedding_model", "all-MiniLM-L6-v2")+ embedding_device = config_dict.get("embedding_device", "cpu")+ embedding_model_type = config_dict.get("embedding_model_type", "sentence_transformers")+ ollama_base_url = config_dict.get("ollama_base_url")+ force_reindex = config_dict.get("force_reindex", False)+ chunk_size = config_dict.get("chunk_size", 1000)+ chunk_overlap = config_dict.get("chunk_overlap", 200)+ cache_dir = config_dict.get("cache_dir", ".cache/local_search")++ return cls(+ folder_paths=folder_paths,+ collections=collections,+ llm=llm,+ max_results=max_results,+ max_filtered_results=max_filtered_results,+ embedding_model=embedding_model,+ embedding_device=embedding_device,+ embedding_model_type=embedding_model_type,+ ollama_base_url=ollama_base_url,+ force_reindex=force_reindex,+ chunk_size=chunk_size,+ chunk_overlap=chunk_overlap,+ cache_dir=cache_dir+ )\ No newline at end of filediff --git a/web_search_engines/engines/search_engine_local_all.py b/web_search_engines/engines/search_engine_local_all.pynew file mode 100644index 0000000000..e62dbe7718--- /dev/null+++ b/web_search_engines/engines/search_engine_local_all.py@@ -0,0 +1,153 @@+"""+Search engine that searches across all local collections+"""++import logging+from typing import Dict, List, Any, Optional+from langchain_core.language_models import BaseLLM++from web_search_engines.search_engine_base import BaseSearchEngine+from web_search_engines.search_engine_factory import create_search_engine+import config++# Setup logging+logger = logging.getLogger(__name__)++class LocalAllSearchEngine(BaseSearchEngine):+ """+ Search engine that searches across all local document collections.+ Acts as a meta search engine specifically for local collections.+ """++ def __init__(+ self,+ llm: Optional[BaseLLM] = None,+ max_results: int = 10,+ max_filtered_results: Optional[int] = None,+ **kwargs+ ):+ """+ Initialize the local all-collections search engine.++ Args:+ llm: Language model for relevance filtering+ max_results: Maximum number of search results+ max_filtered_results: Maximum results after filtering+ **kwargs: Additional parameters passed to LocalSearchEngine instances+ """+ # Initialize the base search engine+ super().__init__(llm=llm, max_filtered_results=max_filtered_results)++ self.max_results = max_results++ # Find all local collection search engines+ self.local_engines = {}+ try:+ from local_collections import LOCAL_COLLECTIONS++ for collection_id, collection in LOCAL_COLLECTIONS.items():+ if not collection.get("enabled", True):+ continue++ # Create a search engine for this collection+ try:+ engine = create_search_engine(+ collection_id,+ llm=llm,+ max_filtered_results=max_filtered_results+ )++ if engine:+ self.local_engines[collection_id] = {+ "engine": engine,+ "name": collection.get("name", collection_id),+ "description": collection.get("description", "")+ }+ except Exception as e:+ logger.error(f"Error creating search engine for collection '{collection_id}': {e}")+ except ImportError:+ logger.warning("No local collections configuration found")++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """+ Get preview information for documents from all local collections.++ Args:+ query: The search query++ Returns:+ List of preview dictionaries+ """+ logger.info(f"Searching across all local collections for query: {query}")++ all_previews = []++ # Get previews from each local search engine+ for collection_id, engine_info in self.local_engines.items():+ engine = engine_info["engine"]+ try:+ # Get previews from this engine+ previews = engine._get_previews(query)++ # Add collection info to each preview+ for preview in previews:+ preview["collection_id"] = collection_id+ preview["collection_name"] = engine_info["name"]+ preview["collection_description"] = engine_info["description"]++ all_previews.extend(previews)+ except Exception as e:+ logger.error(f"Error searching collection '{collection_id}': {e}")++ if not all_previews:+ logger.info(f"No local documents found for query: {query}")+ return []++ # Sort by similarity score if available+ all_previews.sort(+ key=lambda x: float(x.get("similarity", 0)),+ reverse=True+ )++ # Limit to max_results+ return all_previews[:self.max_results]++ def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """+ Get full content for the relevant documents.+ Delegates to the appropriate collection's search engine.++ Args:+ relevant_items: List of relevant preview dictionaries++ Returns:+ List of result dictionaries with full content+ """+ # Group items by collection+ items_by_collection = {}+ for item in relevant_items:+ collection_id = item.get("collection_id")+ if collection_id and collection_id in self.local_engines:+ if collection_id not in items_by_collection:+ items_by_collection[collection_id] = []+ items_by_collection[collection_id].append(item)++ # Process each collection's items with its own engine+ all_results = []+ for collection_id, items in items_by_collection.items():+ engine = self.local_engines[collection_id]["engine"]+ try:+ results = engine._get_full_content(items)+ all_results.extend(results)+ except Exception as e:+ logger.error(f"Error getting full content from collection '{collection_id}': {e}")+ # Fall back to returning the items without full content+ all_results.extend(items)++ # Add any items that weren't processed+ processed_ids = set(item["id"] for item in all_results)+ for item in relevant_items:+ if item["id"] not in processed_ids:+ all_results.append(item)++ return all_resultsdiff --git a/web_search_engines/search_engine_base.py b/web_search_engines/search_engine_base.pyindex f197bcfe52..e1d5444c40 100644--- a/web_search_engines/search_engine_base.py+++ b/web_search_engines/search_engine_base.py@@ -101,7 +101,7 @@ class BaseSearchEngine(ABC):prompt = f"""Analyze these search results and provide a ranked list of the most relevant ones.IMPORTANT: Evaluate and rank based on these criteria (in order of importance):-1. [MOST IMPORTANT] Timeliness - current/recent information as of {current_time}+1. Timeliness - current/recent information as of {current_time}2. Direct relevance to query: "{query}"3. Source reliability (prefer official sources, established websites)4. Factual accuracy (cross-reference major claims)diff --git a/web_search_engines/search_engines_config.py b/web_search_engines/search_engines_config.pyindex c453745f6d..6b862c89c0 100644--- a/web_search_engines/search_engines_config.py+++ b/web_search_engines/search_engines_config.py@@ -108,3 +108,33 @@ SEARCH_ENGINES["auto"] = SEARCH_ENGINES["auto"]# Default search engine to use if none specifiedDEFAULT_SEARCH_ENGINE = "wikipedia"+++# Import local collections+try:+ from local_collections import register_local_collections++ # Register all enabled local collections as search engines+ register_local_collections(SEARCH_ENGINES)++ print(f"Registered local document collections as search engines")+except ImportError:+ print("No local collections configuration found. Local document search is disabled.")++# Optionally, also register a "local_all" search engine that searches all collections+# This is useful when users want to search across all their local collections+SEARCH_ENGINES["local_all"] = {+ "module_path": "web_search_engines.engines.search_engine_local_all",+ "class_name": "LocalAllSearchEngine",+ "requires_api_key": False,+ "reliability": 0.85,+ "strengths": ["searches all local collections", "personal documents", "offline access"],+ "weaknesses": ["may return too many results", "requires indexing"],+ "default_params": {},+ "requires_llm": True+}++# Ensure the meta search engine is still available at the end+meta_config = SEARCH_ENGINES["auto"]+del SEARCH_ENGINES["auto"]+SEARCH_ENGINES["auto"] = meta_config