Skip to content

~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.

improving logging, clean up and bug fixing

LearningCircuit78b8517fe294
diff --git a/pyproject.toml b/pyproject.toml
index 9f4cecaabc..2bf54feda5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -44,7 +44,13 @@ dependencies = [
"pydantic-settings>=2.0.0",
"toml>=0.10.2",
"platformdirs>=3.0.0",
- "dynaconf"
+ "dynaconf",
+ "requests>=2.28.0",
+ "tiktoken>=0.4.0",
+ "xmltodict>=0.13.0",
+ "lxml>=4.9.2",
+ "pdfplumber>=0.9.0",
+ "unstructured>=0.10.0",
]
[project.urls]
diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.py
index cb3eb5c1a8..688da1458d 100644
--- a/src/local_deep_research/citation_handler.py
+++ b/src/local_deep_research/citation_handler.py
@@ -50,7 +50,6 @@ class CitationHandler:
documents = self._create_documents(search_results)
formatted_sources = self._format_sources(documents)
- print(formatted_sources)
prompt = f"""Analyze the following information concerning the question and include citations using numbers in square brackets [1], [2], etc. When citing, use the source number provided at the start of each source.
Question: {query}
@@ -75,7 +74,6 @@ Provide a detailed analysis with citations and always keep URLS. Never make up s
"""Process follow-up analysis with citations."""
documents = self._create_documents(search_results, nr_of_links=nr_of_links)
formatted_sources = self._format_sources(documents)
- print(formatted_sources)
# Add fact-checking step
fact_check_prompt = f"""Analyze these sources for factual consistency:
1. Cross-reference major claims between sources
diff --git a/src/local_deep_research/config.py b/src/local_deep_research/config.py
index 0bfceaa320..79d4cd3f06 100644
--- a/src/local_deep_research/config.py
+++ b/src/local_deep_research/config.py
@@ -20,7 +20,7 @@ def get_config_dir():
from platformdirs import user_config_dir
config_dir = Path(user_config_dir("local_deep_research", "LearningCircuit"))
- print(f"Looking for config in: {config_dir}")
+ logger.info(f"Looking for config in: {config_dir}")
return config_dir
# Define config paths
CONFIG_DIR = get_config_dir() / "config"
@@ -31,9 +31,6 @@ LLM_CONFIG_FILE = CONFIG_DIR / "llm_config.py"
SEARCH_ENGINES_FILE = CONFIG_DIR / "search_engines.toml"
LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"
-print("CONFIGDIR:", CONFIG_DIR)
-print("SECRETS_FILE:", SECRETS_FILE)
-print("SETTINGS_FILE:", SETTINGS_FILE)
# Set environment variable for Dynaconf to use
diff --git a/src/local_deep_research/defaults/llm_config.py b/src/local_deep_research/defaults/llm_config.py
index 4df1925c8f..d6809d7fe3 100644
--- a/src/local_deep_research/defaults/llm_config.py
+++ b/src/local_deep_research/defaults/llm_config.py
@@ -210,7 +210,7 @@ def is_anthropic_available():
def is_openai_endpoint_available():
"""Check if OpenAI endpoint is available"""
- print(os.getenv("OPENAI_ENDPOINT_API_KEY"))
+
try:
api_key = settings.OPENAI_ENDPOINT_API_KEY
return bool(api_key)
diff --git a/src/local_deep_research/local_collections.py b/src/local_deep_research/local_collections.py
deleted file mode 100644
index 6bd2cbcb0e..0000000000
--- a/src/local_deep_research/local_collections.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# 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": "local_deep_research.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 file
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index d76ab740cf..87527b57ed 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -1,6 +1,6 @@
from typing import Dict, List, Optional, Callable
from datetime import datetime
-from .utilties.search_utilities import remove_think_tags, format_findings_to_text, print_search_results, format_links
+from .utilties.search_utilities import remove_think_tags, format_findings_to_text, format_links
import os
from .utilties.enums import KnowledgeAccumulationApproach
from .config import settings, get_llm, get_search
diff --git a/src/local_deep_research/utilties/search_utilities.py b/src/local_deep_research/utilties/search_utilities.py
index 126c9cff43..2493cf9dc2 100644
--- a/src/local_deep_research/utilties/search_utilities.py
+++ b/src/local_deep_research/utilties/search_utilities.py
@@ -3,7 +3,6 @@ import re
def remove_think_tags(text: str) -> str:
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
- print(text)
return text
@@ -17,13 +16,13 @@ def extract_links_from_search_results(search_results: list) -> list:
"""
links = []
for result in search_results:
- #print(result)
+
try:
title = result.get("title", "").strip()
url = result.get("link", "").strip()
index = result.get("index", "").strip()
- print("INDEX:",index)
+
if title and url:
links.append({"title": title, "url": url, "index": index})
except Exception:
@@ -111,5 +110,5 @@ def print_search_results(search_results):
links = extract_links_from_search_results(search_results)
if links:
formatted_text=format_links(links=links)
- print(formatted_text)
+ logger.info(formatted_text)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
index a2a5c1011c..ff003e99b7 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py
@@ -121,7 +121,7 @@ class ArXivSearchEngine(BaseSearchEngine):
return previews
except Exception as e:
- print(f"Error getting arXiv previews: {e}")
+ logger.error(f"Error getting arXiv previews: {e}")
return []
def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
@@ -138,10 +138,10 @@ class ArXivSearchEngine(BaseSearchEngine):
"""
# Check if we should get full content
if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Snippet-only mode, skipping full content retrieval")
+ logger.info("Snippet-only mode, skipping full content retrieval")
return relevant_items
- print("Getting full content for relevant arXiv papers")
+ logger.info("Getting full content for relevant arXiv papers")
results = []
pdf_count = 0 # Track number of PDFs processed
@@ -198,7 +198,7 @@ class ArXivSearchEngine(BaseSearchEngine):
if pdf_text.strip(): # Only use if we got meaningful text
result["content"] = pdf_text
result["full_content"] = pdf_text
- print(f"Successfully extracted text from PDF using PyPDF2")
+ logger.info(f"Successfully extracted text from PDF using PyPDF2")
except (ImportError, Exception) as e1:
# Fall back to pdfplumber
try:
@@ -211,20 +211,20 @@ class ArXivSearchEngine(BaseSearchEngine):
if pdf_text.strip(): # Only use if we got meaningful text
result["content"] = pdf_text
result["full_content"] = pdf_text
- print(f"Successfully extracted text from PDF using pdfplumber")
+ logger.info(f"Successfully extracted text from PDF using pdfplumber")
except (ImportError, Exception) as e2:
- print(f"PDF text extraction failed: {str(e1)}, then {str(e2)}")
- print(f"Using paper summary as content instead")
+ logger.error(f"PDF text extraction failed: {str(e1)}, then {str(e2)}")
+ logger.error(f"Using paper summary as content instead")
except Exception as e:
- print(f"Error extracting text from PDF: {e}")
- print(f"Using paper summary as content instead")
+ logger.error(f"Error extracting text from PDF: {e}")
+ logger.error(f"Using paper summary as content instead")
except Exception as e:
- print(f"Error downloading paper {paper.title}: {e}")
+ logger.error(f"Error downloading paper {paper.title}: {e}")
result["pdf_path"] = None
pdf_count -= 1 # Decrement counter if download fails
elif self.include_full_text and self.download_dir and pdf_count >= self.max_full_text:
# Reached PDF limit
- print(f"Maximum number of PDFs ({self.max_full_text}) reached. Skipping remaining PDFs.")
+ logger.info(f"Maximum number of PDFs ({self.max_full_text}) reached. Skipping remaining PDFs.")
result["content"] = paper.summary
result["full_content"] = paper.summary
@@ -242,7 +242,7 @@ class ArXivSearchEngine(BaseSearchEngine):
Returns:
List of search results
"""
- print("---Execute a search using arXiv---")
+ logger.info("---Execute a search using arXiv---")
# Use the implementation from the parent class which handles all phases
results = super().run(query)
@@ -308,12 +308,12 @@ class ArXivSearchEngine(BaseSearchEngine):
paper_path = paper.download_pdf(dirpath=self.download_dir)
result["pdf_path"] = str(paper_path)
except Exception as e:
- print(f"Error downloading paper: {e}")
+ logger.error(f"Error downloading paper: {e}")
return result
except Exception as e:
- print(f"Error getting paper details: {e}")
+ logger.error(f"Error getting paper details: {e}")
return {}
def search_by_author(self, author_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
diff --git a/src/local_deep_research/web_search_engines/full_search.py b/src/local_deep_research/web_search_engines/full_search.py
deleted file mode 100644
index 8a06eb78a3..0000000000
--- a/src/local_deep_research/web_search_engines/full_search.py
+++ /dev/null
@@ -1,254 +0,0 @@
-import justext
-from langchain_community.document_loaders import AsyncChromiumLoader
-from langchain_community.document_transformers import BeautifulSoupTransformer
-from langchain_core.language_models import BaseLLM
-from typing import List, Dict, Any, Optional, Union
-import json
-import os
-from .utilties.search_utilities import remove_think_tags
-from datetime import datetime
-from local_deep_research import config
-
-class FullSearchResults:
- """
- Enhanced web content retrieval class that works with the BaseSearchEngine architecture.
- Can be used as a wrapper around web-based search engines like DuckDuckGo and SerpAPI.
- """
-
- def __init__(
- self,
- llm: BaseLLM,
- web_search,
- output_format: str = "list",
- language: str = "English",
- max_results: int = 10,
- region: str = "wt-wt",
- time: str = "y",
- safesearch: str = "Moderate"
- ):
- """
- Initialize the full search results processor.
-
- Args:
- llm: Language model instance for relevance filtering
- web_search: Web search engine instance that provides initial results
- output_format: Format of output ('list' or other formats)
- language: Language for content processing
- max_results: Maximum number of search results
- region: Search region
- time: Time period for search results
- safesearch: Safe search setting
- """
- 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
- self.web_search = web_search
- os.environ["USER_AGENT"] = "Local Deep Research/1.0"
-
- self.bs_transformer = BeautifulSoupTransformer()
- self.tags_to_extract = ["p", "div", "span"]
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Legacy method that performs a full search in one step.
- Respects config parameters:
- - SEARCH_SNIPPETS_ONLY: If True, only returns snippets without full content
- - SKIP_RELEVANCE_FILTER: If True, returns all results without filtering
-
- Args:
- query: The search query
-
- Returns:
- List of search results with full content (unless SEARCH_SNIPPETS_ONLY is True)
- """
- # Phase 1: Get search results from the web search engine
- previews = self._get_previews(query)
- if not previews:
- return []
-
- # Phase 2: Filter URLs using LLM (unless SKIP_RELEVANCE_FILTER is True)
- if hasattr(config, 'SKIP_RELEVANCE_FILTER') and config.SKIP_RELEVANCE_FILTER:
- relevant_items = previews
- print("Skipping relevance filtering as per config")
- else:
- relevant_items = self._filter_relevant_items(previews, query)
- if not relevant_items:
- return []
-
- # Phase 3: Get full content for relevant items (unless SEARCH_SNIPPETS_ONLY is True)
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Returning snippet-only results as per config")
- return relevant_items
- else:
- results = self._get_full_content(relevant_items)
- return results
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information from the web search engine.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- try:
- # Get search results from the web search engine
- search_results = self.web_search.invoke(query)
-
- if not isinstance(search_results, list):
- print("Error: Expected search results in list format")
- return []
-
- # Return the results as previews
- return search_results
-
- except Exception as e:
- print(f"Error getting previews: {e}")
- return []
-
- def _filter_relevant_items(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:
- """
- Filter previews for relevance using LLM.
-
- Args:
- previews: List of preview dictionaries
- query: The original search query
-
- Returns:
- List of relevant preview dictionaries
- """
- # Skip filtering if disabled in config or no previews
- if not config.QUALITY_CHECK_DDG_URLS or not previews:
- return previews
-
- # Format for LLM evaluation
- 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}
-
- URLs to evaluate:
- {json.dumps(previews, indent=2)}
-
- 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)
-
- # Extract JSON array from response
- response_text = remove_think_tags(response.content)
- # Clean up response to handle potential formatting issues
- response_text = response_text.strip()
-
- # Find the first occurrence of '[' and the last occurrence of ']'
- start_idx = response_text.find('[')
- end_idx = response_text.rfind(']')
-
- if start_idx >= 0 and end_idx > start_idx:
- array_text = response_text[start_idx:end_idx+1]
- good_indices = json.loads(array_text)
-
- # Return only the results with good indices
- return [r for i, r in enumerate(previews) if i in good_indices]
- else:
- print("Could not find JSON array in response, returning all previews")
- return previews
-
- except Exception as e:
- print(f"URL filtering error: {e}")
- # Fall back to returning all previews on error
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant items by retrieving and processing web pages.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- nr_full_text = 0
-
- # Extract URLs from relevant items
- urls = [item.get("link") for item in relevant_items if item.get("link")]
-
- if not urls:
- print("\n === NO VALID LINKS ===\n")
- return relevant_items
-
- try:
- # Download the full HTML pages for filtered URLs
- loader = AsyncChromiumLoader(urls)
- html_docs = loader.load()
-
- # Process the HTML using BeautifulSoupTransformer
- full_docs = self.bs_transformer.transform_documents(
- html_docs, tags_to_extract=self.tags_to_extract
- )
-
- # Remove boilerplate from each document
- url_to_content = {}
- for doc in full_docs:
- 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 result
- results = []
- for item in relevant_items:
- new_item = item.copy()
- link = item.get("link")
- new_item["full_content"] = url_to_content.get(link, None)
- results.append(new_item)
-
- print(f"FULL SEARCH WITH FILTERED URLS - Full text retrieved: {nr_full_text}")
- return results
-
- except Exception as e:
- print(f"Error retrieving full content: {e}")
- # Return original items if full content retrieval fails
- return relevant_items
-
- def _remove_boilerplate(self, html: str) -> str:
- """
- Remove boilerplate content from HTML.
-
- Args:
- html: HTML content
-
- Returns:
- Cleaned text content
- """
- if not html or not html.strip():
- return ""
- try:
- 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
- except Exception as e:
- print(f"Error removing boilerplate: {e}")
- return html
-
- def invoke(self, query: str) -> List[Dict[str, Any]]:
- """Compatibility method for LangChain tools"""
- return self.run(query)
-
- def __call__(self, query: str) -> List[Dict[str, Any]]:
- """Make the class callable like a function"""
- return self.invoke(query)
\ No newline at end of file
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 58134d24b0..17dcfc97cf 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -53,7 +53,7 @@ class BaseSearchEngine(ABC):
List of search results with full content (if available)
"""
# Ensure we're measuring time correctly for citation tracking
- start_time = datetime.now()
+
# Step 1: Get preview information for items
previews = self._get_previews(query)
diff --git a/web_search_engines/search_engines_config.py b/web_search_engines/search_engines_config.py
deleted file mode 100644
index 1c42c1fe9a..0000000000
--- a/web_search_engines/search_engines_config.py
+++ /dev/null
@@ -1,279 +0,0 @@
-"""
-Configuration file for search engines.
-Add or modify search engines here without changing code elsewhere.
-"""
-
-# Registry of all available search engines
-SEARCH_ENGINES = {
- # Wikipedia search engine
- "wikipedia": {
- "module_path": "web_search_engines.engines.search_engine_wikipedia",
- "class_name": "WikipediaSearchEngine",
- "requires_api_key": False,
- "reliability": 0.95,
- "strengths": ["factual information", "general knowledge", "definitions",
- "historical facts", "biographies", "overview information"],
- "weaknesses": ["recent events", "specialized academic topics", "product comparisons"],
- "default_params": {
- "include_content": True
- }
- },
-
- # arXiv search engine
- "arxiv": {
- "module_path": "web_search_engines.engines.search_engine_arxiv",
- "class_name": "ArXivSearchEngine",
- "requires_api_key": False,
- "reliability": 0.9,
- "strengths": ["scientific papers", "academic research", "physics", "computer science",
- "mathematics", "statistics", "machine learning", "preprints"],
- "weaknesses": ["non-academic topics", "consumer products", "news", "general information"],
- "default_params": {
- "sort_by": "relevance",
- "sort_order": "descending"
- }
- },
-
- # medRxiv search engine
- #"medrxiv": {
- # "module_path": "web_search_engines.engines.search_engine_medrxiv",
- # "class_name": "MedRxivSearchEngine",
- # "requires_api_key": False,
- # "reliability": 0.85,
- # "strengths": ["medical preprints", "health research", "covid-19 research",
- # "clinical studies", "medical sciences", "preliminary results"],
- # "weaknesses": ["not peer-reviewed", "preliminary findings", "limited to medical research"],
- # "default_params": {
- # "sort_by": "relevance_score",
- # "sort_order": "desc",
- # "include_full_text": False,
- # "optimize_queries": True # Use LLM to optimize natural language queries
- # },
- # "requires_llm": True # Needs LLM for query optimization
- #},
- # PubMed search engine
- "pubmed": {
- "module_path": "web_search_engines.engines.search_engine_pubmed",
- "class_name": "PubMedSearchEngine",
- "requires_api_key": False, # Works without API key but with rate limits
- "api_key_env": "NCBI_API_KEY", # Optional for higher rate limits
- "reliability": 0.95,
- "strengths": ["biomedical literature", "medical research", "clinical studies",
- "life sciences", "health information", "scientific papers"],
- "weaknesses": ["non-medical topics", "very recent papers may be missing",
- "limited to published research"],
- "default_params": {
- "max_results": 20,
- "get_abstracts": True,
- "get_full_text": False, # Default to abstracts only, not full text
- "full_text_limit": 3, # Limit full text retrieval to top 3 articles when enabled
- "days_limit": None, # No default time limit
- "optimize_queries": True # Use LLM to optimize natural language queries
- },
- "requires_llm": True # Needs LLM for query optimization
- },
- # SearXNG search engine (using "API key" for instance URL)
- "searxng": {
- "module_path": "web_search_engines.engines.search_engine_searxng",
- "class_name": "SearXNGSearchEngine",
- "requires_api_key": True,
- "api_key_env": "SEARXNG_INSTANCE",
- "reliability": 0.7,
- "strengths": ["privacy-focused", "metasearch capability", "no tracking",
- "combines multiple engines", "ethical usage", "respects rate limits"],
- "weaknesses": ["requires self-hosted instance", "disabled without configuration"],
- "default_params": {
- "max_results": 15,
- "instance_url": "http://localhost:8080", # Default to localhost
- "categories": ["general"],
- "engines": None,
- "language": "en",
- "safe_search": 1,
- "time_range": None,
- "delay_between_requests": 2.0, # Respectful rate limiting
- "include_full_content": True
- },
- "supports_full_search": True
- },
- # GitHub search engine
- "github": {
- "module_path": "web_search_engines.engines.search_engine_github",
- "class_name": "GitHubSearchEngine",
- "requires_api_key": False, # Works without API key but rate limited
- #"api_key_env": "GITHUB_API_KEY",
- "reliability": 0.99,
- "strengths": ["code repositories", "software documentation", "open source projects",
- "programming issues", "developer information", "technical documentation"],
- "weaknesses": ["non-technical content", "content outside GitHub", "rate limits without API key"],
- "default_params": {
- "max_results": 15,
- "search_type": "repositories", # Options: "repositories", "code", "issues", "users"
- "include_readme": True,
- "include_issues": False
- },
- "supports_full_search": True
- },
- # DuckDuckGo search engine
- # "duckduckgo": {
- # "module_path": "web_search_engines.engines.search_engine_ddg",
- # "class_name": "DuckDuckGoSearchEngine",
- # "requires_api_key": False,
- # "reliability": 0.4,
- # "strengths": ["web search", "product information", "reviews", "recent information",
- # "news", "general queries", "broad coverage"],
- # "weaknesses": ["inconsistent due to rate limits", "not specialized for academic content"],
- # "default_params": {
- # "region": "us",
- # "safe_search": True
- # },
- # "supports_full_search": True,
- # "full_search_module": "web_search_engines.engines.full_search",
- # "full_search_class": "FullSearchResults"
- # },
-
- # SerpAPI search engine
- "serpapi": {
- "module_path": "web_search_engines.engines.search_engine_serpapi",
- "class_name": "SerpAPISearchEngine",
- "requires_api_key": True,
- "api_key_env": "SERP_API_KEY",
- "reliability": 0.6,
- "strengths": ["comprehensive web search", "product information", "reviews",
- "recent content", "news", "broad coverage"],
- "weaknesses": ["requires API key with usage limits", "not specialized for academic content"],
- "default_params": {
- "region": "us",
- "time_period": "y",
- "safe_search": True,
- "search_language": "English"
- },
- "supports_full_search": True,
- "full_search_module": "web_search_engines.engines.full_serp_search_results_old",
- "full_search_class": "FullSerpAPISearchResults"
- },
-
- # Google Programmable Search Engine
- "google_pse": {
- "module_path": "web_search_engines.engines.search_engine_google_pse",
- "class_name": "GooglePSESearchEngine",
- "requires_api_key": True,
- "api_key_env": "GOOGLE_PSE_API_KEY",
- "reliability": 0.9,
- "strengths": ["custom search scope", "high-quality results", "domain-specific search",
- "configurable search experience", "control over search index"],
- "weaknesses": ["requires API key with usage limits", "limited to 10,000 queries/day on free tier",
- "requires search engine configuration in Google Control Panel"],
- "default_params": {
- "region": "us",
- "safe_search": True,
- "search_language": "English"
- },
- "supports_full_search": True,
- "full_search_module": "web_search_engines.engines.full_search",
- "full_search_class": "FullSearchResults"
- },
-
- # Brave search engine
- "brave": {
- "module_path": "web_search_engines.engines.search_engine_brave",
- "class_name": "BraveSearchEngine",
- "requires_api_key": True,
- "api_key_env": "BRAVE_API_KEY",
- "reliability": 0.7,
- "strengths": ["privacy-focused web search", "product information", "reviews",
- "recent content", "news", "broad coverage"],
- "weaknesses": ["requires API key with usage limits", "smaller index than Google"],
- "default_params": {
- "region": "US",
- "time_period": "y",
- "safe_search": True,
- "search_language": "English"
- },
- "supports_full_search": True,
- "full_search_module": "web_search_engines.engines.full_search",
- "full_search_class": "FullSearchResults"
- },
-
- # The Guardian search engine - search seem to often provide irrelevant results.
- #"guardian": {
- # "module_path": "web_search_engines.engines.search_engine_guardian",
- # "class_name": "GuardianSearchEngine",
- # "requires_api_key": True,
- # "api_key_env": "GUARDIAN_API_KEY",
- # "reliability": 0.5,
- # "strengths": ["news articles", "current events", "opinion pieces", "journalism",
- # "UK and global news", "political analysis"],
- # "weaknesses": ["primarily focused on news", "limited historical content pre-1999"],
- # "default_params": {
- # "order_by": "relevance"
- # }
- #},
- # Wayback Machine search engine - not sure if it is usefull
- "wayback": {
- "module_path": "web_search_engines.engines.search_engine_wayback",
- "class_name": "WaybackSearchEngine",
- "requires_api_key": False,
- "reliability": 0.5,
- "strengths": ["historical web content", "archived websites", "content verification",
- "deleted or changed web pages", "website evolution tracking"],
- "weaknesses": ["limited to previously archived content", "may miss recent changes",
- "archiving quality varies"],
- "default_params": {
- "max_results": 15,
- "max_snapshots_per_url": 3,
- "closest_only": False,
- "language": "English"
- },
- "supports_full_search": True
- },
- # Meta search engine (intelligent engine selection)
- "auto": {
- "module_path": "web_search_engines.engines.meta_search_engine",
- "class_name": "MetaSearchEngine",
- "requires_api_key": False,
- "reliability": 0.85,
- "strengths": ["intelligent engine selection", "adaptable to query type", "fallback capabilities"],
- "weaknesses": ["slightly slower due to LLM analysis"],
- "default_params": {
- "use_api_key_services": True,
- "max_engines_to_try": 3
- },
- "requires_llm": True
- }
-}
-
-# Add 'auto' as an alias for 'meta'
-SEARCH_ENGINES["auto"] = SEARCH_ENGINES["auto"]
-
-# Default search engine to use if none specified
-DEFAULT_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