~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
working on pip
LearningCircuit6f31f898f069
diff --git a/pyproject.toml b/pyproject.tomlindex 4c8bd099d8..59e93562f7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -43,7 +43,7 @@ dependencies = ["pydantic-settings>=2.0.0","toml>=0.10.2","platformdirs>=3.0.0",-+ "dynaconf"][project.urls]@@ -59,4 +59,4 @@ include-package-data = true[tool.setuptools.package-data]"local_deep_research.web" = ["templates/*", "static/*", "static/**/*"]-"local_deep_research.defaults" = ["*.toml", "*.py"]\ No newline at end of file+"local_deep_research.defaults" = ["*.toml", "*.py"]diff --git a/src/local_deep_research/config_manager.py b/src/local_deep_research/config_manager.pyindex 0b525d8b85..e0392330fb 100644--- a/src/local_deep_research/config_manager.py+++ b/src/local_deep_research/config_manager.py@@ -3,23 +3,20 @@"""Configuration manager for Local Deep Research.-This module handles loading and managing configuration from multiple sources:-- Default values embedded in the code-- TOML configuration files in the user's config directory-- Environment variables-- LLM configuration from the Python module--It provides a unified interface for accessing all configuration settings.+This module uses Dynaconf to handle configuration management+while using template files from the defaults directory."""import osimport sys-import json-import toml-import loggingimport importlib.util+import logging+import shutilfrom pathlib import Path-from typing import Dict, Any, Optional, List+from typing import Dict, Any, Optional++# Import Dynaconf - required dependency+from dynaconf import Dynaconf, loaders# Setup logginglogger = logging.getLogger(__name__)@@ -31,398 +28,263 @@ APP_AUTHOR = "LearningCircuit"# Find the appropriate config directory based on platformdef get_config_dir() -> Path:"""Get the configuration directory based on platform standards."""- # Use platformdirs if available- try:- from platformdirs import user_config_dir- return Path(user_config_dir(APP_NAME, APP_AUTHOR))- except ImportError:- # Fallback implementation- if sys.platform == "win32":- base_dir = os.environ.get("APPDATA", os.path.expanduser("~"))- return Path(base_dir) / APP_NAME- elif sys.platform == "darwin":- return Path(os.path.expanduser("~")) / "Library" / "Application Support" / APP_NAME- else:- # Linux and other Unix-like systems- xdg_config_home = os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))- return Path(xdg_config_home) / APP_NAME+ from platformdirs import user_config_dir+ return Path(user_config_dir(APP_NAME, APP_AUTHOR))def get_data_dir() -> Path:"""Get the data directory based on platform standards."""- try:- from platformdirs import user_data_dir- return Path(user_data_dir(APP_NAME, APP_AUTHOR))- except ImportError:- return get_config_dir() / "data"+ from platformdirs import user_data_dir+ data_dir_path = Path(user_data_dir(APP_NAME, APP_AUTHOR))+ logger.info(f"Data Dir: {data_dir_path}")+ return data_dir_pathdef get_cache_dir() -> Path:"""Get the cache directory based on platform standards."""- try:- from platformdirs import user_cache_dir- return Path(user_cache_dir(APP_NAME, APP_AUTHOR))- except ImportError:- return get_config_dir() / "cache"+ from platformdirs import user_cache_dir+ return Path(user_cache_dir(APP_NAME, APP_AUTHOR))-# Define main configuration file paths+# Define pathsCONFIG_DIR = get_config_dir() / "config"MAIN_CONFIG_FILE = CONFIG_DIR / "main.toml"LOCAL_COLLECTIONS_FILE = CONFIG_DIR / "local_collections.toml"LLM_CONFIG_FILE = CONFIG_DIR / "llm_config.py"-# Default main configuration-DEFAULT_MAIN_CONFIG = {- "general": {- "output_dir": "research_outputs",- "knowledge_accumulation": "ITERATION",- "knowledge_accumulation_context_limit": 2000000,- "enable_fact_checking": False- },- "search": {- "tool": "auto",- "iterations": 3,- "questions_per_iteration": 3,- "searches_per_section": 3,- "max_results": 50,- "max_filtered_results": 5,- "region": "us",- "time_period": "y",- "safe_search": True,- "search_language": "English",- "snippets_only": False,- "skip_relevance_filter": False,- "quality_check_urls": True- }-}+# Dynaconf settings object - initialized once+settings = None-# Default local collections configuration-DEFAULT_LOCAL_COLLECTIONS = {- "project_docs": {- "name": "Project Documents",- "description": "Project documentation and specifications",- "paths": [str(get_data_dir() / "documents" / "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": str(get_cache_dir() / "local_search" / "project_docs")- },- "research_papers": {- "name": "Research Papers",- "description": "Academic research papers and articles",- "paths": [str(get_data_dir() / "documents" / "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,- "chunk_overlap": 150,- "cache_dir": str(get_cache_dir() / "local_search" / "research_papers")- },- "personal_notes": {- "name": "Personal Notes",- "description": "Personal notes and documents",- "paths": [str(get_data_dir() / "documents" / "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,- "chunk_overlap": 100,- "cache_dir": str(get_cache_dir() / "local_search" / "personal_notes")- }-}+# LLM config cache+_llm_config_cache = None-# Cache for loaded configurations-_config_cache = {- "main": None,- "local_collections": None,- "llm": None-}--def _create_default_configs():- """Create default configuration files if they don't exist."""+def ensure_config_files_exist():+ """+ Ensure all configuration files exist by copying from templates.+ Raises a clear error if templates are not found.+ """# Create config directoryCONFIG_DIR.mkdir(parents=True, exist_ok=True)- # Main config- if not MAIN_CONFIG_FILE.exists():- with open(MAIN_CONFIG_FILE, "w") as f:- toml.dump(DEFAULT_MAIN_CONFIG, f)- logger.info(f"Created default main configuration at {MAIN_CONFIG_FILE}")+ # Try to find the default templates in the package+ package_dir = Path(__file__).parent+ defaults_dir = package_dir / "defaults"++ # Log what we find for debugging+ logger.info(f"Looking for default templates in: {defaults_dir}")+ if not defaults_dir.exists():+ raise FileNotFoundError(+ f"Default templates directory not found at {defaults_dir}. "+ f"Make sure the 'defaults' directory exists in the package."+ )++ # Check for required default files+ required_files = ["main.toml", "local_collections.toml", "llm_config.py"]+ missing_files = []+ for file in required_files:+ if not (defaults_dir / file).exists():+ missing_files.append(file)- # Local collections config+ if missing_files:+ raise FileNotFoundError(+ f"Missing required default templates: {', '.join(missing_files)}. "+ f"Make sure all required templates exist in {defaults_dir}."+ )++ # Create directories first+ data_dir = get_data_dir()+ docs_dir = data_dir / "documents"+ docs_dir.mkdir(parents=True, exist_ok=True)+ cache_dir = get_cache_dir()+ cache_dir.mkdir(parents=True, exist_ok=True)++ # Create subdirectories+ (docs_dir / "project_documents").mkdir(exist_ok=True)+ (docs_dir / "research_papers").mkdir(exist_ok=True)+ (docs_dir / "personal_notes").mkdir(exist_ok=True)+ (cache_dir / "local_search").mkdir(exist_ok=True)+ (data_dir / "research_outputs").mkdir(parents=True, exist_ok=True)++ # Copy main.toml if needed+ print(MAIN_CONFIG_FILE)+ logger.info(f"Main config file exists? {MAIN_CONFIG_FILE.exists()}")++ if not False:+ default_main = defaults_dir / "main.toml"+ logger.info(f"Copying main.toml from {default_main} to {MAIN_CONFIG_FILE}")+ shutil.copy(default_main, MAIN_CONFIG_FILE)+ # After copying the file+ if os.path.exists(MAIN_CONFIG_FILE):+ absolute_path = os.path.abspath(MAIN_CONFIG_FILE)+ logger.info(f"File exists at absolute path: {absolute_path}")+ else:+ logger.error(f"File does not exist after copy: {MAIN_CONFIG_FILE}")+ # Process and copy local_collections.toml if neededif not LOCAL_COLLECTIONS_FILE.exists():- with open(LOCAL_COLLECTIONS_FILE, "w") as f:- toml.dump(DEFAULT_LOCAL_COLLECTIONS, f)- logger.info(f"Created default local collections configuration at {LOCAL_COLLECTIONS_FILE}")+ default_collections = defaults_dir / "local_collections.toml"+ logger.info(f"Processing local_collections.toml from {default_collections}")++ # Read the template file+ with open(default_collections, 'r') as f:+ template_content = f.read()++ # Replace placeholders with actual paths+ template_content = template_content.replace("__DATA_DIR__", str(data_dir))+ template_content = template_content.replace("__CACHE_DIR__", str(cache_dir))++ # Write the processed file+ with open(LOCAL_COLLECTIONS_FILE, 'w') as f:+ f.write(template_content)++ logger.info(f"Created collections configuration at {LOCAL_COLLECTIONS_FILE}")- # Create LLM config if needed+ # Copy llm_config.py if neededif not LLM_CONFIG_FILE.exists():- # Try to copy from package resources- try:- import importlib.resources- with importlib.resources.path('local_deep_research.defaults', 'llm_config.py') as default_llm:- import shutil- shutil.copy(default_llm, LLM_CONFIG_FILE)- logger.info(f"Copied default LLM configuration from package to {LLM_CONFIG_FILE}")- except (ImportError, FileNotFoundError) as e:- logger.warning(f"Could not copy default LLM config from package: {e}")-- # Create a simple default- default_content = """# Default LLM configuration-DEFAULT_MODEL = "mistral"-DEFAULT_MODEL_TYPE = "ollama"-DEFAULT_TEMPERATURE = 0.7-MAX_TOKENS = 30000--# OpenAI Endpoint configuration-USE_OPENAI_ENDPOINT = True-OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"-OPENAI_ENDPOINT_REQUIRES_MODEL = True+ default_llm = defaults_dir / "llm_config.py"+ logger.info(f"Copying llm_config.py from {default_llm} to {LLM_CONFIG_FILE}")+ shutil.copy(default_llm, LLM_CONFIG_FILE)++ logger.info("Configuration files successfully set up")-from langchain_anthropic import ChatAnthropic-from langchain_openai import ChatOpenAI-from langchain_ollama import ChatOllama-from langchain_community.llms import VLLM, Ollama-import os-import logging+def get_settings(reload=False):+ """Get Dynaconf settings object."""+ global settings++ if settings is not None and not reload:+ return settings++ # Ensure config files exist+ ensure_config_files_exist()++ # Initialize Dynaconf with our config files+ settings = Dynaconf(+ settings_files=[+ MAIN_CONFIG_FILE,+ LOCAL_COLLECTIONS_FILE+ ],+ environments=True,+ env_prefix="LDR",+ includes=[], # Additional config files+ )++ return settings-def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):- '''Get LLM instance based on model name and type.'''- # Use defaults if not specified- if model_name is None:- model_name = DEFAULT_MODEL- if model_type is None:- model_type = DEFAULT_MODEL_TYPE- if temperature is None:- temperature = DEFAULT_TEMPERATURE-- # Common parameters- common_params = {- "temperature": temperature,- "max_tokens": kwargs.get("max_tokens", MAX_TOKENS),+def load_main_config(reload=False):+ """Load main configuration using Dynaconf."""+ settings = get_settings(reload)++ # Convert Dynaconf settings to a dictionary structure+ # matching your existing expectations+ config = {+ "general": {+ "output_dir": settings.get('output_dir', 'research_outputs'),+ "knowledge_accumulation": settings.get('knowledge_accumulation', 'ITERATION'),+ "knowledge_accumulation_context_limit": settings.get('knowledge_accumulation_context_limit', 2000000),+ "enable_fact_checking": settings.get('enable_fact_checking', False),+ },+ "search": {+ "tool": settings.get('tool', 'auto'),+ "iterations": settings.get('iterations', 3),+ "questions_per_iteration": settings.get('questions_per_iteration', 3),+ "searches_per_section": settings.get('searches_per_section', 3),+ "max_results": settings.get('max_results', 50),+ "max_filtered_results": settings.get('max_filtered_results', 5),+ "region": settings.get('region', 'us'),+ "time_period": settings.get('time_period', 'y'),+ "safe_search": settings.get('safe_search', True),+ "search_language": settings.get('search_language', 'English'),+ "snippets_only": settings.get('snippets_only', False),+ "skip_relevance_filter": settings.get('skip_relevance_filter', False),+ "quality_check_urls": settings.get('quality_check_urls', True),+ }}- common_params.update(kwargs)-- # Simple pattern matching for model types- if model_type == "ollama":- from langchain_ollama import ChatOllama- return ChatOllama(model=model_name, **common_params)- elif model_type == "openai":- from langchain_openai import ChatOpenAI- return ChatOpenAI(model=model_name, **common_params)- else:- # Default to Ollama- from langchain_ollama import ChatOllama- return ChatOllama(model=model_name, **common_params)-"""- with open(LLM_CONFIG_FILE, "w") as f:- f.write(default_content)- logger.info(f"Created simple default LLM configuration at {LLM_CONFIG_FILE}")- # Create document directories- for collection in DEFAULT_LOCAL_COLLECTIONS.values():- for path in collection["paths"]:- Path(path).mkdir(parents=True, exist_ok=True)--def load_main_config(reload: bool = False) -> Dict[str, Any]:- """Load main configuration from file."""- if _config_cache["main"] is not None and not reload:- return _config_cache["main"]-- # Create default if needed- if not MAIN_CONFIG_FILE.exists():- with open(MAIN_CONFIG_FILE, "w") as f:- toml.dump(DEFAULT_MAIN_CONFIG, f)- logger.info(f"Created default main configuration at {MAIN_CONFIG_FILE}")-- try:- # Load from TOML file- config = toml.load(MAIN_CONFIG_FILE)-- # Apply environment variable overrides- _apply_env_var_overrides(config)-- # Cache the result- _config_cache["main"] = config-- return config- except Exception as e:- logger.error(f"Error loading main config: {e}")- return DEFAULT_MAIN_CONFIG.copy()+ return config-def load_local_collections(reload: bool = False) -> Dict[str, Dict[str, Any]]:- """Load local collections configuration from file."""- if _config_cache["local_collections"] is not None and not reload:- return _config_cache["local_collections"]+def load_local_collections(reload=False):+ """Load local collections configuration using Dynaconf."""+ settings = get_settings(reload)- # Create default if needed- if not LOCAL_COLLECTIONS_FILE.exists():- with open(LOCAL_COLLECTIONS_FILE, "w") as f:- toml.dump(DEFAULT_LOCAL_COLLECTIONS, f)- logger.info(f"Created default local collections configuration at {LOCAL_COLLECTIONS_FILE}")+ # Get all local collections+ # This is a bit tricky as Dynaconf flattens the hierarchy+ collections = {}- try:- # Load from TOML file- collections = toml.load(LOCAL_COLLECTIONS_FILE)-- # Create document directories- for collection in collections.values():- for path in collection.get("paths", []):- Path(path).mkdir(parents=True, exist_ok=True)-- # Cache the result- _config_cache["local_collections"] = collections-- return collections- except Exception as e:- logger.error(f"Error loading local collections config: {e}")- return DEFAULT_LOCAL_COLLECTIONS.copy()+ # Process each collection from settings+ # Note: You'll need to adjust this if your local_collections.toml has a different structure+ for collection_name in ["project_docs", "research_papers", "personal_notes"]:+ if hasattr(settings, collection_name):+ collection_data = getattr(settings, collection_name)+ collections[collection_name] = collection_data++ # Ensure directories exist+ for collection in collections.values():+ for path in collection.get("paths", []):+ Path(path).mkdir(parents=True, exist_ok=True)++ return collections-def load_llm_config(reload: bool = False) -> Dict[str, Any]:+def load_llm_config(reload=False):"""Load LLM configuration by importing the Python module."""- if _config_cache["llm"] is not None and not reload:- return _config_cache["llm"]+ global _llm_config_cache- try:- # Add config directory to path if needed- if str(CONFIG_DIR) not in sys.path:- sys.path.insert(0, str(CONFIG_DIR))-- # Create default if needed- if not LLM_CONFIG_FILE.exists():- _create_default_configs()-- # Import the module- spec = importlib.util.spec_from_file_location("llm_config", LLM_CONFIG_FILE)- llm_config = importlib.util.module_from_spec(spec)- spec.loader.exec_module(llm_config)-- # Extract configuration as dictionary- config = {}- for key in dir(llm_config):- if key.isupper() and not key.startswith("_"):- config[key] = getattr(llm_config, key)-- # Add the get_llm function- config["get_llm"] = getattr(llm_config, "get_llm", None)-- # Cache the result- _config_cache["llm"] = config-- return config- except Exception as e:- logger.error(f"Error loading LLM config: {e}")-- # Return minimal default config- return {- "DEFAULT_MODEL": "mistral",- "DEFAULT_MODEL_TYPE": "ollama",- "DEFAULT_TEMPERATURE": 0.7,- "MAX_TOKENS": 30000,- "USE_OPENAI_ENDPOINT": True,- "get_llm": None- }--def _apply_env_var_overrides(config: Dict[str, Any]) -> None:- """Apply environment variable overrides to configuration."""- prefix = "LDR_"- for env_name, env_value in os.environ.items():- if env_name.startswith(prefix):- # Remove prefix and convert to lowercase- key = env_name[len(prefix):].lower()-- # Handle nested keys with double underscore separator- if "__" in key:- parts = key.split("__")- curr = config- for part in parts[:-1]:- if part not in curr:- curr[part] = {}- curr = curr[part]-- # Set the value with type conversion- try:- # Try to infer the right type- if env_value.lower() in ("true", "yes", "1"):- curr[parts[-1]] = True- elif env_value.lower() in ("false", "no", "0"):- curr[parts[-1]] = False- elif env_value.isdigit():- curr[parts[-1]] = int(env_value)- elif env_value.replace(".", "", 1).isdigit():- curr[parts[-1]] = float(env_value)- else:- curr[parts[-1]] = env_value- except Exception as e:- logger.warning(f"Error setting config value from environment: {e}")- else:- # Handle top-level keys- # Find section containing this key- for section in config.values():- if isinstance(section, dict) and key in section:- try:- # Try to convert to the right type- orig_value = section[key]- if isinstance(orig_value, bool):- section[key] = env_value.lower() in ("true", "yes", "1")- elif isinstance(orig_value, int):- section[key] = int(env_value)- elif isinstance(orig_value, float):- section[key] = float(env_value)- else:- section[key] = env_value- except Exception as e:- logger.warning(f"Error converting environment variable: {e}")+ if _llm_config_cache is not None and not reload:+ return _llm_config_cache++ # Ensure config files exist+ ensure_config_files_exist()++ # Add config directory to path if needed+ if str(CONFIG_DIR) not in sys.path:+ sys.path.insert(0, str(CONFIG_DIR))++ # Import the module+ spec = importlib.util.spec_from_file_location("llm_config", LLM_CONFIG_FILE)+ llm_config = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(llm_config)++ # Extract configuration as dictionary+ config = {}+ for key in dir(llm_config):+ if key.isupper() and not key.startswith("_"):+ config[key] = getattr(llm_config, key)++ # Add the get_llm function+ config["get_llm"] = getattr(llm_config, "get_llm", None)++ # Cache the result+ _llm_config_cache = config++ return config-def save_main_config(config: Dict[str, Any]) -> None:+def save_main_config(config):"""Save main configuration to file."""- try:- # Ensure directory exists- CONFIG_DIR.mkdir(parents=True, exist_ok=True)-- # Write to file- with open(MAIN_CONFIG_FILE, "w") as f:- toml.dump(config, f)-- # Update cache- _config_cache["main"] = config-- logger.info(f"Saved main configuration to {MAIN_CONFIG_FILE}")- except Exception as e:- logger.error(f"Error saving main config: {e}")+ # Ensure directory exists+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)++ # Use Dynaconf's writer to save the config+ loaders.write(str(MAIN_CONFIG_FILE), config, env="default")++ # Reset settings to reload from file+ get_settings(reload=True)++ logger.info(f"Saved main configuration to {MAIN_CONFIG_FILE}")-def save_local_collections(collections: Dict[str, Dict[str, Any]]) -> None:+def save_local_collections(collections):"""Save local collections configuration to file."""- try:- # Ensure directory exists- CONFIG_DIR.mkdir(parents=True, exist_ok=True)-- # Write to file- with open(LOCAL_COLLECTIONS_FILE, "w") as f:- toml.dump(collections, f)-- # Update cache- _config_cache["local_collections"] = collections-- # Create document directories- for collection in collections.values():- for path in collection.get("paths", []):- Path(path).mkdir(parents=True, exist_ok=True)-- logger.info(f"Saved local collections configuration to {LOCAL_COLLECTIONS_FILE}")- except Exception as e:- logger.error(f"Error saving local collections config: {e}")+ # Ensure directory exists+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)++ # Use Dynaconf's writer to save the config+ loaders.write(str(LOCAL_COLLECTIONS_FILE), collections, env="default")++ # Reset settings to reload from file+ get_settings(reload=True)++ # Create document directories+ for collection in collections.values():+ for path in collection.get("paths", []):+ Path(path).mkdir(parents=True, exist_ok=True)++ logger.info(f"Saved local collections configuration to {LOCAL_COLLECTIONS_FILE}")-def get_config() -> Dict[str, Any]:+def get_config():"""Get combined configuration."""return {"main": load_main_config(),@@ -437,7 +299,7 @@ def get_llm(*args, **kwargs):if get_llm_func is None:# Fall back to utility function- from .utils.llm_utils import get_model+ from .utilties.llm_utils import get_modelreturn get_model(*args, **kwargs)return get_llm_func(*args, **kwargs)@@ -446,8 +308,6 @@ def get_search(search_tool=None):"""Get search tool instance based on configuration settings.- This is a compatibility wrapper for the old config.get_search function.-Args:search_tool: Override the search tool from configuration@@ -487,10 +347,10 @@ def get_search(search_tool=None):return engine-# Initialize configuration files if they don't exist-_create_default_configs()+# Initialize configuration at module load time+ensure_config_files_exist()-# Add at the end of config_manager.py+# API exports__all__ = ["get_config","get_llm",@@ -499,5 +359,11 @@ __all__ = ["load_llm_config","save_main_config","save_local_collections",- "get_search"+ "get_search",+ "get_data_dir",+ "get_cache_dir",+ "CONFIG_DIR",+ "MAIN_CONFIG_FILE",+ "LOCAL_COLLECTIONS_FILE",+ "LLM_CONFIG_FILE"]\ No newline at end of filediff --git a/src/local_deep_research/defaults/__init__.py b/src/local_deep_research/defaults/__init__.pyindex e69de29bb2..f0101379c3 100644--- a/src/local_deep_research/defaults/__init__.py+++ b/src/local_deep_research/defaults/__init__.py@@ -0,0 +1,43 @@+"""+Default configuration module for Local Deep Research.++This module is responsible for loading and initializing default+configuration files and resources used throughout the application.+"""+import os+import logging+from pathlib import Path++logger = logging.getLogger(__name__)++# Define the path to the package's defaults directory+DEFAULTS_DIR = Path(__file__).parent++# Default files available in this package+DEFAULT_FILES = {+ "main.toml": DEFAULTS_DIR / "main.toml",+ "local_collections.toml": DEFAULTS_DIR / "local_collections.toml",+ "llm_config.py": DEFAULTS_DIR / "llm_config.py"+}++def get_default_file_path(filename):+ """Get the path to a default configuration file."""+ if filename in DEFAULT_FILES:+ return DEFAULT_FILES[filename]+ return None++def list_default_files():+ """List all available default configuration files."""+ return list(DEFAULT_FILES.keys())++def ensure_defaults_exist():+ """Verify that all expected default files exist in the package."""+ missing = []+ for filename, filepath in DEFAULT_FILES.items():+ if not filepath.exists():+ missing.append(filename)++ if missing:+ logger.warning(f"The following default files are missing from the package: {', '.join(missing)}")+ return False+ return True\ No newline at end of filediff --git a/src/local_deep_research/defaults/local_collections.toml b/src/local_deep_research/defaults/local_collections.tomlnew file mode 100644index 0000000000..0e69b1939a--- /dev/null+++ b/src/local_deep_research/defaults/local_collections.toml@@ -0,0 +1,47 @@+# Default local document collections configuration+# Each collection functions as an independent search engine++# Project Documents Collection+[project_docs]+name = "Project Documents"+description = "Project documentation and specifications"+paths = ["__DATA_DIR__/documents/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_DIR__/local_search/project_docs"++# Research Papers Collection+[research_papers]+name = "Research Papers"+description = "Academic research papers and articles"+paths = ["__DATA_DIR__/documents/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+chunk_overlap = 150+cache_dir = "__CACHE_DIR__/local_search/research_papers"++# Personal Notes Collection+[personal_notes]+name = "Personal Notes"+description = "Personal notes and documents"+paths = ["__DATA_DIR__/documents/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+chunk_overlap = 100+cache_dir = "__CACHE_DIR__/local_search/personal_notes"\ No newline at end of filediff --git a/src/local_deep_research/utilties/setup_utils.py b/src/local_deep_research/utilties/setup_utils.pyindex 377a748cc8..056f2bd8ec 100644--- a/src/local_deep_research/utilties/setup_utils.py+++ b/src/local_deep_research/utilties/setup_utils.py@@ -1,210 +1,6 @@-# utilties/setup_utils.py-"""-Setup utilities for Local Deep Research.--This module handles initial setup of configuration and directories.-"""--import os-import logging-import shutil-from pathlib import Path-import toml--logger = logging.getLogger(__name__)-+"""Setup utilities (legacy wrapper)."""def setup_user_directories():- """Create the necessary directories and configuration files."""- import os- import logging- from pathlib import Path-- logger = logging.getLogger(__name__)- logger.info("Setting up user directories and configuration...")-- # Import configuration paths- from ..config_manager import CONFIG_DIR, MAIN_CONFIG_FILE, LOCAL_COLLECTIONS_FILE, LLM_CONFIG_FILE- from ..config_manager import get_data_dir, get_cache_dir-- # Print paths for debugging- logger.info(f"Config directory: {CONFIG_DIR}")- logger.info(f"Main config file: {MAIN_CONFIG_FILE}")- logger.info(f"Local collections file: {LOCAL_COLLECTIONS_FILE}")- logger.info(f"LLM config file: {LLM_CONFIG_FILE}")-- # Create config directory- logger.info(f"Creating directory: {CONFIG_DIR}")- CONFIG_DIR.mkdir(parents=True, exist_ok=True)-- # Create config files- _create_default_config_files(MAIN_CONFIG_FILE, LOCAL_COLLECTIONS_FILE, LLM_CONFIG_FILE)-- # Create data directories- data_dir = get_data_dir()- logger.info(f"Creating data directory: {data_dir}")- data_dir.mkdir(parents=True, exist_ok=True)-- # Create document directories- docs_dir = data_dir / "documents"- docs_dir.mkdir(parents=True, exist_ok=True)- (docs_dir / "project_documents").mkdir(exist_ok=True)- (docs_dir / "research_papers").mkdir(exist_ok=True)- (docs_dir / "personal_notes").mkdir(exist_ok=True)-- # Create output directory- (data_dir / "research_outputs").mkdir(parents=True, exist_ok=True)-- # Create cache directories- cache_dir = get_cache_dir()- cache_dir.mkdir(parents=True, exist_ok=True)- (cache_dir / "local_search").mkdir(exist_ok=True)-- logger.info("User directories and configuration files created successfully")--def _create_default_config_files(main_config_file, collections_file, llm_config_file):- """- Create default configuration files from package resources.-- Args:- main_config_file: Path to main configuration file- collections_file: Path to collections configuration file- llm_config_file: Path to LLM configuration file- """- try:- # Import from package resources- import importlib.resources-- # Create main.toml if it doesn't exist- if not main_config_file.exists():- try:- with importlib.resources.path('local_deep_research.defaults', 'main.toml') as default_main:- shutil.copy(default_main, main_config_file)- logger.info(f"Created default main configuration at {main_config_file}")- except (ImportError, FileNotFoundError) as e:- logger.warning(f"Could not copy default main config: {e}")- _create_simple_main_config(main_config_file)-- # Create local_collections.toml if it doesn't exist- if not collections_file.exists():- try:- with importlib.resources.path('local_deep_research.defaults', 'local_collections.toml') as default_collections:- shutil.copy(default_collections, collections_file)- logger.info(f"Created default collections configuration at {collections_file}")- except (ImportError, FileNotFoundError) as e:- logger.warning(f"Could not copy default collections config: {e}")- _create_simple_collections_config(collections_file)-- # Create llm_config.py if it doesn't exist- if not llm_config_file.exists():- try:- with importlib.resources.path('local_deep_research.defaults', 'llm_config.py') as default_llm:- shutil.copy(default_llm, llm_config_file)- logger.info(f"Created default LLM configuration at {llm_config_file}")- except (ImportError, FileNotFoundError) as e:- logger.warning(f"Could not copy default LLM config: {e}")- _create_simple_llm_config(llm_config_file)-- except Exception as e:- logger.error(f"Error creating default configuration files: {e}")--def _create_simple_main_config(config_file):- """Create a simple main configuration file."""- from ..config_manager import DEFAULT_MAIN_CONFIG-- try:- with open(config_file, 'w') as f:- toml.dump(DEFAULT_MAIN_CONFIG, f)- logger.info(f"Created simple main configuration at {config_file}")- except Exception as e:- logger.error(f"Error creating simple main config: {e}")--def _create_simple_collections_config(config_file):- """Create a simple collections configuration file."""- from ..config_manager import DEFAULT_LOCAL_COLLECTIONS, get_data_dir, get_cache_dir-- # Update paths- collections = DEFAULT_LOCAL_COLLECTIONS.copy()- for collection_name, collection in collections.items():- # Set paths to default locations- collection["paths"] = [str(get_data_dir() / "documents" / collection_name.replace("_", "-"))]-- # Set cache dir- collection["cache_dir"] = str(get_cache_dir() / "local_search" / collection_name)-- try:- with open(config_file, 'w') as f:- toml.dump(collections, f)- logger.info(f"Created simple collections configuration at {config_file}")- except Exception as e:- logger.error(f"Error creating simple collections config: {e}")--def _create_simple_llm_config(config_file):- """Create a simple LLM configuration file."""- default_content = """# Default LLM configuration-DEFAULT_MODEL = "mistral"-DEFAULT_MODEL_TYPE = "ollama"-DEFAULT_TEMPERATURE = 0.7-MAX_TOKENS = 30000--# OpenAI Endpoint configuration-USE_OPENAI_ENDPOINT = True-OPENAI_ENDPOINT_URL = "https://openrouter.ai/api/v1"-OPENAI_ENDPOINT_REQUIRES_MODEL = True--from langchain_anthropic import ChatAnthropic-from langchain_openai import ChatOpenAI-from langchain_ollama import ChatOllama-from langchain_community.llms import VLLM, Ollama-import os-import logging--logger = logging.getLogger(__name__)--def get_llm(model_name=None, model_type=None, temperature=None, **kwargs):- '''Get LLM instance based on model name and type.'''- # Use defaults if not specified- if model_name is None:- model_name = DEFAULT_MODEL- if model_type is None:- model_type = DEFAULT_MODEL_TYPE- if temperature is None:- temperature = DEFAULT_TEMPERATURE-- # Common parameters- common_params = {- "temperature": temperature,- "max_tokens": kwargs.get("max_tokens", MAX_TOKENS),- }- common_params.update(kwargs)-- # Simple pattern matching for model types- if model_type == "ollama":- try:- return ChatOllama(model=model_name, **common_params)- except (ImportError, Exception):- from langchain_community.llms import Ollama- return Ollama(model=model_name, **common_params)- elif model_type == "openai":- api_key = os.getenv("OPENAI_API_KEY")- if not api_key:- logger.warning("OPENAI_API_KEY not found. Falling back to default model.")- return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)- return ChatOpenAI(model=model_name, api_key=api_key, **common_params)- elif model_type == "anthropic":- api_key = os.getenv("ANTHROPIC_API_KEY")- if not api_key:- logger.warning("ANTHROPIC_API_KEY not found. Falling back to default model.")- return get_llm(DEFAULT_MODEL, DEFAULT_MODEL_TYPE, temperature, **kwargs)- return ChatAnthropic(model=model_name, anthropic_api_key=api_key, **common_params)- else:- # Default to Ollama- return ChatOllama(model=model_name, **common_params)-"""-- try:- with open(config_file, 'w') as f:- f.write(default_content)- logger.info(f"Created simple LLM configuration at {config_file}")- except Exception as e:- logger.error(f"Error creating simple LLM config: {e}")\ No newline at end of file+ """Set up directories (delegated to config_manager)."""+ from ..config_manager import ensure_config_files_exist+ ensure_config_files_exist()\ No newline at end of filediff --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 3d3f82769f..036678cad4 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@@ -226,9 +226,8 @@ SEARCH_ENGINES["auto"] = SEARCH_ENGINES["auto"]DEFAULT_SEARCH_ENGINE = "wikipedia"-# Import local collectionstry:- from local_collections import register_local_collections+ from ..local_collections import register_local_collections# Register all enabled local collections as search enginesregister_local_collections(SEARCH_ENGINES)@@ -236,7 +235,7 @@ try: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 collectionsSEARCH_ENGINES["local_all"] = {