~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
Reorganize the `config.py` file.
Daniel Petti8085f9bd3da3
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.pyindex a2de1d5c35..0d4e11e064 100644--- a/src/local_deep_research/__init__.py+++ b/src/local_deep_research/__init__.py@@ -7,7 +7,16 @@ and multiple search engines integration.__version__ = "0.1.0"-from .config import get_llm, get_search+# Import API functions+from .api import (+ analyze_documents,+ generate_report,+ get_available_collections,+ get_available_search_engines,+ quick_summary,+)+from .config.llm_config import get_llm+from .config.search_config import get_searchfrom .report_generator import IntegratedReportGenerator# Import main components@@ -16,13 +25,9 @@ from .search_system import AdvancedSearchSystem# Initialize configuration on module importfrom .utilties.setup_utils import setup_user_directories-# Import API functions-from .api import quick_summary, generate_report, analyze_documents-from .api import get_available_search_engines, get_available_collections-# Export it__all__ = [- "AdvancedSearchSystem",+ "AdvancedSearchSystem","IntegratedReportGenerator","get_llm","get_search",@@ -30,6 +35,5 @@ __all__ = ["generate_report","analyze_documents","get_available_search_engines",- "get_available_collections"+ "get_available_collections",]-diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 5561ed6c03..d6f53e630f 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -3,18 +3,21 @@ API module for Local Deep Research.Provides programmatic access to search and research capabilities."""-from typing import Dict, List, Optional, Union, Any, Callableimport loggingimport os-import traceback+from typing import Any, Callable, Dict, Optional+import toml-from ..search_system import AdvancedSearchSystem++from ..config.llm_config import get_llm+from ..config.search_config import get_searchfrom ..report_generator import IntegratedReportGenerator-from ..config import get_llm, get_search, settings+from ..search_system import AdvancedSearchSystemfrom ..utilties.search_utilities import remove_think_tagslogger = logging.getLogger(__name__)+def quick_summary(query: str,search_tool: Optional[str] = None,@@ -30,7 +33,7 @@ def quick_summary() -> Dict[str, Any]:"""Generate a quick research summary for a given query.-+Args:query: The research query to analyzesearch_tool: Search engine to use (auto, wikipedia, arxiv, etc.). If None, uses default@@ -43,7 +46,7 @@ def quick_summary(safe_search: Whether to enable safe searchtemperature: LLM temperature for generationprogress_callback: Optional callback function to receive progress updates-+Returns:Dictionary containing the research results with keys:- 'summary': The generated summary text@@ -52,40 +55,41 @@ def quick_summary(- 'questions': Questions generated during research"""logger.info(f"Generating quick summary for query: {query}")-# Get language model with custom temperaturellm = get_llm(temperature=temperature)-+# Create search system with custom parameterssystem = AdvancedSearchSystem()-+# Override default settings with user-provided values- system.max_iterations = iterations+ system.max_iterations = iterationssystem.questions_per_iteration = questions_per_iterationsystem.model = llm # Ensure the model is directly attached to the system-+# Set the search engine if specifiedif search_tool:search_engine = get_search(search_tool)if search_engine:system.search = search_engineelse:- logger.warning(f"Could not create search engine '{search_tool}', using default.")-+ logger.warning(+ f"Could not create search engine '{search_tool}', using default."+ )+# Set progress callback if providedif progress_callback:system.set_progress_callback(progress_callback)-+# Perform the search and analysisresults = system.analyze_topic(query)-+# Extract the summary from the current knowledgeif results and "current_knowledge" in results:summary = results["current_knowledge"]else:summary = "Unable to generate summary for the query."-+# Prepare the return valuereturn {"summary": summary,@@ -93,7 +97,7 @@ def quick_summary("iterations": results.get("iterations", 0),"questions": results.get("questions", {}),"formatted_findings": results.get("formatted_findings", ""),- "sources": results.get("all_links_of_system", [])+ "sources": results.get("all_links_of_system", []),}@@ -114,7 +118,7 @@ def generate_report() -> Dict[str, Any]:"""Generate a comprehensive, structured research report for a given query.-+Args:query: The research query to analyzesearch_tool: Search engine to use (auto, wikipedia, arxiv, etc.). If None, uses default@@ -129,26 +133,25 @@ def generate_report(temperature: LLM temperature for generationoutput_file: Optional path to save report markdown fileprogress_callback: Optional callback function to receive progress updates-+Returns:Dictionary containing the research report with keys:- 'content': The full report content in markdown format- 'metadata': Report metadata including generated timestamp and query"""logger.info(f"Generating comprehensive research report for query: {query}")-# Get language model with custom temperaturellm = get_llm(temperature=temperature)-+# Create search system with custom parameterssystem = AdvancedSearchSystem()-+# Override default settings with user-provided valuessystem.max_iterations = iterationssystem.questions_per_iteration = questions_per_iterationsystem.model = llm # Ensure the model is directly attached to the system-+# Set the search engine if specifiedif search_tool:search_engine = get_search(@@ -158,35 +161,38 @@ def generate_report(max_filtered_results=max_filtered_results,region=region,time_period=time_period,- safe_search=safe_search+ safe_search=safe_search,)if search_engine:system.search = search_engineelse:- logger.warning(f"Could not create search engine '{search_tool}', using default.")-+ logger.warning(+ f"Could not create search engine '{search_tool}', using default."+ )+# Set progress callback if providedif progress_callback:system.set_progress_callback(progress_callback)-+# Perform the initial researchinitial_findings = system.analyze_topic(query)-+# Generate the structured report- report_generator = IntegratedReportGenerator(searches_per_section=searches_per_section)+ report_generator = IntegratedReportGenerator(+ searches_per_section=searches_per_section+ )report_generator.model = llm # Ensure the model is set on the report generator tooreport = report_generator.generate_report(initial_findings, query)-+# Save report to file if path is providedif output_file and report and "content" in report:- with open(output_file, "w", encoding="utf-8") as f:- f.write(report["content"])- logger.info(f"Report saved to {output_file}")- report["file_path"] = output_file+ with open(output_file, "w", encoding="utf-8") as f:+ f.write(report["content"])+ logger.info(f"Report saved to {output_file}")+ report["file_path"] = output_filereturn report-def analyze_documents(query: str,collection_name: str,@@ -197,7 +203,7 @@ def analyze_documents() -> Dict[str, Any]:"""Search and analyze documents in a specific local collection.-+Args:query: The search querycollection_name: Name of the local document collection to search@@ -205,58 +211,63 @@ def analyze_documents(temperature: LLM temperature for summary generationforce_reindex: Whether to force reindexing the collectionoutput_file: Optional path to save analysis results to a file-+Returns:Dictionary containing:- 'summary': Summary of the findings- 'documents': List of matching documents with content and metadata"""- logger.info(f"Analyzing documents in collection '{collection_name}' for query: {query}")-+ logger.info(+ f"Analyzing documents in collection '{collection_name}' for query: {query}"+ )# Get language model with custom temperaturellm = get_llm(temperature=temperature)-+# Get search engine for the specified collectionsearch = get_search(collection_name, llm_instance=llm)-+if not search:return {"summary": f"Error: Collection '{collection_name}' not found or not properly configured.",- "documents": []+ "documents": [],}-+# Set max resultssearch.max_results = max_results-+# Force reindex if requested- if force_reindex and hasattr(search, 'embedding_manager'):- for folder_path in search.folder_paths:- search.embedding_manager.index_folder(folder_path, force_reindex=True)+ if force_reindex and hasattr(search, "embedding_manager"):+ for folder_path in search.folder_paths:+ search.embedding_manager.index_folder(folder_path, force_reindex=True)# Perform the searchresults = search.run(query)-+if not results:return {"summary": f"No documents found in collection '{collection_name}' for query: '{query}'",- "documents": []+ "documents": [],}-+# Get LLM to generate a summary of the results- docs_text = "\n\n".join([f"Document {i+1}: {doc.get('content', doc.get('snippet', ''))[:1000]}"- for i, doc in enumerate(results[:5])]) # Limit to first 5 docs and 1000 chars each-+ docs_text = "\n\n".join(+ [+ f"Document {i + 1}:" f" {doc.get('content', doc.get('snippet', ''))[:1000]}"+ for i, doc in enumerate(results[:5])+ ]+ ) # Limit to first 5 docs and 1000 chars each+summary_prompt = f"""Analyze these document excerpts related to the query: "{query}"-+{docs_text}-+Provide a concise summary of the key information found in these documents related to the query."""-+summary_response = llm.invoke(summary_prompt)- if hasattr(summary_response, 'content'):+ if hasattr(summary_response, "content"):summary = remove_think_tags(summary_response.content)else:summary = str(summary_response)@@ -266,38 +277,42 @@ def analyze_documents("summary": summary,"documents": results,"collection": collection_name,- "document_count": len(results)+ "document_count": len(results),}-+# Save to file if requestedif output_file:- with open(output_file, "w", encoding="utf-8") as f:- f.write(f"# Document Analysis: {query}\n\n")- f.write(f"## Summary\n\n{summary}\n\n")- f.write(f"## Documents Found: {len(results)}\n\n")-- for i, doc in enumerate(results):- f.write(f"### Document {i+1}: {doc.get('title', 'Untitled')}\n\n")- f.write(f"**Source:** {doc.get('link', 'Unknown')}\n\n")- f.write(f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n")- f.write("---\n\n")-- analysis_result["file_path"] = output_file- logger.info(f"Analysis saved to {output_file}")+ with open(output_file, "w", encoding="utf-8") as f:+ f.write(f"# Document Analysis: {query}\n\n")+ f.write(f"## Summary\n\n{summary}\n\n")+ f.write(f"## Documents Found: {len(results)}\n\n")++ for i, doc in enumerate(results):+ f.write(f"### Document {i + 1}:" f" {doc.get('title', 'Untitled')}\n\n")+ f.write(f"**Source:** {doc.get('link', 'Unknown')}\n\n")+ f.write(+ f"**Content:**\n\n{doc.get('content', doc.get('snippet', 'No content available'))[:1000]}...\n\n"+ )+ f.write("---\n\n")++ analysis_result["file_path"] = output_file+ logger.info(f"Analysis saved to {output_file}")return analysis_result+def get_available_search_engines() -> Dict[str, str]:"""Get a dictionary of available search engines.-+Returns:Dictionary mapping engine names to descriptions"""from ..web_search_engines.search_engine_factory import get_available_engines+engines = get_available_engines()-+# Add some descriptions for common enginesdescriptions = {"auto": "Automatic selection based on query type",@@ -306,25 +321,24 @@ def get_available_search_engines() -> Dict[str, str]:"pubmed": "Medical and biomedical literature","semantic_scholar": "Academic papers across all fields","github": "Code repositories and technical documentation",- "local_all": "All local document collections"+ "local_all": "All local document collections",}-+return {engine: descriptions.get(engine, "Search engine") for engine in engines}def get_available_collections() -> Dict[str, Dict[str, Any]]:"""Get a dictionary of available local document collections.-+Returns:Dictionary mapping collection names to their configuration"""+ from ..config.config_files import LOCAL_COLLECTIONS_FILE- from ..config import LOCAL_COLLECTIONS_FILE-if os.path.exists(LOCAL_COLLECTIONS_FILE):- collections = toml.load(LOCAL_COLLECTIONS_FILE)- return collections+ collections = toml.load(LOCAL_COLLECTIONS_FILE)+ return collectionsreturn {}diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.pyindex c0a7e4a381..e907bc43ea 100644--- a/src/local_deep_research/citation_handler.py+++ b/src/local_deep_research/citation_handler.py@@ -4,7 +4,7 @@ from typing import Any, Dict, List, Unionfrom langchain_core.documents import Document-from .config import settings+from .config.config_files import settingsfrom .utilties.search_utilities import remove_think_tagsdiff --git a/src/local_deep_research/config.py b/src/local_deep_research/config.pydeleted file mode 100644index 08a7c5f630..0000000000--- a/src/local_deep_research/config.py+++ /dev/null@@ -1,592 +0,0 @@-# local_deep_research/config.py-import logging-import os-from pathlib import Path--from dynaconf import Dynaconf-from platformdirs import user_documents_dir-from langchain_anthropic import ChatAnthropic-from langchain_community.llms import VLLM-from langchain_ollama import ChatOllama-from langchain_openai import ChatOpenAI-from .utilties.search_utilities import remove_think_tags--# Setup logging-logger = logging.getLogger(__name__)-from dotenv import load_dotenv-import platform--# Valid provider options-VALID_PROVIDERS = [- "ollama",- "openai",- "anthropic",- "vllm",- "openai_endpoint",- "lmstudio",- "llamacpp",- "none",-]--# Get config directory-def get_config_dir():--- if platform.system() == "Windows":- # Windows: Use Documents directory- from platformdirs import user_documents_dir-- config_dir = (- Path(user_documents_dir()) / "LearningCircuit" / "local-deep-research"- )- else:- # Linux/Mac: Use standard config directory- from platformdirs import user_config_dir-- config_dir = Path(user_config_dir("local_deep_research", "LearningCircuit"))-- logger.info(f"Looking for config in: {config_dir}")- return config_dir---# Define config paths-CONFIG_DIR = get_config_dir() / "config"-CONFIG_DIR.mkdir(parents=True, exist_ok=True)-SETTINGS_FILE = CONFIG_DIR / "settings.toml"-SECRETS_FILE = CONFIG_DIR / ".secrets.toml"-SEARCH_ENGINES_FILE = CONFIG_DIR / "search_engines.toml"--LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"---env_file = CONFIG_DIR / ".env"--if env_file.exists():- logger.info(f"Loading environment variables from: {env_file}")- load_dotenv(dotenv_path=env_file)-else:- logger.warning(f"Warning: .env file not found at {env_file}. Trying secondary location.")- env_file_secondary = get_config_dir() / ".env"- if env_file_secondary.exists():- get_config_dir() / "config"- logger.info(f"Loading environment variables from: {env_file_secondary}")- load_dotenv(dotenv_path=env_file_secondary)- else:- logger.warning(f"Warning: .env file also not found at {env_file_secondary}.")---# Set environment variable for Dynaconf to use-docs_base = Path(user_documents_dir()) / "local_deep_research"-os.environ["DOCS_DIR"] = str(docs_base)--# Expose get_search function-def get_search(search_tool=None):- """- Helper function to get search engine- """-- # Use specified tool or default from settings- tool = search_tool or settings.search.tool- logger.info(f"Search tool is: {tool}")-- # Import here to avoid circular imports- from .web_search_engines.search_engine_factory import (- get_search as factory_get_search,- )-- # Get search parameters- params = {- "search_tool": tool,- "llm_instance": get_llm(),- "max_results": settings.search.max_results,- "region": settings.search.region,- "time_period": settings.search.time_period,- "safe_search": settings.search.safe_search,- "search_snippets_only": settings.search.snippets_only,- "search_language": settings.search.search_language,- "max_filtered_results": settings.search.max_filtered_results,- }- logger.info(f"Search config params: {params}")- # Create and return search engine- return factory_get_search(**params)---def init_config_files():- """Initialize config files if they don't exist"""- import os- import platform- import shutil-- # Ensure CONFIG_DIR exists with explicit creation- os.makedirs(CONFIG_DIR, exist_ok=True)-- # Get default files path with more reliable approach for Windows- if platform.system() == "Windows":- # Use a more reliable method on Windows- from pkg_resources import resource_filename-- try:- defaults_dir = Path(resource_filename("local_deep_research", "defaults"))- logger.info(f"Using pkg_resources for Windows: {defaults_dir}")-- # Create settings.toml if it doesn't exist (with explicit Windows paths)- settings_file = os.path.join(CONFIG_DIR, "settings.toml")- default_settings = os.path.join(defaults_dir, "main.toml")- if not os.path.exists(settings_file) and os.path.exists(default_settings):- shutil.copyfile(default_settings, settings_file)- logger.info(f"Created settings.toml at {settings_file}")-- # Create local_collections.toml if it doesn't exist- collections_file = os.path.join(CONFIG_DIR, "local_collections.toml")- default_collections = os.path.join(defaults_dir, "local_collections.toml")- if not os.path.exists(collections_file) and os.path.exists(- default_collections- ):- shutil.copyfile(default_collections, collections_file)- logger.info(f"Created local_collections.toml at {collections_file}")-- # Create search_engines.toml if it doesn't exist- search_engines_file = os.path.join(CONFIG_DIR, "search_engines.toml")- default_engines = os.path.join(defaults_dir, "search_engines.toml")- if not os.path.exists(search_engines_file) and os.path.exists(- default_engines- ):- shutil.copyfile(default_engines, search_engines_file)- logger.info(f"Created search_engines.toml at {search_engines_file}")-- # Create .env.template if it doesn't exist- env_template_file = CONFIG_DIR / ".env.template"- if not env_template_file.exists():- shutil.copy(defaults_dir / ".env.template", env_template_file)- logger.info(f"Created .env.template at {env_template_file}")-- # Optionally create an empty .env file if it doesn't exist- env_file = CONFIG_DIR / ".env"- if not env_file.exists():- with open(env_file, "w") as f:- f.write("# Add your environment variables here\n")- logger.info(f"Created empty .env file at {env_file}")- except Exception as e:- logger.error(f"Error initializing Windows config files: {e}")- else:- """Initialize config files if they don't exist"""- import shutil- from importlib.resources import files-- # Get default files path- try:- try:- defaults_dir = files("local_deep_research.defaults")- except ModuleNotFoundError:- defaults_dir = files("src.local_deep_research.defaults")- except ImportError:- # Fallback for older Python versions- from pkg_resources import resource_filename-- defaults_dir = Path(resource_filename("local_deep_research", "defaults"))-- # Create settings.toml if it doesn't exist- settings_file = CONFIG_DIR / "settings.toml"- if not settings_file.exists():- shutil.copy(defaults_dir / "main.toml", settings_file)- logger.info(f"Created settings.toml at {settings_file}")-- # Create local_collections.toml if it doesn't exist- collections_file = CONFIG_DIR / "local_collections.toml"- if not collections_file.exists():- shutil.copy(defaults_dir / "local_collections.toml", collections_file)- logger.info(f"Created local_collections.toml at {collections_file}")-- # Create search_engines.toml if it doesn't exist- search_engines_file = CONFIG_DIR / "search_engines.toml"- if not search_engines_file.exists():- shutil.copy(defaults_dir / "search_engines.toml", search_engines_file)- logger.info(f"Created search_engines.toml at {search_engines_file}")- env_template_file = CONFIG_DIR / ".env.template"- if not env_template_file.exists():- shutil.copy(defaults_dir / ".env.template", env_template_file)- logger.info(f"Created .env.template at {env_template_file}")-- # Optionally create an empty .env file if it doesn't exist- env_file = CONFIG_DIR / ".env"- if not env_file.exists():- with open(env_file, "w") as f:- f.write("# Add your environment variables here\n")- logger.info(f"Created empty .env file at {env_file}")- secrets_file = CONFIG_DIR / ".secrets.toml"- if not secrets_file.exists():- with open(secrets_file, "w") as f:- f.write(- """- # ANTHROPIC_API_KEY = "your-api-key-here"- # OPENAI_API_KEY = "your-openai-key-here"- # GOOGLE_API_KEY = "your-google-key-here"- # SERP_API_KEY = "your-api-key-here"- # GUARDIAN_API_KEY = "your-api-key-here"- # GOOGLE_PSE_API_KEY = "your-google-api-key-here"- # GOOGLE_PSE_ENGINE_ID = "your-programmable-search-engine-id-here"- """- )--# ================================-# LLM FUNCTIONS-# ================================--def get_llm(model_name=None, temperature=None, provider=None):- """- Get LLM instance based on model name and provider.-- Args:- model_name: Name of the model to use (if None, uses settings.llm.model)- temperature: Model temperature (if None, uses settings.llm.temperature)- provider: Provider to use (if None, uses settings.llm.provider)-- Returns:- A LangChain LLM instance with automatic think-tag removal- """- # Use settings values for parameters if not provided- if model_name is None:- model_name = settings.llm.model-- if temperature is None:- temperature = settings.llm.temperature-- if provider is None:- provider = settings.llm.provider.lower()- if provider not in VALID_PROVIDERS:- logger.error(f"Invalid provider in settings: {provider}")- raise ValueError(- f"Invalid provider: {provider}. Must be one of: {VALID_PROVIDERS}"- )-- # Common parameters for all models- common_params = {- "temperature": temperature,- "max_tokens": settings.llm.max_tokens,- }-- # Handle different providers- if provider == "anthropic":- api_key_name = 'ANTHROPIC_API_KEY'- api_key = settings.get(api_key_name, '')- if not api_key:- api_key = os.getenv(api_key_name)- if not api_key:- api_key = os.getenv("LDR_" + api_key_name)- if not api_key:- logger.warning(- "ANTHROPIC_API_KEY not found. Falling back to default model."- )- return get_fallback_model(temperature)-- llm = ChatAnthropic(- model=model_name, anthropic_api_key=api_key, **common_params- )- return wrap_llm_without_think_tags(llm)-- elif provider == "openai":- api_key_name = 'OPENAI_API_KEY'- api_key = settings.get(api_key_name, '')- if not api_key:- api_key = os.getenv(api_key_name)- if not api_key:- api_key = os.getenv("LDR_" + api_key_name)- if not api_key:- logger.warning("OPENAI_API_KEY not found. Falling back to default model.")- return get_fallback_model(temperature)-- llm = ChatOpenAI(model=model_name, api_key=api_key, **common_params)- return wrap_llm_without_think_tags(llm)-- elif provider == "openai_endpoint":- api_key_name = 'OPENAI_ENDPOINT_API_KEY'- api_key = settings.get(api_key_name, '')- if not api_key:- api_key = os.getenv(api_key_name)- if not api_key:- api_key = os.getenv("LDR_" + api_key_name)- if not api_key:- logger.warning(- "OPENAI_ENDPOINT_API_KEY not found. Falling back to default model."- )- return get_fallback_model(temperature)-- # Get endpoint URL from settings- openai_endpoint_url = settings.llm.openai_endpoint_url-- llm = ChatOpenAI(- model=model_name,- api_key=api_key,- openai_api_base=openai_endpoint_url,- **common_params,- )- return wrap_llm_without_think_tags(llm)-- elif provider == "vllm":- try:- llm = VLLM(- model=model_name,- trust_remote_code=True,- max_new_tokens=128,- top_k=10,- top_p=0.95,- temperature=temperature,- )- return wrap_llm_without_think_tags(llm)- except Exception as e:- logger.error(f"Error loading VLLM model: {e}")- logger.warning("Falling back.")- return get_fallback_model(temperature)-- elif provider == "ollama":- try:- # Use the configurable Ollama base URL- base_url = settings.get('OLLAMA_BASE_URL', settings.llm.get('ollama_base_url', 'http://localhost:11434'))- llm = ChatOllama(model=model_name, base_url=base_url, **common_params)- return wrap_llm_without_think_tags(llm)- except Exception as e:- logger.error(f"Error loading Ollama model: {e}")- return get_fallback_model(temperature)-- elif provider == "lmstudio":- # LM Studio supports OpenAI API format, so we can use ChatOpenAI directly- lmstudio_url = settings.llm.get('lmstudio_url', "http://localhost:1234")-- llm = ChatOpenAI(- model=model_name,- api_key="lm-studio", # LM Studio doesn't require a real API key- base_url=f"{lmstudio_url}/v1", # Use the configured URL with /v1 endpoint- temperature=temperature,- max_tokens=settings.llm.max_tokens- )- return wrap_llm_without_think_tags(llm)-- elif provider == "llamacpp":- # Import LlamaCpp- from langchain_community.llms import LlamaCpp-- # Get LlamaCpp model path from settings- model_path = settings.llm.get('llamacpp_model_path', "")- if not model_path:- logger.error("llamacpp_model_path not set in settings")- raise ValueError("llamacpp_model_path not set in settings.toml")-- # Get additional LlamaCpp parameters- n_gpu_layers = settings.llm.get('llamacpp_n_gpu_layers', 1)- n_batch = settings.llm.get('llamacpp_n_batch', 512)- f16_kv = settings.llm.get('llamacpp_f16_kv', True)-- # Create LlamaCpp instance- llm = LlamaCpp(- model_path=model_path,- temperature=temperature,- max_tokens=settings.llm.max_tokens,- n_gpu_layers=n_gpu_layers,- n_batch=n_batch,- f16_kv=f16_kv,- verbose=True- )- return wrap_llm_without_think_tags(llm)-- else:- return wrap_llm_without_think_tags(get_fallback_model(temperature))---def get_fallback_model(temperature=None):- """Create a dummy model for when no providers are available"""- from langchain_community.llms.fake import FakeListLLM-- return FakeListLLM(- responses=[- "No language models are available. Please install Ollama or set up API keys."- ]- )---# ================================-# COMPATIBILITY FUNCTIONS-# ================================--def wrap_llm_without_think_tags(llm):- """Create a wrapper class that processes LLM outputs with remove_think_tags"""--- class ProcessingLLMWrapper:- def __init__(self, base_llm):- self.base_llm = base_llm-- def invoke(self, *args, **kwargs):- response = self.base_llm.invoke(*args, **kwargs)-- # Process the response content if it has a content attribute- if hasattr(response, 'content'):- response.content = remove_think_tags(response.content)- elif isinstance(response, str):- response = remove_think_tags(response)-- return response-- # Pass through any other attributes to the base LLM- def __getattr__(self, name):- return getattr(self.base_llm, name)-- return ProcessingLLMWrapper(llm)--def get_available_provider_types():- """Return available model providers"""- providers = {}-- if is_ollama_available():- providers["ollama"] = "Ollama (local models)"-- if is_openai_available():- providers["openai"] = "OpenAI API"-- if is_anthropic_available():- providers["anthropic"] = "Anthropic API"-- if is_openai_endpoint_available():- providers["openai_endpoint"] = "OpenAI-compatible Endpoint"-- if is_lmstudio_available():- providers["lmstudio"] = "LM Studio (local models)"-- if is_llamacpp_available():- providers["llamacpp"] = "LlamaCpp (local models)"-- # Check for VLLM capability- try:- import torch # noqa: F401- import transformers # noqa: F401-- providers["vllm"] = "VLLM (local models)"- except ImportError:- pass-- # Default fallback- if not providers:- providers["none"] = "No model providers available"-- return providers---# ================================-# HELPER FUNCTIONS-# ================================---def is_openai_available():- """Check if OpenAI is available"""- try:- api_key = settings.get("OPENAI_API_KEY", "")- if not api_key:- api_key = os.getenv("OPENAI_API_KEY")- return bool(api_key)- except Exception:- return False---def is_anthropic_available():- """Check if Anthropic is available"""- try:- api_key = settings.get("ANTHROPIC_API_KEY", "")- if not api_key:- api_key = os.getenv("ANTHROPIC_API_KEY")- return bool(api_key)- except Exception:- return False---def is_openai_endpoint_available():- """Check if OpenAI endpoint is available"""- try:- api_key = settings.get("OPENAI_ENDPOINT_API_KEY", "")- if not api_key:- api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")- return bool(api_key)- except Exception:- return False---def is_ollama_available():- """Check if Ollama is running"""- try:- import requests-- base_url = settings.get(- "OLLAMA_BASE_URL",- settings.llm.get("ollama_base_url", "http://localhost:11434"),- )- response = requests.get(f"{base_url}/api/tags", timeout=1.0)- return response.status_code == 200- except Exception:- return False---def is_vllm_available():- """Check if VLLM capability is available"""- try:- import torch # noqa: F401- import transformers # noqa: F401-- return True- except ImportError:- return False---def is_lmstudio_available():- """Check if LM Studio is available"""- try:- import requests-- lmstudio_url = settings.llm.get("lmstudio_url", "http://localhost:1234")- # LM Studio typically uses OpenAI-compatible endpoints- response = requests.get(f"{lmstudio_url}/v1/models", timeout=1.0)- return response.status_code == 200- except Exception:- return False---def is_llamacpp_available():- """Check if LlamaCpp is available and configured"""- try:- from langchain_community.llms import LlamaCpp # noqa: F401-- model_path = settings.llm.get("llamacpp_model_path", "")- return bool(model_path) and os.path.exists(model_path)- except Exception:- return False---def get_available_providers():- """Get dictionary of available providers"""- return get_available_provider_types()---# Initialize config files on import-init_config_files()--# Use an absolute path to your .secrets.toml for testing-secrets_file = Path(SECRETS_FILE)--settings = Dynaconf(- settings_files=[- str(SETTINGS_FILE),- str(LOCAL_COLLECTIONS_FILE),- str(SEARCH_ENGINES_FILE),- ],- secrets=str(SECRETS_FILE),- env_prefix="LDR",- load_dotenv=True,- envvar_prefix="LDR",- env_file=str(CONFIG_DIR / ".env"),-)--# Log which providers are available-AVAILABLE_PROVIDERS = get_available_providers()-logger.info(f"Available providers: {list(AVAILABLE_PROVIDERS.keys())}")--# Check if selected provider is available-selected_provider = settings.llm.provider.lower()-if selected_provider not in AVAILABLE_PROVIDERS and selected_provider != "none":- logger.warning(f"Selected provider {selected_provider} is not available.")diff --git a/src/local_deep_research/config/__init__.py b/src/local_deep_research/config/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/src/local_deep_research/config/config_files.py b/src/local_deep_research/config/config_files.pynew file mode 100644index 0000000000..2f3e7cf5bf--- /dev/null+++ b/src/local_deep_research/config/config_files.py@@ -0,0 +1,194 @@+import logging+import os+import platform+from pathlib import Path++from dotenv import load_dotenv+from dynaconf import Dynaconf+from platformdirs import user_documents_dir++# Setup logging+logger = logging.getLogger(__name__)+++def get_config_dir():++ if platform.system() == "Windows":+ # Windows: Use Documents directory+ from platformdirs import user_documents_dir++ config_dir = (+ Path(user_documents_dir()) / "LearningCircuit" / "local-deep-research"+ )+ else:+ # Linux/Mac: Use standard config directory+ from platformdirs import user_config_dir++ config_dir = Path(user_config_dir("local_deep_research", "LearningCircuit"))++ logger.info(f"Looking for config in: {config_dir}")+ return config_dir+++# Define config paths+CONFIG_DIR = get_config_dir() / "config"+CONFIG_DIR.mkdir(parents=True, exist_ok=True)+SETTINGS_FILE = CONFIG_DIR / "settings.toml"+SECRETS_FILE = CONFIG_DIR / ".secrets.toml"+SEARCH_ENGINES_FILE = CONFIG_DIR / "search_engines.toml"++LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"++env_file = CONFIG_DIR / ".env"++if env_file.exists():+ logger.info(f"Loading environment variables from: {env_file}")+ load_dotenv(dotenv_path=env_file)+else:+ logger.warning(+ f"Warning: .env file not found at {env_file}. Trying secondary location."+ )+ env_file_secondary = get_config_dir() / ".env"+ if env_file_secondary.exists():+ get_config_dir() / "config"+ logger.info(f"Loading environment variables from: {env_file_secondary}")+ load_dotenv(dotenv_path=env_file_secondary)+ else:+ logger.warning(f"Warning: .env file also not found at {env_file_secondary}.")+++# Set environment variable for Dynaconf to use+docs_base = Path(user_documents_dir()) / "local_deep_research"+os.environ["DOCS_DIR"] = str(docs_base)+++def init_config_files():+ """Initialize config files if they don't exist"""+ import os+ import platform+ import shutil++ # Ensure CONFIG_DIR exists with explicit creation+ os.makedirs(CONFIG_DIR, exist_ok=True)++ # Get default files path with more reliable approach for Windows+ if platform.system() == "Windows":+ # Use a more reliable method on Windows+ from pkg_resources import resource_filename++ try:+ defaults_dir = Path(resource_filename("local_deep_research", "defaults"))+ logger.info(f"Using pkg_resources for Windows: {defaults_dir}")++ # Create settings.toml if it doesn't exist (with explicit Windows paths)+ settings_file = os.path.join(CONFIG_DIR, "settings.toml")+ default_settings = os.path.join(defaults_dir, "main.toml")+ if not os.path.exists(settings_file) and os.path.exists(default_settings):+ shutil.copyfile(default_settings, settings_file)+ logger.info(f"Created settings.toml at {settings_file}")++ # Create local_collections.toml if it doesn't exist+ collections_file = os.path.join(CONFIG_DIR, "local_collections.toml")+ default_collections = os.path.join(defaults_dir, "local_collections.toml")+ if not os.path.exists(collections_file) and os.path.exists(+ default_collections+ ):+ shutil.copyfile(default_collections, collections_file)+ logger.info(f"Created local_collections.toml at {collections_file}")++ # Create search_engines.toml if it doesn't exist+ search_engines_file = os.path.join(CONFIG_DIR, "search_engines.toml")+ default_engines = os.path.join(defaults_dir, "search_engines.toml")+ if not os.path.exists(search_engines_file) and os.path.exists(+ default_engines+ ):+ shutil.copyfile(default_engines, search_engines_file)+ logger.info(f"Created search_engines.toml at {search_engines_file}")++ # Create .env.template if it doesn't exist+ env_template_file = CONFIG_DIR / ".env.template"+ if not env_template_file.exists():+ shutil.copy(defaults_dir / ".env.template", env_template_file)+ logger.info(f"Created .env.template at {env_template_file}")++ # Optionally create an empty .env file if it doesn't exist+ env_file = CONFIG_DIR / ".env"+ if not env_file.exists():+ with open(env_file, "w") as f:+ f.write("# Add your environment variables here\n")+ logger.info(f"Created empty .env file at {env_file}")+ except Exception as e:+ logger.error(f"Error initializing Windows config files: {e}")+ else:+ """Initialize config files if they don't exist"""+ import shutil+ from importlib.resources import files++ # Get default files path+ try:+ defaults_dir = files("local_deep_research.defaults")+ except ImportError:+ # Fallback for older Python versions+ from pkg_resources import resource_filename++ defaults_dir = Path(resource_filename("local_deep_research", "defaults"))++ # Create settings.toml if it doesn't exist+ settings_file = CONFIG_DIR / "settings.toml"+ if not settings_file.exists():+ shutil.copy(defaults_dir / "main.toml", settings_file)+ logger.info(f"Created settings.toml at {settings_file}")++ # Create local_collections.toml if it doesn't exist+ collections_file = CONFIG_DIR / "local_collections.toml"+ if not collections_file.exists():+ shutil.copy(defaults_dir / "local_collections.toml", collections_file)+ logger.info(f"Created local_collections.toml at {collections_file}")++ # Create search_engines.toml if it doesn't exist+ search_engines_file = CONFIG_DIR / "search_engines.toml"+ if not search_engines_file.exists():+ shutil.copy(defaults_dir / "search_engines.toml", search_engines_file)+ logger.info(f"Created search_engines.toml at {search_engines_file}")+ env_template_file = CONFIG_DIR / ".env.template"+ if not env_template_file.exists():+ shutil.copy(defaults_dir / ".env.template", env_template_file)+ logger.info(f"Created .env.template at {env_template_file}")++ # Optionally create an empty .env file if it doesn't exist+ env_file = CONFIG_DIR / ".env"+ if not env_file.exists():+ with open(env_file, "w") as f:+ f.write("# Add your environment variables here\n")+ logger.info(f"Created empty .env file at {env_file}")+ secrets_file = CONFIG_DIR / ".secrets.toml"+ if not secrets_file.exists():+ with open(secrets_file, "w") as f:+ f.write(+ """+ # ANTHROPIC_API_KEY = "your-api-key-here"+ # OPENAI_API_KEY = "your-openai-key-here"+ # GOOGLE_API_KEY = "your-google-key-here"+ # SERP_API_KEY = "your-api-key-here"+ # GUARDIAN_API_KEY = "your-api-key-here"+ # GOOGLE_PSE_API_KEY = "your-google-api-key-here"+ # GOOGLE_PSE_ENGINE_ID = "your-programmable-search-engine-id-here"+ """+ )+++settings = Dynaconf(+ settings_files=[+ str(SETTINGS_FILE),+ str(LOCAL_COLLECTIONS_FILE),+ str(SEARCH_ENGINES_FILE),+ ],+ secrets=str(SECRETS_FILE),+ env_prefix="LDR",+ load_dotenv=True,+ envvar_prefix="LDR",+ env_file=str(CONFIG_DIR / ".env"),+)++# Initialize config files on import+init_config_files()diff --git a/src/local_deep_research/defaults/llm_config.py b/src/local_deep_research/config/llm_config.pysimilarity index 85%rename from src/local_deep_research/defaults/llm_config.pyrename to src/local_deep_research/config/llm_config.pyindex 0e144d39ae..22d4ad8f38 100644--- a/src/local_deep_research/defaults/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -1,24 +1,16 @@-"""-LLM configuration for Local Deep Research.--This file controls which language models are available and how they're configured.-You can customize model selection, parameters, and fallbacks here.-"""-import loggingimport os+from pathlib import Pathfrom langchain_anthropic import ChatAnthropic-from langchain_openai import ChatOpenAI-from langchain_ollama import ChatOllamafrom langchain_community.llms import VLLM-from local_deep_research.utilties.search_utilities import remove_think_tagsfrom langchain_ollama import ChatOllamafrom langchain_openai import ChatOpenAI-from ..config import settings+from ..utilties.search_utilities import remove_think_tags+from .config_files import CONFIG_DIR, settings-# Initialize environment+# Setup logginglogger = logging.getLogger(__name__)# Valid provider options@@ -32,12 +24,7 @@ VALID_PROVIDERS = ["llamacpp","none",]--# ================================-# LLM FUNCTIONS-# ================================--+SECRETS_FILE = CONFIG_DIR / ".secrets.toml"def get_llm(model_name=None, temperature=None, provider=None):@@ -75,8 +62,8 @@ def get_llm(model_name=None, temperature=None, provider=None):# Handle different providersif provider == "anthropic":- api_key_name = 'ANTHROPIC_API_KEY'- api_key = settings.get(api_key_name, '')+ api_key_name = "ANTHROPIC_API_KEY"+ api_key = settings.get(api_key_name, "")if not api_key:api_key = os.getenv(api_key_name)if not api_key:@@ -86,15 +73,15 @@ def get_llm(model_name=None, temperature=None, provider=None):"ANTHROPIC_API_KEY not found. Falling back to default model.")return get_fallback_model(temperature)-+llm = ChatAnthropic(model=model_name, anthropic_api_key=api_key, **common_params)return wrap_llm_without_think_tags(llm)-+elif provider == "openai":- api_key_name = 'OPENAI_API_KEY'- api_key = settings.get(api_key_name, '')+ api_key_name = "OPENAI_API_KEY"+ api_key = settings.get(api_key_name, "")if not api_key:api_key = os.getenv(api_key_name)if not api_key:@@ -102,13 +89,13 @@ def get_llm(model_name=None, temperature=None, provider=None):if not api_key:logger.warning("OPENAI_API_KEY not found. Falling back to default model.")return get_fallback_model(temperature)-+llm = ChatOpenAI(model=model_name, api_key=api_key, **common_params)return wrap_llm_without_think_tags(llm)-+elif provider == "openai_endpoint":- api_key_name = 'OPENAI_ENDPOINT_API_KEY'- api_key = settings.get(api_key_name, '')+ api_key_name = "OPENAI_ENDPOINT_API_KEY"+ api_key = settings.get(api_key_name, "")if not api_key:api_key = os.getenv(api_key_name)if not api_key:@@ -121,15 +108,15 @@ def get_llm(model_name=None, temperature=None, provider=None):# Get endpoint URL from settingsopenai_endpoint_url = settings.llm.openai_endpoint_url-+llm = ChatOpenAI(- model=model_name,+ model=model_name,api_key=api_key,openai_api_base=openai_endpoint_url,**common_params,)return wrap_llm_without_think_tags(llm)-+elif provider == "vllm":try:llm = VLLM(@@ -149,7 +136,10 @@ def get_llm(model_name=None, temperature=None, provider=None):elif provider == "ollama":try:# Use the configurable Ollama base URL- base_url = settings.get('OLLAMA_BASE_URL', settings.llm.get('ollama_base_url', 'http://localhost:11434'))+ base_url = settings.get(+ "OLLAMA_BASE_URL",+ settings.llm.get("ollama_base_url", "http://localhost:11434"),+ )llm = ChatOllama(model=model_name, base_url=base_url, **common_params)return wrap_llm_without_think_tags(llm)except Exception as e:@@ -158,32 +148,32 @@ def get_llm(model_name=None, temperature=None, provider=None):elif provider == "lmstudio":# LM Studio supports OpenAI API format, so we can use ChatOpenAI directly- lmstudio_url = settings.llm.get('lmstudio_url', "http://localhost:1234")-+ lmstudio_url = settings.llm.get("lmstudio_url", "http://localhost:1234")+llm = ChatOpenAI(model=model_name,api_key="lm-studio", # LM Studio doesn't require a real API keybase_url=f"{lmstudio_url}/v1", # Use the configured URL with /v1 endpointtemperature=temperature,- max_tokens=settings.llm.max_tokens+ max_tokens=settings.llm.max_tokens,)return wrap_llm_without_think_tags(llm)-+elif provider == "llamacpp":# Import LlamaCppfrom langchain_community.llms import LlamaCpp-+# Get LlamaCpp model path from settings- model_path = settings.llm.get('llamacpp_model_path', "")+ model_path = settings.llm.get("llamacpp_model_path", "")if not model_path:logger.error("llamacpp_model_path not set in settings")raise ValueError("llamacpp_model_path not set in settings.toml")-+# Get additional LlamaCpp parameters- n_gpu_layers = settings.llm.get('llamacpp_n_gpu_layers', 1)- n_batch = settings.llm.get('llamacpp_n_batch', 512)- f16_kv = settings.llm.get('llamacpp_f16_kv', True)-+ n_gpu_layers = settings.llm.get("llamacpp_n_gpu_layers", 1)+ n_batch = settings.llm.get("llamacpp_n_batch", 512)+ f16_kv = settings.llm.get("llamacpp_f16_kv", True)+# Create LlamaCpp instancellm = LlamaCpp(model_path=model_path,@@ -192,10 +182,10 @@ def get_llm(model_name=None, temperature=None, provider=None):n_gpu_layers=n_gpu_layers,n_batch=n_batch,f16_kv=f16_kv,- verbose=True+ verbose=True,)return wrap_llm_without_think_tags(llm)-+else:return wrap_llm_without_think_tags(get_fallback_model(temperature))@@ -211,35 +201,31 @@ def get_fallback_model(temperature=None):)-# ================================-# COMPATIBILITY FUNCTIONS-# ================================-def wrap_llm_without_think_tags(llm):"""Create a wrapper class that processes LLM outputs with remove_think_tags"""-class ProcessingLLMWrapper:def __init__(self, base_llm):self.base_llm = base_llm-+def invoke(self, *args, **kwargs):response = self.base_llm.invoke(*args, **kwargs)-+# Process the response content if it has a content attribute- if hasattr(response, 'content'):+ if hasattr(response, "content"):response.content = remove_think_tags(response.content)elif isinstance(response, str):response = remove_think_tags(response)-+return response-+# Pass through any other attributes to the base LLMdef __getattr__(self, name):return getattr(self.base_llm, name)-+return ProcessingLLMWrapper(llm)+def get_available_provider_types():"""Return available model providers"""providers = {}@@ -278,11 +264,6 @@ def get_available_provider_types():return providers-# ================================-# HELPER FUNCTIONS-# ================================--def is_openai_available():"""Check if OpenAI is available"""try:@@ -371,11 +352,13 @@ def get_available_providers():return get_available_provider_types()-# Log which providers are available+secrets_file = Path(SECRETS_FILE)AVAILABLE_PROVIDERS = get_available_providers()+selected_provider = settings.llm.provider.lower()++# Log which providers are availablelogger.info(f"Available providers: {list(AVAILABLE_PROVIDERS.keys())}")# Check if selected provider is available-selected_provider = settings.llm.provider.lower()if selected_provider not in AVAILABLE_PROVIDERS and selected_provider != "none":logger.warning(f"Selected provider {selected_provider} is not available.")diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pynew file mode 100644index 0000000000..37af40c2ad--- /dev/null+++ b/src/local_deep_research/config/search_config.py@@ -0,0 +1,43 @@+# local_deep_research/config.py+import logging++from ..web_search_engines.search_engine_factory import get_search as factory_get_search+from .config_files import settings+from .llm_config import get_llm++# Setup logging+logger = logging.getLogger(__name__)+++# Whether to check the quality search results using the LLM.+QUALITY_CHECK_DDG_URLS = True+# Whether to only retrieve snippets instead of full search results.+SEARCH_SNIPPETS_ONLY = settings.search.snippets_only+++# Expose get_search function+def get_search(search_tool=None):+ """+ Helper function to get search engine+ """++ # Use specified tool or default from settings+ tool = search_tool or settings.search.tool+ logger.info(f"Search tool is: {tool}")++ # Get search parameters+ params = {+ "search_tool": tool,+ "llm_instance": get_llm(),+ "max_results": settings.search.max_results,+ "region": settings.search.region,+ "time_period": settings.search.time_period,+ "safe_search": settings.search.safe_search,+ "search_snippets_only": SEARCH_SNIPPETS_ONLY,+ "search_language": settings.search.search_language,+ "max_filtered_results": settings.search.max_filtered_results,+ }+ logger.info(f"Search config params: {params}")++ # Create and return search engine+ return factory_get_search(**params)diff --git a/src/local_deep_research/main.py b/src/local_deep_research/main.pyindex 9b99370e5b..43d0184bc7 100644--- a/src/local_deep_research/main.py+++ b/src/local_deep_research/main.py@@ -1,6 +1,6 @@from typing import Dict-from .config import settings+from .config.config_files import settingsfrom .report_generator import IntegratedReportGeneratorfrom .search_system import AdvancedSearchSystemdiff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.pyindex 79deba4a16..3847a220c1 100644--- a/src/local_deep_research/report_generator.py+++ b/src/local_deep_research/report_generator.py@@ -1,7 +1,6 @@from typing import Dict, List-from . import utilties-from .config import get_llm+from . import get_llm, utiltiesfrom .search_system import AdvancedSearchSystemfrom .utilties import search_utilitiesdiff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex be42565146..6885913c6a 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -3,8 +3,10 @@ import osfrom datetime import datetimefrom typing import Callable, Dict, List+from . import get_llmfrom .citation_handler import CitationHandler-from .config import get_llm, get_search, settings+from .config.config_files import get_config_dir, settings+from .config.search_config import get_searchfrom .utilties.enums import KnowledgeAccumulationApproachfrom .utilties.search_utilities import (extract_links_from_search_results,@@ -367,9 +369,8 @@ class AdvancedSearchSystem::50]safe_query = safe_query.replace(" ", "_").lower()- from . import config as conf- output_dir = f"{conf.get_config_dir()}/research_outputs"+ output_dir = f"{get_config_dir()}/research_outputs"if not os.path.exists(output_dir):os.makedirs(output_dir)diff --git a/src/local_deep_research/utilties/setup_utils.py b/src/local_deep_research/utilties/setup_utils.pyindex 49fb5c59cf..0efe4127fe 100644--- a/src/local_deep_research/utilties/setup_utils.py+++ b/src/local_deep_research/utilties/setup_utils.py@@ -3,6 +3,6 @@def setup_user_directories():"""Set up directories and ensure config files exist."""- from ..config import init_config_files+ from ..config.config_files import init_config_filesinit_config_files()diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.pyindex 4adbed4ff0..5824def3ae 100644--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@ -28,7 +28,7 @@ from flask import (from flask_socketio import SocketIO, emit# Import the new configuration manager-from ..config import SEARCH_ENGINES_FILE, get_config_dir+from ..config.config_files import SEARCH_ENGINES_FILE, get_config_dir, settingsfrom ..report_generator import IntegratedReportGeneratorfrom ..search_system import AdvancedSearchSystem@@ -54,7 +54,7 @@ try:setup_user_directories()# Get directories based on package installation- PACKAGE_DIR = importlib_resources.files("src.local_deep_research") / "web"+ PACKAGE_DIR = importlib_resources.files("local_deep_research") / "web"with importlib_resources.as_file(PACKAGE_DIR) as package_dir:STATIC_DIR = (package_dir / "static").as_posix()TEMPLATE_DIR = (package_dir / "templates").as_posix()@@ -1591,6 +1591,7 @@ def main_config_page():"""Edit main configuration with search parameters"""return render_template("main_config.html", main_file_path=MAIN_CONFIG_FILE)+@research_bp.route("/settings/collections", methods=["GET"])def collections_config_page():"""Edit local collections configuration using raw file editor"""@@ -1939,7 +1940,6 @@ def main():This function is needed for the package's entry point to work properly."""# Import settings here to avoid circular imports- from ..config import settings# Get web server settings with defaultsport = settings.web.portdiff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.pyindex bb91554c75..6335d080a0 100644--- a/src/local_deep_research/web_search_engines/engines/full_search.py+++ b/src/local_deep_research/web_search_engines/engines/full_search.py@@ -9,7 +9,7 @@ from langchain_community.document_loaders import AsyncChromiumLoaderfrom langchain_community.document_transformers import BeautifulSoupTransformerfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config.search_config import QUALITY_CHECK_DDG_URLSfrom ...utilties.search_utilities import remove_think_tagslogger = logging.getLogger(__name__)@@ -85,7 +85,7 @@ class FullSearchResults:raise ValueError("Expected the search results in list format.")# Step 2: Filter URLs using LLM- if config.QUALITY_CHECK_DDG_URLS:+ if QUALITY_CHECK_DDG_URLS:filtered_results = self.check_urls(search_results, query)else:filtered_results = search_resultsdiff --git a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py b/src/local_deep_research/web_search_engines/engines/meta_search_engine.pyindex ed39b5b358..77dd153f84 100644--- a/src/local_deep_research/web_search_engines/engines/meta_search_engine.py+++ b/src/local_deep_research/web_search_engines/engines/meta_search_engine.py@@ -2,7 +2,7 @@ import loggingimport osfrom typing import Any, Dict, List, Optional-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEnginefrom ..search_engine_factory import create_search_enginefrom ..search_engines_config import SEARCH_ENGINES@@ -247,7 +247,10 @@ Do not include any engines that are not listed above. Only return the comma-sepaList of result dictionaries with full content"""# Check if we should get full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_itemsdiff --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.pyindex 109ad6c1bf..5159ad3979 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@@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optionalimport arxivfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEnginelogger = logging.getLogger(__name__)@@ -158,7 +158,10 @@ class ArXivSearchEngine(BaseSearchEngine):List of result dictionaries with full content"""# Check if we should get full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_items@@ -350,8 +353,8 @@ class ArXivSearchEngine(BaseSearchEngine):# Add full content if not in snippet-only modeif (- not hasattr(config, "SEARCH_SNIPPETS_ONLY")- or not config.SEARCH_SNIPPETS_ONLY+ not hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ or not search_config.SEARCH_SNIPPETS_ONLY):result.update({diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.pyindex 1741647101..87bb527ca3 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py@@ -5,7 +5,7 @@ from typing import Any, Dict, List, Optionalfrom langchain_community.tools import BraveSearchfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEnginelogger = logging.getLogger(__name__)@@ -183,7 +183,10 @@ class BraveSearchEngine(BaseSearchEngine):List of result dictionaries with full content if requested"""# Check if we should get full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")# Return the relevant items with their full Brave informationdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_github.py b/src/local_deep_research/web_search_engines/engines/search_engine_github.pyindex 7228defee4..c9bf5f8654 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_github.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_github.py@@ -1,15 +1,14 @@import base64+import jsonimport loggingimport osimport timefrom typing import Any, Dict, List, Optionalimport requests-import json-from typing import Dict, List, Any, Optional, Unionfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import llm_config, search_configfrom ..search_engine_base import BaseSearchEngine# Setup logging@@ -90,28 +89,28 @@ class GitHubSearchEngine(BaseSearchEngine):f"GitHub API rate limit exceeded. Waiting {wait_time:.0f} seconds.")time.sleep(min(wait_time, 60)) # Wait at most 60 seconds-+def _optimize_github_query(self, query: str) -> str:"""Optimize the GitHub search query using LLM to improve search results.-+Args:query: Original search query-+Returns:Optimized GitHub search query"""# Get LLM from config if not already setif not self.llm:try:- self.llm = config.get_llm()+ self.llm = llm_config.get_llm()if not self.llm:logger.warning("No LLM available for query optimization")return queryexcept Exception as e:logger.error(f"Error getting LLM from config: {e}")return query-+prompt = f"""Transform this GitHub search query into an optimized version for the GitHub search API. Follow these steps:1. Strip question words (e.g., 'what', 'are', 'is'), stop words (e.g., 'and', 'as', 'of', 'on'), and redundant terms (e.g., 'repositories', 'repos', 'github') since they're implied by the search context.2. Keep only domain-specific keywords and avoid using "-related" terms.@@ -136,15 +135,17 @@ class GitHubSearchEngine(BaseSearchEngine):try:response = self.llm.invoke(prompt)optimized_query = response.content.strip()-+# Validate the optimized queryif optimized_query and len(optimized_query) > 0:- logger.info(f"LLM optimized query from '{query}' to '{optimized_query}'")+ logger.info(+ f"LLM optimized query from '{query}' to '{optimized_query}'"+ )return optimized_queryelse:logger.warning("LLM returned empty query, using original")return query-+except Exception as e:logger.error(f"Error optimizing query with LLM: {e}")return query@@ -164,9 +165,9 @@ class GitHubSearchEngine(BaseSearchEngine):try:# Optimize GitHub query using LLMgithub_query = self._optimize_github_query(query)-+logger.info(f"Final GitHub query: {github_query}")-+# Construct search parametersparams = {"q": github_query,@@ -546,7 +547,10 @@ class GitHubSearchEngine(BaseSearchEngine):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:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_items@@ -700,8 +704,8 @@ class GitHubSearchEngine(BaseSearchEngine):# Get full content if requestedif (- hasattr(config, "SEARCH_SNIPPETS_ONLY")- and not config.SEARCH_SNIPPETS_ONLY+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and not search_config.SEARCH_SNIPPETS_ONLY):return self._get_full_content(previews)@@ -788,20 +792,22 @@ class GitHubSearchEngine(BaseSearchEngine):else:logger.error(f"Invalid GitHub search type: {search_type}")- def _filter_for_relevance(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:+ def _filter_for_relevance(+ self, previews: List[Dict[str, Any]], query: str+ ) -> List[Dict[str, Any]]:"""Filter GitHub search results for relevance using LLM.-+Args:previews: List of preview dictionariesquery: Original search query-+Returns:List of relevant preview dictionaries"""if not self.llm or not previews:return previews-+# Create a specialized prompt for GitHub resultsprompt = f"""Analyze these GitHub search results and rank them by relevance to the query.Consider:@@ -823,31 +829,38 @@ Do not include any other text or explanation."""try:response = self.llm.invoke(prompt)response_text = response.content.strip()-+# Extract JSON array from response- start_idx = response_text.find('[')- end_idx = response_text.rfind(']')-+ 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]+ array_text = response_text[start_idx : end_idx + 1]ranked_indices = json.loads(array_text)-+# Return the results in ranked orderranked_results = []for idx in ranked_indices:if idx < len(previews):ranked_results.append(previews[idx])-+# Limit to max_filtered_results if specified- if self.max_filtered_results and len(ranked_results) > self.max_filtered_results:- logger.info(f"Limiting filtered results to top {self.max_filtered_results}")- return ranked_results[:self.max_filtered_results]-+ if (+ self.max_filtered_results+ and len(ranked_results) > self.max_filtered_results+ ):+ logger.info(+ f"Limiting filtered results to top {self.max_filtered_results}"+ )+ return ranked_results[: self.max_filtered_results]+return ranked_resultselse:- logger.info("Could not find JSON array in response, returning no previews")+ logger.info(+ "Could not find JSON array in response, returning no previews"+ )return []-+except Exception as e:logger.error(f"Error filtering GitHub results: {e}")return []diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.pyindex e2d496d48d..086e767f07 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Optional, Tupleimport requestsfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ...utilties.search_utilities import remove_think_tagsfrom ..search_engine_base import BaseSearchEngine@@ -459,7 +459,10 @@ ONE WORD ONLY:""")# Check if we should add full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):return relevant_items# Get full articles for relevant itemsdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.pyindex 840e6e2f46..6f2e8d6969 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py@@ -25,7 +25,7 @@ from langchain_community.vectorstores import FAISSfrom langchain_core.language_models import BaseLLMfrom langchain_text_splitters import RecursiveCharacterTextSplitter-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEngine# Setup logging@@ -771,7 +771,10 @@ class LocalSearchEngine(BaseSearchEngine):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:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content addition")return relevant_items@@ -850,7 +853,10 @@ class LocalSearchEngine(BaseSearchEngine):return []# Phase 3: Get full content for relevant items- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Returning snippet-only results as per config")results = relevant_itemselse:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.pyindex 2c869ee8f9..44e99c4c19 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local_all.py@@ -8,7 +8,7 @@ from typing import Any, Dict, List, Optionalimport tomlfrom langchain_core.language_models import BaseLLM-from ...config import LOCAL_COLLECTIONS_FILE+from ...config.config_files import LOCAL_COLLECTIONS_FILEfrom ..search_engine_base import BaseSearchEnginefrom ..search_engine_factory import create_search_enginediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex 8f52453f0c..99873b4abf 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -7,7 +7,7 @@ from typing import Any, Dict, List, Optional, Tupleimport requestsfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEngine# Setup logging@@ -893,7 +893,10 @@ The default assumption should be that medical and scientific queries want RECENTList of result dictionaries with full content"""# Check if we should add full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_itemsdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex 0ef4c9eb07..180e27f1c6 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py@@ -6,7 +6,7 @@ from typing import Any, Dict, List, Optionalimport requestsfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEnginefrom .full_search import FullSearchResults@@ -368,7 +368,10 @@ class SearXNGSearchEngine(BaseSearchEngine):if not self.is_available:return relevant_items- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_itemsdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.pyindex 6d0e4dfa0b..55317af524 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py@@ -8,7 +8,7 @@ from langchain_core.language_models import BaseLLMfrom requests.adapters import HTTPAdapterfrom urllib3.util import Retry-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEngine# Setup logging@@ -554,7 +554,10 @@ Format each query on a new line with no numbering or explanation. Keep each querList of result dictionaries with full content"""# Check if we should add full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_itemsdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.pyindex f243601b09..99f9ad8ed0 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py@@ -5,7 +5,7 @@ from typing import Any, Dict, List, Optionalfrom langchain_community.utilities import SerpAPIWrapperfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEnginelogger = logging.getLogger(__name__)@@ -165,7 +165,10 @@ class SerpAPISearchEngine(BaseSearchEngine):List of result dictionaries with full content if requested"""# Check if we should get full content- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")# Return the relevant items with their full SerpAPI informationdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.pyindex 153dcbb226..dcda6e7183 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py@@ -7,7 +7,7 @@ import justextimport requestsfrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEngine# Setup logging@@ -307,7 +307,10 @@ class WaybackSearchEngine(BaseSearchEngine):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:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_items@@ -375,8 +378,8 @@ class WaybackSearchEngine(BaseSearchEngine):# Get full content if not in snippets-only modeif (- not hasattr(config, "SEARCH_SNIPPETS_ONLY")- or not config.SEARCH_SNIPPETS_ONLY+ not hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ or not search_config.SEARCH_SNIPPETS_ONLY):return self._get_full_content(previews)@@ -440,8 +443,8 @@ class WaybackSearchEngine(BaseSearchEngine):# Get full content if not in snippets-only modeif (- not hasattr(config, "SEARCH_SNIPPETS_ONLY")- or not config.SEARCH_SNIPPETS_ONLY+ not hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ or not search_config.SEARCH_SNIPPETS_ONLY):return self._get_full_content(snapshots)@@ -482,8 +485,8 @@ class WaybackSearchEngine(BaseSearchEngine):# Get full content if not in snippets-only modeif (- not hasattr(config, "SEARCH_SNIPPETS_ONLY")- or not config.SEARCH_SNIPPETS_ONLY+ not hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ or not search_config.SEARCH_SNIPPETS_ONLY):raw_html, full_content = self._get_wayback_content(wayback_url)result["raw_html"] = raw_htmldiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.pyindex 2ea44d93fd..05bfddc222 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wikipedia.py@@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optionalimport wikipediafrom langchain_core.language_models import BaseLLM-from ... import config+from ...config import search_configfrom ..search_engine_base import BaseSearchEngine# Setup logging@@ -148,7 +148,10 @@ class WikipediaSearchEngine(BaseSearchEngine):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:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Snippet-only mode, skipping full content retrieval")return relevant_items@@ -235,7 +238,8 @@ class WikipediaSearchEngine(BaseSearchEngine):"""# Check if we should include full contentinclude_content = not (- hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY)try: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.pyindex d6297fe544..2e1267bd6f 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@@ -6,6 +6,7 @@ from typing import Any, Dict, List, Optionalfrom langchain_core.language_models import BaseLLM+from ..config import search_configfrom ..utilties.search_utilities import remove_think_tagslogger = logging.getLogger(__name__)@@ -79,9 +80,11 @@ class BaseSearchEngine(ABC):# Step 3: Get full content for filtered items# Import config inside the method to avoid circular import- from .. import config- if hasattr(config, "SEARCH_SNIPPETS_ONLY") and config.SEARCH_SNIPPETS_ONLY:+ if (+ hasattr(search_config, "SEARCH_SNIPPETS_ONLY")+ and search_config.SEARCH_SNIPPETS_ONLY+ ):logger.info("Returning snippet-only results as per config")results = filtered_itemselse:@@ -109,10 +112,12 @@ class BaseSearchEngine(ABC):Filtered list of the most relevant search results"""# Import config inside the method to avoid circular import- from .. import config# Skip filtering if configured to do so or if no LLM is available- if hasattr(config, "SKIP_RELEVANCE_FILTER") and config.SKIP_RELEVANCE_FILTER:+ if (+ hasattr(search_config, "SKIP_RELEVANCE_FILTER")+ and search_config.SKIP_RELEVANCE_FILTER+ ):# Return all previews up to max_filtered_results if no filtering is performedlimit = self.max_filtered_results or 5return previews[:limit]diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex 629c1fca81..ca9916bc68 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -35,7 +35,7 @@ def create_search_engine(# Get engine configurationengine_config = SEARCH_ENGINES[engine_name]- from ..config import settings+ from ..config.config_files import settings# Set default max_results from config if not provided in kwargsif "max_results" not in kwargs:@@ -53,7 +53,6 @@ def create_search_engine(if not api_key:api_key = os.getenv("LDR_" + api_key_env)-# If not found in environment, check Dynaconf settingsif not api_key and api_key_env:# Convert env var name to settings path (e.g., BRAVE_API_KEY -> brave_api_key)@@ -82,7 +81,7 @@ def create_search_engine(if module_path.startswith("."):# This is a relative import. Assume it's relative to# `web_search_engines`.- package = "src.local_deep_research.web_search_engines"+ package = "local_deep_research.web_search_engines"module = importlib.import_module(module_path, package=package)engine_class = getattr(module, class_name)diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.pyindex bedfbb9870..4256112a60 100644--- a/src/local_deep_research/web_search_engines/search_engines_config.py+++ b/src/local_deep_research/web_search_engines/search_engines_config.py@@ -8,7 +8,7 @@ import osimport toml-from ..config import CONFIG_DIR, LOCAL_COLLECTIONS_FILE+from ..config.config_files import CONFIG_DIR, LOCAL_COLLECTIONS_FILElogger = logging.getLogger(__name__)