Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Completely excise remaining references to config files.

Daniel Pettiad2488bb2a1e
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
index a7c7c40a08..09c1a73d8e 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
@@ -10,7 +10,6 @@ from typing import Dict, List
from langchain_core.language_models import BaseLLM
from ...citation_handler import CitationHandler
-from ...config.config_files import settings
from ...config.llm_config import get_llm
from ...config.search_config import get_search
from ...utilities.db_utils import get_db_setting
@@ -396,13 +395,7 @@ Please try again with a different query or contact support.
"""
# Compress knowledge if needed
- if (
- get_db_setting(
- "general.knowledge_accumulation",
- settings.general.knowledge_accumulation,
- )
- == "ITERATION"
- ):
+ if get_db_setting("general.knowledge_accumulation", "ITERATION") == "ITERATION":
try:
self._update_progress(
"Compressing knowledge", 90, {"phase": "knowledge_compression"}
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
index 8922617b45..f81381bec6 100644
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
@@ -3,7 +3,6 @@ import logging
from typing import Dict
from ...citation_handler import CitationHandler
-from ...config.config_files import settings
from ...config.llm_config import get_llm
from ...config.search_config import get_search
from ...utilities.db_utils import get_db_setting
@@ -117,7 +116,7 @@ Iteration: {iteration + 1} of {total_iterations}"""
question_count = len(questions)
knowledge_accumulation = get_db_setting(
"general.knowledge_accumulation",
- settings.general.knowledge_accumulation,
+ "ITERATION",
)
for q_idx, question in enumerate(questions):
question_progress_base = iteration_progress_base + (
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 779f6478e3..61646a226c 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -4,11 +4,8 @@ Provides programmatic access to search and research capabilities.
"""
import logging
-import os
from typing import Any, Callable, Dict, Optional
-import toml
-
from .. import get_report_generator # Use the lazy import function
from ..config.llm_config import get_llm
from ..config.search_config import get_search
@@ -297,46 +294,3 @@ def analyze_documents(
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 engines
- descriptions = {
- "auto": "Automatic selection based on query type",
- "wikipedia": "Wikipedia articles and general knowledge",
- "arxiv": "Scientific papers and research",
- "pubmed": "Medical and biomedical literature",
- "semantic_scholar": "Academic papers across all fields",
- "github": "Code repositories and technical documentation",
- "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
-
- if os.path.exists(LOCAL_COLLECTIONS_FILE):
- collections = toml.load(LOCAL_COLLECTIONS_FILE)
- return collections
-
- return {}
diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.py
index 8bb978c340..02ad8cc501 100644
--- a/src/local_deep_research/citation_handler.py
+++ b/src/local_deep_research/citation_handler.py
@@ -4,7 +4,6 @@ from typing import Any, Dict, List, Union
from langchain_core.documents import Document
-from .config.config_files import settings
from .utilities.db_utils import get_db_setting
@@ -94,9 +93,7 @@ Provide a detailed analysis with citations. Do not create the bibliography, it w
{formatted_sources}
Return any inconsistencies or conflicts found."""
- if get_db_setting(
- "general.enable_fact_checking", settings.general.enable_fact_checking
- ):
+ if get_db_setting("general.enable_fact_checking", True):
fact_check_response = self.llm.invoke(fact_check_prompt).content
else:
diff --git a/src/local_deep_research/config/config_files.py b/src/local_deep_research/config/config_files.py
deleted file mode 100644
index 5774647240..0000000000
--- a/src/local_deep_research/config/config_files.py
+++ /dev/null
@@ -1,245 +0,0 @@
-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"
-
-# Define data directory for database
-DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "data"))
-os.makedirs(DATA_DIR, exist_ok=True)
-DB_PATH = os.path.join(DATA_DIR, "ldr.db")
-
-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}")
- # Add note about database-first settings
- with open(settings_file, "a") as f:
- f.write(
- "\n\n# NOTE: Settings in this file are used as fallback only.\n"
- )
- f.write(
- "# Settings stored in the database (ldr.db) take precedence.\n"
- )
- f.write(
- "# To modify settings permanently, use the web interface settings page.\n"
- )
-
- # 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}")
- # Add note about database-first settings
- with open(search_engines_file, "a") as f:
- f.write(
- "\n\n# NOTE: Settings in this file are used as fallback only.\n"
- )
- f.write(
- "# Settings stored in the database (ldr.db) take precedence.\n"
- )
- f.write(
- "# To modify search settings permanently, use the web interface settings page.\n"
- )
-
- # 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}")
- # Add note about database-first settings
- with open(settings_file, "a") as f:
- f.write(
- "\n\n# NOTE: Settings in this file are used as fallback only.\n"
- )
- f.write("# Settings stored in the database (ldr.db) take precedence.\n")
- f.write(
- "# To modify settings permanently, use the web interface settings page.\n"
- )
-
- # 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}")
- # Add note about database-first settings
- with open(search_engines_file, "a") as f:
- f.write(
- "\n\n# NOTE: Settings in this file are used as fallback only.\n"
- )
- f.write("# Settings stored in the database (ldr.db) take precedence.\n")
- f.write(
- "# To modify search settings permanently, use the web interface settings page.\n"
- )
-
- 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"
- """
- )
-
-
-# Add a comment to explain the DB-first settings approach
-logger.info(
- "Using database-first settings approach. TOML files are used as fallback only."
-)
-
-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/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index a5e5ebed02..39cb00388c 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -1,8 +1,6 @@
import logging
import os
-from pathlib import Path
-from dynaconf.vendor.box.exceptions import BoxKeyError
from langchain_anthropic import ChatAnthropic
from langchain_community.llms import VLLM
from langchain_ollama import ChatOllama
@@ -10,7 +8,6 @@ from langchain_openai import ChatOpenAI
from ..utilities.db_utils import get_db_setting
from ..utilities.search_utilities import remove_think_tags
-from .config_files import CONFIG_DIR, settings
# Setup logging
logger = logging.getLogger(__name__)
@@ -26,7 +23,14 @@ VALID_PROVIDERS = [
"llamacpp",
"none",
]
-SECRETS_FILE = CONFIG_DIR / ".secrets.toml"
+
+
+# Environment variables to use. Will override DB settings if set.
+OPENAI_API_KEY_ENV = "LDR_OPENAI_API_KEY"
+ANTHROPIC_API_KEY_ENV = "LDR_ANTHROPIC_API_KEY"
+OPENAI_ENDPOINT_API_KEY_ENV = "LDR_OPENAI_ENDPOINT_API_KEY"
+OLLAMA_BASE_URL_ENV = "LDR_OLLAMA_BASE_URL"
+LMSTUDIO_URL_ENV = "LDR_LMSTUDIO_URL"
def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_url=None):
@@ -46,11 +50,11 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
# Use database values for parameters if not provided
if model_name is None:
- model_name = get_db_setting("llm.model", settings.llm.model)
+ model_name = get_db_setting("llm.model", "gemma:latest")
if temperature is None:
- temperature = get_db_setting("llm.temperature", settings.llm.temperature)
+ temperature = get_db_setting("llm.temperature", 0.7)
if provider is None:
- provider = get_db_setting("llm.provider", settings.llm.provider)
+ provider = get_db_setting("llm.provider", "ollama")
# Clean model name: remove quotes and extra whitespace
if model_name:
@@ -77,21 +81,14 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
common_params = {
"temperature": temperature,
}
- try:
- common_params["max_tokens"] = settings.llm.max_tokens
- except BoxKeyError:
- # Some providers don't support this parameter, in which case it can
- # be omitted.
- pass
+ if get_db_setting("llm.supports_max_tokens", True):
+ common_params["max_tokens"] = get_db_setting("llm.max_tokens", 30000)
# Handle different providers
if provider == "anthropic":
- api_key_name = "ANTHROPIC_API_KEY"
- api_key = settings.get(api_key_name, "")
+ api_key = os.getenv(ANTHROPIC_API_KEY_ENV)
if not api_key:
- api_key = os.getenv(api_key_name)
- if not api_key:
- api_key = os.getenv("LDR_" + api_key_name)
+ api_key = get_db_setting("llm.anthropic.api_key")
if not api_key:
logger.warning(
"ANTHROPIC_API_KEY not found. Falling back to default model."
@@ -104,12 +101,9 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
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)
+ api_key = os.getenv(OPENAI_API_KEY_ENV)
if not api_key:
- api_key = os.getenv("LDR_" + api_key_name)
+ api_key = get_db_setting("llm.openai.api_key")
if not api_key:
logger.warning("OPENAI_API_KEY not found. Falling back to default model.")
return get_fallback_model(temperature)
@@ -118,12 +112,9 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
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 = os.getenv(OPENAI_ENDPOINT_API_KEY_ENV)
if not api_key:
- api_key = os.getenv(api_key_name)
- if not api_key:
- api_key = os.getenv("LDR_" + api_key_name)
+ api_key = get_db_setting("llm.openai_endpoint.api_key")
if not api_key:
logger.warning(
"OPENAI_ENDPOINT_API_KEY not found. Falling back to default model."
@@ -133,7 +124,7 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
# Get endpoint URL from settings
if openai_endpoint_url is not None:
openai_endpoint_url = get_db_setting(
- "llm.openai_endpoint_url", settings.llm.openai_endpoint_url
+ "llm.openai_endpoint.url", "https://openrouter.ai/api/v1"
)
llm = ChatOpenAI(
@@ -163,10 +154,9 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
elif provider == "ollama":
try:
# Use the configurable Ollama base URL
- base_url = os.getenv(
- "OLLAMA_BASE_URL",
- settings.llm.get("ollama_base_url", "http://localhost:11434"),
- )
+ base_url = os.getenv(OLLAMA_BASE_URL_ENV)
+ if not base_url:
+ base_url = get_db_setting("llm.ollama.url", "http://localhost:11434")
# Check if Ollama is available before trying to use it
if not is_ollama_available():
@@ -230,15 +220,16 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
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 = get_db_setting("llm.lmstudio_url", lmstudio_url)
+ lmstudio_url = os.getenv(LMSTUDIO_URL_ENV)
+ if not lmstudio_url:
+ lmstudio_url = get_db_setting("llm.lmstudio.url", lmstudio_url)
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=get_db_setting("llm.max_tokens", settings.llm.max_tokens),
+ max_tokens=get_db_setting("llm.max_tokens", 30000),
)
return wrap_llm_without_think_tags(llm)
@@ -247,25 +238,21 @@ def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_ur
from langchain_community.llms import LlamaCpp
# Get LlamaCpp model path from settings
- model_path = settings.llm.get("llamacpp_model_path", "")
- model_path = get_db_setting("llm.llamacpp_model_path", model_path)
+ model_path = get_db_setting("llm.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")
# Get additional LlamaCpp parameters
- n_gpu_layers = settings.llm.get("llamacpp_n_gpu_layers", 1)
- n_gpu_layers = get_db_setting("llm.llamacpp_n_gpu_layers", n_gpu_layers)
- n_batch = settings.llm.get("llamacpp_n_batch", 512)
- n_batch = get_db_setting("llm.llamacpp_n_batch", n_batch)
- f16_kv = settings.llm.get("llamacpp_f16_kv", True)
- f16_kv = get_db_setting("llm.llamacpp_f16_kv", f16_kv)
+ n_gpu_layers = get_db_setting("llm.llamacpp_n_gpu_layers", 1)
+ n_batch = get_db_setting("llm.llamacpp_n_batch", 512)
+ f16_kv = get_db_setting("llm.llamacpp_f16_kv", True)
# Create LlamaCpp instance
llm = LlamaCpp(
model_path=model_path,
temperature=temperature,
- max_tokens=get_db_setting("llm.max_tokens", settings.llm.max_tokens),
+ max_tokens=get_db_setting("llm.max_tokens", 30000),
n_gpu_layers=n_gpu_layers,
n_batch=n_batch,
f16_kv=f16_kv,
@@ -354,9 +341,9 @@ def get_available_provider_types():
def is_openai_available():
"""Check if OpenAI is available"""
try:
- api_key = settings.get("OPENAI_API_KEY", "")
+ api_key = os.getenv(OPENAI_API_KEY_ENV)
if not api_key:
- api_key = os.getenv("OPENAI_API_KEY")
+ api_key = get_db_setting("llm.openai.api_key")
return bool(api_key)
except Exception:
return False
@@ -365,9 +352,9 @@ def is_openai_available():
def is_anthropic_available():
"""Check if Anthropic is available"""
try:
- api_key = settings.get("ANTHROPIC_API_KEY", "")
+ api_key = os.getenv(ANTHROPIC_API_KEY_ENV)
if not api_key:
- api_key = os.getenv("ANTHROPIC_API_KEY")
+ api_key = get_db_setting("llm.anthropic.api_key")
return bool(api_key)
except Exception:
return False
@@ -376,9 +363,9 @@ def is_anthropic_available():
def is_openai_endpoint_available():
"""Check if OpenAI endpoint is available"""
try:
- api_key = settings.get("OPENAI_ENDPOINT_API_KEY", "")
+ api_key = os.getenv(OPENAI_ENDPOINT_API_KEY_ENV)
if not api_key:
- api_key = os.getenv("OPENAI_ENDPOINT_API_KEY")
+ api_key = get_db_setting("llm.openai_endpoint.api_key")
return bool(api_key)
except Exception:
return False
@@ -390,8 +377,8 @@ def is_ollama_available():
import requests
base_url = os.getenv(
- "OLLAMA_BASE_URL",
- settings.llm.get("ollama_base_url", "http://localhost:11434"),
+ OLLAMA_BASE_URL_ENV,
+ get_db_setting("llm.ollama.url", "http://localhost:11434"),
)
logger.info(f"Checking Ollama availability at {base_url}/api/tags")
@@ -434,8 +421,9 @@ def is_lmstudio_available():
try:
import requests
- lmstudio_url = settings.llm.get("lmstudio_url", "http://localhost:1234")
- lmstudio_url = get_db_setting("llm.lmstudio_url", lmstudio_url)
+ lmstudio_url = os.getenv(LMSTUDIO_URL_ENV)
+ if not lmstudio_url:
+ lmstudio_url = get_db_setting("llm.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
@@ -448,8 +436,7 @@ def is_llamacpp_available():
try:
from langchain_community.llms import LlamaCpp # noqa: F401
- model_path = settings.llm.get("llamacpp_model_path", "")
- model_path = get_db_setting("llm.llamacpp_model_path", model_path)
+ model_path = get_db_setting("llm.llamacpp_model_path")
return bool(model_path) and os.path.exists(model_path)
except Exception:
return False
@@ -460,9 +447,8 @@ def get_available_providers():
return get_available_provider_types()
-secrets_file = Path(SECRETS_FILE)
AVAILABLE_PROVIDERS = get_available_providers()
-selected_provider = get_db_setting("llm.provider", settings.llm.provider).lower()
+selected_provider = get_db_setting("llm.provider", "ollama").lower()
# Log which providers are available
logger.info(f"Available providers: {list(AVAILABLE_PROVIDERS.keys())}")
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index 4c0946c15f..d49f8149da 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -3,7 +3,6 @@ import logging
from ..utilities.db_utils import get_db_setting
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
@@ -13,9 +12,7 @@ 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 = get_db_setting(
- "search.snippets_only", settings.search.snippets_only
-)
+SEARCH_SNIPPETS_ONLY = get_db_setting("search.snippets_only", True)
# Expose get_search function
@@ -29,7 +26,7 @@ def get_search(search_tool=None, llm_instance=None):
"""
# Use specified tool or default from settings
- tool = search_tool or get_db_setting("search.tool", settings.search.tool)
+ tool = search_tool or get_db_setting("search.tool", "auto")
logger.info(f"Creating search engine with tool: {tool}")
# Get LLM instance (use provided or get fresh one)
@@ -39,23 +36,13 @@ def get_search(search_tool=None, llm_instance=None):
params = {
"search_tool": tool,
"llm_instance": llm,
- "max_results": get_db_setting(
- "search.max_results", settings.search.max_results
- ),
- "region": get_db_setting("search.region", settings.search.region),
- "time_period": get_db_setting(
- "search.time_period", settings.search.time_period
- ),
- "safe_search": get_db_setting(
- "search.safe_search", settings.search.safe_search
- ),
+ "max_results": get_db_setting("search.max_results", 10),
+ "region": get_db_setting("search.region", "wt-wt"),
+ "time_period": get_db_setting("search.time_period", "all"),
+ "safe_search": get_db_setting("search.safe_search", True),
"search_snippets_only": SEARCH_SNIPPETS_ONLY,
- "search_language": get_db_setting(
- "search.search_language", settings.search.search_language
- ),
- "max_filtered_results": get_db_setting(
- "search.max_filtered_results", settings.search.max_filtered_results
- ),
+ "search_language": get_db_setting("search.search_language", "English"),
+ "max_filtered_results": get_db_setting("search.max_filtered_results", 5),
}
# Log NULL parameters for debugging
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 2bfc4e8a05..0c8c120afe 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -166,9 +166,9 @@
"value": 1,
"visible": true
},
- "llm.lmstudio_url": {
+ "llm.lmstudio.url": {
"category": null,
- "description": "Setting for llm.lmstudio_url",
+ "description": "URL of the LMStudio endpoint.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -194,6 +194,20 @@
"value": 30000,
"visible": true
},
+ "llm.supports_max_tokens": {
+ "category": "llm_parameters",
+ "description": "Whether the LLM API supports the 'max_tokens' option.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Supports 'Max Tokens'",
+ "options": null,
+ "step": null,
+ "type": "LLM",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
"llm.model": {
"category": "llm_general",
"description": "Language model to use for research and analysis",
@@ -237,9 +251,9 @@
"value": "gemma3:12b",
"visible": true
},
- "llm.openai_endpoint_url": {
+ "llm.openai_endpoint.url": {
"category": null,
- "description": "Setting for llm.openai_endpoint_url",
+ "description": "URL of the OpenAI-compatible endpoint.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -251,6 +265,20 @@
"value": "https://openrouter.ai/api/v1",
"visible": true
},
+ "llm.ollama.url": {
+ "category": null,
+ "description": "URL of the Ollama endpoint.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Ollama Endpoint Url",
+ "options": null,
+ "step": null,
+ "type": "LLM",
+ "ui_element": "text",
+ "value": "http://localhost:11434",
+ "visible": true
+ },
"llm.provider": {
"category": "llm_general",
"description": "Service provider for the language model",
@@ -304,6 +332,48 @@
"value": 0.7,
"visible": true
},
+ "llm.anthropic.api_key": {
+ "category": "llm_general",
+ "description": "API key to use for the Anthropic provider.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Anthropic API Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "ANTHROPIC_API_KEY",
+ "visible": true
+ },
+ "llm.openai.api_key": {
+ "category": "llm_general",
+ "description": "API key to use for the OpenAI provider.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "OpenAI API Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "OPENAI_API_KEY",
+ "visible": true
+ },
+ "llm.openai_endpoint.api_key": {
+ "category": "llm_general",
+ "description": "API key to use for the OpenAI-compatible endpoint provider.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "OpenAI Endpoint API Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "OPENAI_ENDPOINT_API_KEY",
+ "visible": true
+ },
"report.detailed_citations": {
"category": "report_parameters",
"description": "Include detailed citations in reports",
@@ -1044,17 +1114,17 @@
"value": "Search the web using the Brave search engine.",
"visible": false
},
- "search.engine.web.brave.api_key_env": {
+ "search.engine.web.brave.api_key": {
"category": "brave",
- "description": "Setting for brave.api_key_env",
+ "description": "The Brave API key to use.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Api Key Env",
+ "name": "Api Key",
"options": null,
"step": null,
"type": "SEARCH",
- "ui_element": "text",
+ "ui_element": "password",
"value": "BRAVE_API_KEY",
"visible": true
},
@@ -1544,17 +1614,17 @@
"value": "Search the web using Google's Programmable Search Engine API.",
"visible": false
},
- "search.engine.web.google_pse.api_key_env": {
+ "search.engine.web.google_pse.api_key": {
"category": "google_pse",
- "description": "Setting for google_pse.api_key_env",
+ "description": "The Google PSE API key to use.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Api Key Env",
+ "name": "Api Key",
"options": null,
"step": null,
"type": "SEARCH",
- "ui_element": "text",
+ "ui_element": "password",
"value": "GOOGLE_PSE_API_KEY",
"visible": true
},
@@ -1978,15 +2048,24 @@
},
"search.engine.local.personal_notes.embedding_model_type": {
"category": "personal_notes",
- "description": "Setting for personal_notes.embedding_model_type",
+ "description": "Model provider to use for generating document embeddings.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Embedding Model Type",
- "options": null,
+ "options": [
+ {
+ "label": "SentenceTransformers",
+ "value": "sentence_transformers"
+ },
+ {
+ "label": "Ollama",
+ "value": "ollama"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
+ "ui_element": "select",
"value": "sentence_transformers",
"visible": true
},
@@ -2206,15 +2285,24 @@
},
"search.engine.local.project_docs.embedding_model_type": {
"category": "project_docs",
- "description": "Setting for project_docs.embedding_model_type",
+ "description": "Model provider to use for generating document embeddings.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Embedding Model Type",
- "options": null,
+ "options": [
+ {
+ "label": "SentenceTransformers",
+ "value": "sentence_transformers"
+ },
+ {
+ "label": "Ollama",
+ "value": "ollama"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
+ "ui_element": "select",
"value": "sentence_transformers",
"visible": true
},
@@ -2367,18 +2455,18 @@
"value": "Search papers indexed by PubMed.",
"visible": false
},
- "search.engine.web.pubmed.api_key_env": {
+ "search.engine.web.pubmed.api_key": {
"category": "pubmed",
- "description": "Setting for pubmed.api_key_env",
+ "description": "The PubMed API key to use.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Api Key Env",
+ "name": "Api Key",
"options": null,
"step": null,
"type": "SEARCH",
- "ui_element": "text",
- "value": "NCBI_API_KEY",
+ "ui_element": "password",
+ "value": "PUBMED_API_KEY",
"visible": true
},
"search.engine.web.pubmed.class_name": {
@@ -2669,15 +2757,24 @@
},
"search.engine.local.research_papers.embedding_model_type": {
"category": "research_papers",
- "description": "Setting for research_papers.embedding_model_type",
+ "description": "Model provider to use for generating document embeddings.",
"editable": true,
"max_value": null,
"min_value": null,
"name": "Embedding Model Type",
- "options": null,
+ "options": [
+ {
+ "label": "SentenceTransformers",
+ "value": "sentence_transformers"
+ },
+ {
+ "label": "Ollama",
+ "value": "ollama"
+ }
+ ],
"step": null,
"type": "SEARCH",
- "ui_element": "text",
+ "ui_element": "select",
"value": "sentence_transformers",
"visible": true
},
@@ -2830,18 +2927,18 @@
"value": "A locally-hosted meta-search engine.",
"visible": false
},
- "search.engine.web.searxng.api_key_env": {
+ "search.engine.web.searxng.api_key": {
"category": "searxng",
- "description": "Setting for searxng.api_key_env",
+ "description": "The SearXNG API key to use.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Api Key Env",
+ "name": "Api Key",
"options": null,
"step": null,
"type": "SEARCH",
- "ui_element": "text",
- "value": "SEARXNG_INSTANCE",
+ "ui_element": "password",
+ "value": "SEARXNG_API_KEY",
"visible": true
},
"search.engine.web.searxng.class_name": {
@@ -3095,17 +3192,17 @@
"value": "Search the web with Google's search API.",
"visible": false
},
- "search.engine.web.serpapi.api_key_env": {
+ "search.engine.web.serpapi.api_key": {
"category": "serpapi",
- "description": "Setting for serpapi.api_key_env",
+ "description": "The Serp API key to use.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Api Key Env",
+ "name": "API Key",
"options": null,
"step": null,
"type": "SEARCH",
- "ui_element": "text",
+ "ui_element": "password",
"value": "SERP_API_KEY",
"visible": true
},
diff --git a/src/local_deep_research/defaults/local_collections.toml b/src/local_deep_research/defaults/local_collections.toml
deleted file mode 100644
index f26aa97e04..0000000000
--- a/src/local_deep_research/defaults/local_collections.toml
+++ /dev/null
@@ -1,53 +0,0 @@
-# Project Documents Collection
-[project_docs]
-name = "Project Documents"
-description = "Project documentation and specifications"
-paths = ["@format ${DOCS_DIR}/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"
-strengths = ["project documentation", "specifications", "internal documents"]
-weaknesses = ["no external information", "limited to organizational knowledge"]
-reliability = 0.9
-
-# Research Papers Collection
-[research_papers]
-name = "Research Papers"
-description = "Academic research papers and articles"
-paths = ["@format ${DOCS_DIR}/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"
-strengths = ["academic research", "scientific papers", "scholarly content"]
-weaknesses = ["potentially outdated", "limited to collected papers"]
-reliability = 0.85
-
-# Personal Notes Collection
-[personal_notes]
-name = "Personal Notes"
-description = "Personal notes and documents"
-paths = ["@format ${DOCS_DIR}/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"
-strengths = ["personal knowledge", "notes", "private documents"]
-weaknesses = ["subjective content", "informal information"]
-reliability = 0.75
\ No newline at end of file
diff --git a/src/local_deep_research/defaults/main.toml b/src/local_deep_research/defaults/main.toml
deleted file mode 100644
index f9024052d5..0000000000
--- a/src/local_deep_research/defaults/main.toml
+++ /dev/null
@@ -1,80 +0,0 @@
-
-# Main configuration for Local Deep Research
-
-[web]
-port = 5000
-host = "0.0.0.0"
-debug = true
-
-[llm]
-# LLM provider (one of: ollama, openai, anthropic, vllm, openai_endpoint, lmstudio, llamacpp)
-provider = "ollama"
-# Model name
-model = "gemma3:12b"
-# Temperature
-temperature = 0.7
-# Maximum tokens
-max_tokens = 30000
-# OpenAI-compatible endpoint URL
-openai_endpoint_url = "https://openrouter.ai/api/v1"
-# LM Studio URL (default: http://localhost:1234)
-lmstudio_url = "http://localhost:1234"
-# LlamaCpp model path
-llamacpp_model_path = ""
-# LlamaCpp parameters
-llamacpp_n_gpu_layers = 1
-llamacpp_n_batch = 512
-llamacpp_f16_kv = true
-
-[general]
-# Directory for research outputs (relative to user data directory)
-output_dir = "research_outputs"
-# Knowledge accumulation approach (NONE, QUESTION, or ITERATION)
-knowledge_accumulation = "ITERATION"
-# Maximum context size for knowledge accumulation
-knowledge_accumulation_context_limit = 2000000
-# Enable fact checking (experimental, works better with large LLMs)
-enable_fact_checking = false
-
-
-[search]
-# Search tool to use (auto, wikipedia, arxiv, duckduckgo, serpapi, google_pse,etc.)
-# "auto" intelligently selects based on query content (recommended)
-# "local_all" searches only local document collections
-tool = "auto"
-
-# Number of research cycles
-iterations = 2
-
-# Questions generated per cycle
-questions_per_iteration = 2
-
-# Searches per report section
-searches_per_section = 2
-
-# Results per search query
-max_results = 50
-
-# Results after relevance filtering
-max_filtered_results = 5
-
-# Search region
-region = "us"
-
-# Time period (d=day, w=week, m=month, y=year)
-time_period = "y"
-
-# Enable safe search
-safe_search = true
-
-# Search language
-search_language = "English"
-
-# Return only snippets, not full content (faster but less detailed)
-snippets_only = true
-
-# Skip relevance filtering (return all results)
-skip_relevance_filter = false
-
-# Check URL quality
-quality_check_urls = true
diff --git a/src/local_deep_research/defaults/search_engines.toml b/src/local_deep_research/defaults/search_engines.toml
deleted file mode 100644
index 328ead9073..0000000000
--- a/src/local_deep_research/defaults/search_engines.toml
+++ /dev/null
@@ -1,291 +0,0 @@
-# Search Engines Configuration for Local Deep Research
-# This file defines all available search engines and their properties
-
-[wikipedia]
-module_path = ".engines.search_engine_wikipedia"
-class_name = "WikipediaSearchEngine"
-requires_api_key = false
-reliability = 0.95
-strengths = [
- "factual information", "general knowledge", "definitions",
- "historical facts", "biographies", "overview information"
-]
-weaknesses = ["recent events", "specialized academic topics", "product comparisons"]
-
-[wikipedia.default_params]
-max_results = 20
-include_content = true
-
-[arxiv]
-module_path = ".engines.search_engine_arxiv"
-class_name = "ArXivSearchEngine"
-requires_api_key = false
-reliability = 0.9
-strengths = [
- "scientific papers", "academic research", "physics", "computer science",
- "mathematics", "statistics", "machine learning", "preprints"
-]
-weaknesses = ["non-academic topics", "consumer products", "news", "general information"]
-
-[arxiv.default_params]
-max_results = 20
-sort_by = "relevance"
-sort_order = "descending"
-
-[pubmed]
-module_path = ".engines.search_engine_pubmed"
-class_name = "PubMedSearchEngine"
-requires_api_key = false
-api_key_env = "NCBI_API_KEY"
-reliability = 0.98
-strengths = [
- "biomedical literature", "medical research", "clinical studies",
- "life sciences", "health information", "scientific papers"
-]
-weaknesses = [
- "non-medical topics", "very recent papers may be missing",
- "limited to published research"
-]
-requires_llm = true
-
-[pubmed.default_params]
-max_results = 20
-get_abstracts = true
-get_full_text = false
-full_text_limit = 3
-days_limit = 0
-optimize_queries = true
-
-[github]
-module_path = ".engines.search_engine_github"
-class_name = "GitHubSearchEngine"
-requires_api_key = false
-reliability = 0.99
-strengths = [
- "code repositories", "software documentation", "open source projects",
- "programming issues", "developer information", "technical documentation"
-]
-weaknesses = ["non-technical content", "content outside GitHub", "rate limits without API key"]
-supports_full_search = true
-
-[github.default_params]
-max_results = 15
-search_type = "repositories"
-include_readme = true
-include_issues = false
-
-[serpapi]
-module_path = ".engines.search_engine_serpapi"
-class_name = "SerpAPISearchEngine"
-requires_api_key = true
-api_key_env = "SERP_API_KEY"
-reliability = 0.6
-strengths = [
- "comprehensive web search", "product information", "reviews",
- "recent content", "news", "broad coverage"
-]
-weaknesses = ["requires API key with usage limits", "not specialized for academic content"]
-supports_full_search = true
-full_search_module = "local_deep_research.web_search_engines.engines.full_serp_search_results_old"
-full_search_class = "FullSerpAPISearchResults"
-
-[serpapi.default_params]
-region = "us"
-time_period = "y"
-safe_search = true
-search_language = "English"
-
-[searxng]
-module_path = ".engines.search_engine_searxng"
-class_name = "SearXNGSearchEngine"
-requires_api_key = false
-api_key_env = "SEARXNG_INSTANCE"
-reliability = 0.9
-strengths = [
- "privacy-focused", "metasearch engine", "self-hosted",
- "no tracking", "configurable", "multiple engines in one"
-]
-weaknesses = [
- "requires self-hosting", "depends on other search engines",
- "may be rate limited by underlying engines"
-]
-supports_full_search = true
-full_search_module = ".engines.full_search"
-full_search_class = "FullSearchResults"
-
-[searxng.default_params]
-max_results = 15
-categories = ["general"]
-language = "en"
-safe_search = 1
-delay_between_requests = 0.0
-include_full_content = true
-
-[google_pse]
-module_path = ".engines.search_engine_google_pse"
-class_name = "GooglePSESearchEngine"
-requires_api_key = true
-api_key_env = "GOOGLE_PSE_API_KEY"
-reliability = 0.9
-strengths = [
- "custom search scope", "high-quality results", "domain-specific search",
- "configurable search experience", "control over search index"
-]
-weaknesses = [
- "requires API key with usage limits",
- "limited to 10,000 queries/day on free tier",
- "requires search engine configuration in Google Control Panel"
-]
-supports_full_search = true
-full_search_module = ".engines.full_search"
-full_search_class = "FullSearchResults"
-
-[google_pse.default_params]
-region = "us"
-safe_search = true
-search_language = "English"
-
-[brave]
-module_path = ".engines.search_engine_brave"
-class_name = "BraveSearchEngine"
-requires_api_key = true
-api_key_env = "BRAVE_API_KEY"
-reliability = 0.7
-strengths = [
- "privacy-focused web search", "product information", "reviews",
- "recent content", "news", "broad coverage"
-]
-weaknesses = ["requires API key with usage limits", "smaller index than Google"]
-supports_full_search = true
-full_search_module = "local_deep_research.web_search_engines.engines.full_search"
-full_search_class = "FullSearchResults"
-
-[brave.default_params]
-region = "US"
-time_period = "y"
-safe_search = true
-search_language = "English"
-
-[wayback]
-module_path = ".engines.search_engine_wayback"
-class_name = "WaybackSearchEngine"
-requires_api_key = false
-reliability = 0.5
-strengths = [
- "historical web content", "archived websites", "content verification",
- "deleted or changed web pages", "website evolution tracking"
-]
-weaknesses = [
- "limited to previously archived content", "may miss recent changes",
- "archiving quality varies"
-]
-supports_full_search = true
-
-[wayback.default_params]
-max_results = 15
-max_snapshots_per_url = 3
-closest_only = false
-language = "English"
-
-[auto]
-module_path = ".engines.meta_search_engine"
-class_name = "MetaSearchEngine"
-requires_api_key = false
-reliability = 0.85
-strengths = [
- "intelligent engine selection", "adaptable to query type",
- "fallback capabilities"
-]
-weaknesses = ["slightly slower due to LLM analysis"]
-requires_llm = true
-
-[auto.default_params]
-use_api_key_services = true
-max_engines_to_try = 3
-
-[local_all]
-module_path = ".engines.search_engine_local_all"
-class_name = "LocalAllSearchEngine"
-requires_api_key = false
-reliability = 0.85
-strengths = ["searches all local collections", "personal documents", "offline access"]
-weaknesses = ["may return too many results", "requires indexing"]
-requires_llm = true
-
-#[semantic_scholar]
-#module_path = ".engines.search_engine_semantic_scholar"
-#class_name = "SemanticScholarSearchEngine"
-#requires_api_key = false
-#api_key_env = "S2_API_KEY"
-#reliability = 0.87
-#strengths = [
-# "comprehensive scientific literature",
-# "extensive citation network",
-# "AI-generated summaries (TLDRs)",
-# "academic paper metadata",
-# "cross-disciplinary coverage",
-# "200M+ papers across all fields",
-# "usable without API key"
-#]
-#weaknesses = [
-# "rate limited (1000 requests/day) without API key",
-# "limited to academic content"
-#]
-#supports_full_search = true
-#requires_llm = false
-
-#[semantic_scholar.default_params]
-#max_results = 20
-#get_abstracts = true
-#get_tldr = true
-#get_references = false
-#get_citations = false
-#get_embeddings = false
-#citation_limit = 10
-#reference_limit = 10
-#optimize_queries = true
-#max_retries = 5
-#retry_backoff_factor = 1.0
-
-# Default search engine to use if none specified
-DEFAULT_SEARCH_ENGINE = "wikipedia"
-
-
-
-
-
-# Additional search engines can be added below
-# Uncomment and modify these templates as needed
-
-# [duckduckgo]
-# module_path = ".engines.search_engine_ddg"
-# class_name = "DuckDuckGoSearchEngine"
-# requires_api_key = false
-# reliability = 0.4
-# strengths = [
-# "web search", "product information", "reviews", "recent information",
-# "news", "general queries", "broad coverage"
-# ]
-# weaknesses = ["inconsistent due to rate limits", "not specialized for academic content"]
-# supports_full_search = true
-# full_search_module = "local_deep_research.web_search_engines.engines.full_search"
-# full_search_class = "FullSearchResults"
-#
-# [duckduckgo.default_params]
-# region = "us"
-# safe_search = true
-
-# [guardian]
-# module_path = ".engines.search_engine_guardian"
-# class_name = "GuardianSearchEngine"
-# requires_api_key = true
-# api_key_env = "GUARDIAN_API_KEY"
-# reliability = 0.5
-# strengths = [
-# "news articles", "current events", "opinion pieces", "journalism",
-# "UK and global news", "political analysis"
-# ]
-# weaknesses = ["primarily focused on news", "limited historical content pre-1999"]
-#
-# [guardian.default_params]
-# order_by = "relevance"
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 3068ecea11..52ffd4bab9 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -15,7 +15,6 @@ from .advanced_search_system.strategies.parallel_search_strategy import (
from .advanced_search_system.strategies.rapid_search_strategy import RapidSearchStrategy
from .advanced_search_system.strategies.standard_strategy import StandardSearchStrategy
from .citation_handler import CitationHandler
-from .config.config_files import settings
from .config.llm_config import get_llm
from .config.search_config import get_search
from .utilities.db_utils import get_db_setting
@@ -49,11 +48,9 @@ class AdvancedSearchSystem:
self.model = llm
if llm is None:
self.model = get_llm()
- self.max_iterations = get_db_setting(
- "search.iterations", settings.search.iterations
- )
+ self.max_iterations = get_db_setting("search.iterations", 1)
self.questions_per_iteration = get_db_setting(
- "search.questions_per_iteration", settings.search.questions_per_iteration
+ "search.questions_per_iteration", 3
)
# Log the strategy name that's being used
diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.py
index 10dd37c65d..182e9c2548 100644
--- a/src/local_deep_research/utilities/db_utils.py
+++ b/src/local_deep_research/utilities/db_utils.py
@@ -46,4 +46,6 @@ def get_db_setting(key, default_value=None):
return value
except Exception as e:
logger.error(f"Error getting setting {key} from database: {e}")
+
+ logger.warning(f"Could not find setting '{key}' in the database.")
return default_value
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 8f38470208..a0e5b2d1e7 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -2,7 +2,6 @@ import logging
import os
import sys
-from ..config.config_files import settings
from ..setup_data_dir import setup_data_dir
from ..utilities.db_utils import get_db_setting
from .app_factory import create_app
@@ -92,28 +91,9 @@ def main():
print("Please run migration manually.")
# Get web server settings with defaults
- port = get_db_setting("web.port", settings.web.port)
- host = get_db_setting("web.host", settings.web.host)
- debug = get_db_setting("web.debug", settings.web.debug)
-
- # Check for OpenAI availability but don't import it unless necessary
- try:
- api_key = os.environ.get("OPENAI_API_KEY")
- if api_key:
- try:
- # Only try to import if we have an API key
- import openai
-
- openai.api_key = api_key
- logger.info("OpenAI integration is available")
- except ImportError:
- logger.info("OpenAI package not installed, integration disabled")
- else:
- logger.info(
- "OPENAI_API_KEY not found in environment variables, OpenAI integration disabled"
- )
- except Exception as e:
- logger.error(f"Error checking OpenAI availability: {e}")
+ port = get_db_setting("web.port", 5000)
+ host = get_db_setting("web.host", "0.0.0.0")
+ debug = get_db_setting("web.debug", True)
logger.info(f"Starting web server on {host}:{port} (debug: {debug})")
socketio.run(app, debug=debug, host=host, port=port, allow_unsafe_werkzeug=True)
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 40011df3f2..7a2edd2a58 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -8,9 +8,9 @@ from .models import Base, Setting, SettingType
logger = logging.getLogger(__name__)
-def migrate_settings_from_files(db_session):
+def import_default_settings_file(db_session):
"""
- Migrate settings from files to database
+ Imports all settings from the default settings file to the DB.
"""
# Check if settings table is empty
settings_count = db_session.query(Setting).count()
@@ -47,7 +47,7 @@ def run_migrations(engine, db_session=None):
# Import existing settings from files
if db_session:
- migrate_settings_from_files(db_session)
+ import_default_settings_file(db_session)
def setup_predefined_settings(db_session):
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index dbc320dd3a..d1b98ddea2 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -3,11 +3,9 @@ import logging
import os
import platform
import subprocess
-from pathlib import Path
from typing import Any, Optional, Tuple
import requests
-import toml
from flask import (
Blueprint,
current_app,
@@ -21,7 +19,6 @@ from flask import (
from flask_wtf.csrf import generate_csrf
from sqlalchemy.orm import Session
-from ...config.config_files import get_config_dir
from ..database.models import Setting, SettingType
from ..services.settings_service import (
create_or_update_setting,
@@ -256,10 +253,6 @@ def save_all_settings():
is_valid, error_message = validate_setting(current_setting, value)
if is_valid:
- # Update category if different from our determination
- if category and current_setting.category != category:
- current_setting.category = category
-
# Save the setting
success = set_setting(key, value, db_session=db_session)
if success:
@@ -968,48 +961,6 @@ def api_get_available_search_engines():
return jsonify({"error": str(e)}), 500
-def get_engines_from_file():
- """Get available search engines directly from the toml file"""
- try:
- # Try to load from the actual config directory
- config_dir = get_config_dir()
- search_engines_file = config_dir / "config" / "search_engines.toml"
-
- # If file doesn't exist in user config, try the defaults
- if not search_engines_file.exists():
- # Look in the defaults folder instead
- import inspect
-
- from ...defaults import search_engines
-
- # Get the path to the search_engines.toml file
- module_path = inspect.getfile(search_engines)
- default_file = Path(module_path)
-
- if default_file.exists() and default_file.suffix == ".toml":
- search_engines_file = default_file
-
- # If we found a file, load it
- if search_engines_file.exists():
- data = toml.load(search_engines_file)
-
- # Filter out the metadata entries (like DEFAULT_SEARCH_ENGINE)
- engines = {k: v for k, v in data.items() if isinstance(v, dict)}
-
- # Add display names for each engine
- for key, engine in engines.items():
- if "display_name" not in engine:
- # Create a display name from the key
- engine["display_name"] = key.replace("_", " ").title()
-
- return engines
-
- return None
- except Exception as e:
- logger.error(f"Error loading search engines from file: {e}")
- return None
-
-
# Legacy routes for backward compatibility - these will redirect to the new routes
@settings_bp.route("/main", methods=["GET"])
def main_config_page():
diff --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.py
index 9777487f89..bbbb3d1ab9 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
@@ -642,6 +642,8 @@ class LocalSearchEngine(BaseSearchEngine):
chunk_overlap: int = 200,
cache_dir: str = ".cache/local_search",
collections: Optional[Dict[str, Dict[str, Any]]] = None,
+ name: str = "",
+ description: str = "",
):
"""
Initialize the local search engine.
@@ -660,10 +662,16 @@ class LocalSearchEngine(BaseSearchEngine):
chunk_overlap: Overlap between chunks
cache_dir: Directory to store embedding cache and index
collections: Dictionary of named collections with paths and descriptions
+ name: Human-readable name of the collection we are searching.
+ description: Human-readable description of the collection we are
+ searching.
"""
# Initialize the base search engine
super().__init__(llm=llm, max_filtered_results=max_filtered_results)
+ self.name = name
+ self.description = description
+
# Validate folder paths
self.folder_paths = paths
self.valid_folder_paths = []
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.py
index 44e99c4c19..96a1743cd2 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
@@ -3,14 +3,14 @@ Search engine that searches across all local collections
"""
import logging
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, cast
-import toml
from langchain_core.language_models import BaseLLM
-from ...config.config_files import LOCAL_COLLECTIONS_FILE
from ..search_engine_base import BaseSearchEngine
from ..search_engine_factory import create_search_engine
+from ..search_engines_config import local_search_engines
+from .search_engine_local import LocalSearchEngine
# Setup logging
logger = logging.getLogger(__name__)
@@ -46,12 +46,7 @@ class LocalAllSearchEngine(BaseSearchEngine):
# Find all local collection search engines
self.local_engines = {}
try:
- local_collections = toml.load(LOCAL_COLLECTIONS_FILE)
-
- for collection_id, collection in local_collections.items():
- if not collection.get("enabled", True):
- continue
-
+ for collection_id in local_search_engines():
# Create a search engine for this collection
try:
engine = create_search_engine(
@@ -59,12 +54,13 @@ class LocalAllSearchEngine(BaseSearchEngine):
llm=llm,
max_filtered_results=max_filtered_results,
)
+ engine = cast(LocalSearchEngine, engine)
if engine:
self.local_engines[collection_id] = {
"engine": engine,
- "name": collection.get("name", collection_id),
- "description": collection.get("description", ""),
+ "name": engine.name,
+ "description": engine.description,
}
except Exception as e:
logger.error(
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.py
index 12663695ed..09f899a15e 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
@@ -37,34 +37,22 @@ def create_search_engine(
# Get engine configuration
engine_config = search_config()[engine_name]
- from ..config.config_files import settings
# Set default max_results from config if not provided in kwargs
if "max_results" not in kwargs:
- max_results = get_db_setting("search.max_results", settings.search.max_results)
+ max_results = get_db_setting("search.max_results", 10)
if max_results is None:
max_results = 20
kwargs["max_results"] = max_results
# Check for API key requirements
if engine_config.get("requires_api_key", False):
- api_key_env = engine_config.get("api_key_env")
-
- # First check environment variable
- api_key = os.getenv(api_key_env)
+ api_key = os.getenv(f"LDR_{engine_name.upper()}_API_KEY")
if not api_key:
- api_key = os.getenv("LDR_" + api_key_env)
-
- # If not found in environment, check Dynaconf settings
- if not api_key and api_key_env:
- # Convert env var name to settings path (e.g., BRAVE_API_KEY -> brave_api_key)
- settings_key = api_key_env.lower()
- api_key = settings.get(settings_key)
+ api_key = engine_config.get("api_key")
if not api_key:
- logger.info(
- f"Required API key for {engine_name} not found in environment variable: {api_key_env} or settings"
- )
+ logger.info(f"Required API key for {engine_name} not found in settings.")
return None
# Check for LLM requirements
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.py
index 2b0e6e02ac..17a355ca48 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
@@ -3,9 +3,10 @@ Configuration file for search engines.
Loads search engine definitions from the user's configuration.
"""
+import json
import logging
from functools import cache
-from typing import Any, Dict
+from typing import Any, Dict, List
from ..utilities.db_utils import get_db_setting
@@ -56,13 +57,36 @@ def search_config() -> Dict[str, Any]:
local_collections_data = _extract_per_engine_config(local_collections_data)
for collection, config in local_collections_data.items():
+ if not config.get("enabled", True):
+ # Search engine is not enabled. Ignore.
+ logger.info(f"Ignoring disabled local collection '{collection}'.")
+ continue
+
+ if "paths" in config:
+ # This will be saved as a json array.
+ try:
+ config["paths"] = json.loads(config["paths"])
+ except json.decoder.JSONDecodeError:
+ logger.error(
+ f"Invalid paths specified for local collection: "
+ f"{config['paths']}"
+ )
+ config["paths"] = []
+
# Create a new dictionary with required search engine fields
engine_config = {
- "module_path": "local_deep_research.web_search_engines.engines.search_engine_local",
- "class_name": "LocalSearchEngine",
"default_params": config,
"requires_llm": True,
}
+ engine_config_prefix = f"search.engine.local.{collection}"
+ engine_config["module_path"] = get_db_setting(
+ f"{engine_config_prefix}.module_path",
+ "local_deep_research.web_search_engines.engines.search_engine_local",
+ )
+ engine_config["class_name"] = get_db_setting(
+ f"{engine_config_prefix}.class_name",
+ "LocalSearchEngine",
+ )
# Copy these specific fields to the top level if they exist
for field in ["strengths", "weaknesses", "reliability", "description"]:
@@ -88,3 +112,25 @@ def default_search_engine() -> str:
"""
return get_db_setting("search.engine.DEFAULT_SEARCH_ENGINE", "wikipedia")
+
+
+@cache
+def local_search_engines() -> List[str]:
+ """
+ Returns:
+ A list of the enabled local search engines.
+
+ """
+ local_collections_data = get_db_setting("search.engine.local", {})
+ local_collections_data = _extract_per_engine_config(local_collections_data)
+
+ # Don't include the `local_all` collection.
+ local_collections_data.pop("local_all", None)
+ # Remove disabled collections.
+ local_collections_data = {
+ k: v for k, v in local_collections_data.items() if v.get("enabled", True)
+ }
+
+ enabled_collections = list(local_collections_data.keys())
+ logger.debug(f"Using local collections: {enabled_collections}")
+ return enabled_collections