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.

Transition as much config as possible to reading from the DB.

Daniel Petti6cb2137bacef
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 3110074ede..76f165f125 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
@@ -396,7 +396,13 @@ Please try again with a different query or contact support.
"""
# Compress knowledge if needed
- if settings.general.knowledge_accumulation == "ITERATION":
+ if (
+ get_db_setting(
+ "general.knowledge_accumulation",
+ settings.general.knowledge_accumulation,
+ )
+ == "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 0a93d9f8b9..50e2ab8c65 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
@@ -115,6 +115,10 @@ Iteration: {iteration + 1} of {total_iterations}"""
logger.info(f"Generated questions: {questions}")
question_count = len(questions)
+ knowledge_accumulation = get_db_setting(
+ "general.knowledge_accumulation",
+ settings.general.knowledge_accumulation,
+ )
for q_idx, question in enumerate(questions):
question_progress_base = iteration_progress_base + (
((q_idx + 1) / question_count) * (100 / total_iterations) * 0.5
@@ -198,7 +202,7 @@ Iteration: {iteration + 1} of {total_iterations}"""
}
)
- if settings.general.knowledge_accumulation != str(
+ if knowledge_accumulation != str(
KnowledgeAccumulationApproach.NO_KNOWLEDGE.value
):
current_knowledge = (
@@ -207,7 +211,7 @@ Iteration: {iteration + 1} of {total_iterations}"""
+ results_with_links
)
- if settings.general.knowledge_accumulation == str(
+ if knowledge_accumulation == str(
KnowledgeAccumulationApproach.QUESTION.value
):
logger.info("Compressing knowledge")
@@ -240,10 +244,7 @@ Iteration: {iteration + 1} of {total_iterations}"""
{"phase": "knowledge_compression"},
)
- if (
- settings.general.knowledge_accumulation
- == KnowledgeAccumulationApproach.ITERATION.value
- ):
+ if knowledge_accumulation == KnowledgeAccumulationApproach.ITERATION.value:
try:
logger.info("ITERATION - Compressing Knowledge")
current_knowledge = self.knowledge_generator.compress_knowledge(
diff --git a/src/local_deep_research/citation_handler.py b/src/local_deep_research/citation_handler.py
index 21f930ae8d..3327fa1ff5 100644
--- a/src/local_deep_research/citation_handler.py
+++ b/src/local_deep_research/citation_handler.py
@@ -5,6 +5,7 @@ from typing import Any, Dict, List, Union
from langchain_core.documents import Document
from .config.config_files import settings
+from .utilties.db_utils import get_db_setting
class CitationHandler:
@@ -93,7 +94,9 @@ Provide a detailed analysis with citations. Do not create the bibliography, it w
{formatted_sources}
Return any inconsistencies or conflicts found."""
- if settings.GENERAL.ENABLE_FACT_CHECKING:
+ if get_db_setting(
+ "general.enable_fact_checking", settings.general.enable_fact_checking
+ ):
fact_check_response = self.llm.invoke(fact_check_prompt).content
else:
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index d640a89034..c03cb69fd3 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -29,7 +29,7 @@ VALID_PROVIDERS = [
SECRETS_FILE = CONFIG_DIR / ".secrets.toml"
-def get_llm(model_name=None, temperature=None, provider=None):
+def get_llm(model_name=None, temperature=None, provider=None, openai_endpoint_url=None):
"""
Get LLM instance based on model name and provider.
@@ -37,6 +37,8 @@ def get_llm(model_name=None, temperature=None, provider=None):
model_name: Name of the model to use (if None, uses database setting)
temperature: Model temperature (if None, uses database setting)
provider: Provider to use (if None, uses database setting)
+ openai_endpoint_url: Custom endpoint URL to use (if None, uses database
+ setting)
Returns:
A LangChain LLM instance with automatic think-tag removal
@@ -129,7 +131,10 @@ def get_llm(model_name=None, temperature=None, provider=None):
return get_fallback_model(temperature)
# Get endpoint URL from settings
- openai_endpoint_url = settings.llm.openai_endpoint_url
+ if openai_endpoint_url is not None:
+ openai_endpoint_url = get_db_setting(
+ "llm.openai_endpoint_url", settings.llm.openai_endpoint_url
+ )
llm = ChatOpenAI(
model=model_name,
@@ -226,13 +231,14 @@ def get_llm(model_name=None, temperature=None, provider=None):
elif provider == "lmstudio":
# LM Studio supports OpenAI API format, so we can use ChatOpenAI directly
lmstudio_url = settings.llm.get("lmstudio_url", "http://localhost:1234")
+ lmstudio_url = get_db_setting("llm.llmstudio_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=settings.llm.max_tokens,
+ max_tokens=get_db_setting("llm.max_tokens", settings.llm.max_tokens),
)
return wrap_llm_without_think_tags(llm)
@@ -242,20 +248,24 @@ def get_llm(model_name=None, temperature=None, provider=None):
# 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)
if not model_path:
logger.error("llamacpp_model_path not set in settings")
- raise ValueError("llamacpp_model_path not set in settings.toml")
+ 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)
# Create LlamaCpp instance
llm = LlamaCpp(
model_path=model_path,
temperature=temperature,
- max_tokens=settings.llm.max_tokens,
+ max_tokens=get_db_setting("llm.max_tokens", settings.llm.max_tokens),
n_gpu_layers=n_gpu_layers,
n_batch=n_batch,
f16_kv=f16_kv,
@@ -425,6 +435,7 @@ def is_lmstudio_available():
import requests
lmstudio_url = settings.llm.get("lmstudio_url", "http://localhost:1234")
+ lmstudio_url = get_db_setting("llm.lmstudio_url", lmstudio_url)
# LM Studio typically uses OpenAI-compatible endpoints
response = requests.get(f"{lmstudio_url}/v1/models", timeout=1.0)
return response.status_code == 200
@@ -438,6 +449,7 @@ def is_llamacpp_available():
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)
return bool(model_path) and os.path.exists(model_path)
except Exception:
return False
@@ -450,7 +462,7 @@ def get_available_providers():
secrets_file = Path(SECRETS_FILE)
AVAILABLE_PROVIDERS = get_available_providers()
-selected_provider = settings.llm.provider.lower()
+selected_provider = get_db_setting("llm.provider", settings.llm.provider).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 19677a2762..c5348bfda9 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -13,7 +13,9 @@ logger = logging.getLogger(__name__)
# Whether to check the quality search results using the LLM.
QUALITY_CHECK_DDG_URLS = True
# Whether to only retrieve snippets instead of full search results.
-SEARCH_SNIPPETS_ONLY = settings.search.snippets_only
+SEARCH_SNIPPETS_ONLY = get_db_setting(
+ "search.snippets_only", settings.search.snippets_only
+)
# Expose get_search function
@@ -37,16 +39,26 @@ def get_search(search_tool=None, llm_instance=None):
params = {
"search_tool": tool,
"llm_instance": llm,
- "max_results": settings.search.max_results,
- "region": settings.search.region,
- "time_period": settings.search.time_period,
- "safe_search": settings.search.safe_search,
+ "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
+ ),
"search_snippets_only": SEARCH_SNIPPETS_ONLY,
- "search_language": settings.search.search_language,
- "max_filtered_results": settings.search.max_filtered_results,
+ "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
+ ),
}
- # Log parameters for debugging
+ # Log NULL parameters for debugging
logger.info(
f"Search config: tool={tool}, max_results={params['max_results']}, time_period={params['time_period']}"
)
diff --git a/src/local_deep_research/main.py b/src/local_deep_research/main.py
index 607da82667..cfb89ec249 100644
--- a/src/local_deep_research/main.py
+++ b/src/local_deep_research/main.py
@@ -2,9 +2,9 @@ import logging
import sys
from typing import Dict
-# from .report_generator import IntegratedReportGenerator
from . import get_advanced_search_system, get_report_generator
from .config.config_files import settings
+from .utilties.db_utils import get_db_setting
def print_report(report: Dict):
@@ -47,9 +47,13 @@ def main():
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
+ search_iterations = get_db_setting("search.iterations", settings.search.iterations)
+ questions_per_iteration = get_db_setting(
+ "search.questions_per_iteration", settings.search.questions_per_iteration
+ )
logger.info(
- f"Starting with settings: iterations={settings.search.iterations}, "
- f"questions_per_iteration={settings.search.questions_per_iteration}"
+ f"Starting with settings: iterations={search_iterations}, "
+ f"questions_per_iteration={questions_per_iteration}"
)
# Explicitly run setup
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 2a10a73f72..f96027586d 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -49,8 +49,12 @@ class AdvancedSearchSystem:
self.model = llm
if llm is None:
self.model = get_llm()
- self.max_iterations = settings.search.iterations
- self.questions_per_iteration = settings.search.questions_per_iteration
+ self.max_iterations = get_db_setting(
+ "search.iterations", settings.search.iterations
+ )
+ self.questions_per_iteration = get_db_setting(
+ "search.questions_per_iteration", settings.search.questions_per_iteration
+ )
# Log the strategy name that's being used
logger.info(
diff --git a/src/local_deep_research/utilties/db_utils.py b/src/local_deep_research/utilties/db_utils.py
index 61fb8e87da..10dd37c65d 100644
--- a/src/local_deep_research/utilties/db_utils.py
+++ b/src/local_deep_research/utilties/db_utils.py
@@ -5,6 +5,8 @@ from functools import cache
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
+from ..web.services.settings_manager import SettingsManager
+
logger = logging.getLogger(__name__)
@@ -16,22 +18,29 @@ DB_PATH = os.path.join(DATA_DIR, "ldr.db")
@cache
def get_db_session() -> Session:
"""
- Gets a DB session.
+ Returns:
+ The singleton DB session.
"""
engine = create_engine(f"sqlite:///{DB_PATH}")
session_class = sessionmaker(bind=engine)
return session_class()
+@cache
+def get_settings_manager() -> SettingsManager:
+ """
+ Returns:
+ The singleton settings manager.
+
+ """
+ return SettingsManager(db_session=get_db_session())
+
+
def get_db_setting(key, default_value=None):
"""Get a setting from the database with fallback to default value"""
try:
- # Lazy import to avoid circular dependency
- from ..web.services.settings_manager import SettingsManager
-
# Get settings manager which handles database access
- settings_manager = SettingsManager(db_session=get_db_session())
- value = settings_manager.get_setting(key)
+ value = get_settings_manager().get_setting(key)
if value is not None:
return value
diff --git a/src/local_deep_research/web/__init__.py b/src/local_deep_research/web/__init__.py
index 691fe6aba6..bd4ed6738b 100644
--- a/src/local_deep_research/web/__init__.py
+++ b/src/local_deep_research/web/__init__.py
@@ -1,3 +1 @@
"""Web interface for Local Deep Research"""
-
-from . import app
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 2e243cf0fb..6e2ac30ba3 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -4,6 +4,7 @@ import sys
from ..config.config_files import settings
from ..setup_data_dir import setup_data_dir
+from ..utilties.db_utils import get_db_setting
from .app_factory import create_app
from .models.database import (
DB_PATH,
@@ -91,9 +92,9 @@ def main():
print("Please run migration manually.")
# Get web server settings with defaults
- port = settings.web.port
- host = settings.web.host
- debug = settings.web.debug
+ 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:
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 923b8243e7..904b368a2d 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -5,7 +5,6 @@ import threading
import traceback
from datetime import datetime
-from ...config.config_files import settings
from ...config.llm_config import get_llm
from ...config.search_config import get_search
from ...report_generator import IntegratedReportGenerator
@@ -263,36 +262,13 @@ def run_research_process(
# Override LLM if model or model_provider specified
if model or model_provider:
try:
- # Temporarily override settings
- original_model = settings.llm.model
- original_provider = settings.llm.provider
-
- # Set model if provided
- if model:
- settings.llm.model = model
-
- # Set provider if provided
- if model_provider:
- settings.llm.provider = model_provider
-
- # Set custom endpoint if provided for OpenAI endpoint provider
- original_endpoint = None
- if custom_endpoint and model_provider == "OPENAI_ENDPOINT":
- if hasattr(settings.llm, "openai_endpoint_url"):
- original_endpoint = getattr(
- settings.llm, "openai_endpoint_url", None
- )
- settings.llm.openai_endpoint_url = custom_endpoint
-
# Get LLM with the overridden settings
# Explicitly create the model with parameters to avoid fallback issues
- use_llm = get_llm(model_name=model, provider=model_provider)
-
- # Restore original settings
- settings.llm.model = original_model
- settings.llm.provider = original_provider
- if original_endpoint is not None:
- settings.llm.openai_endpoint_url = original_endpoint
+ use_llm = get_llm(
+ model_name=model,
+ provider=model_provider,
+ openai_endpoint_url=custom_endpoint,
+ )
logger.info(
"Successfully set LLM to: provider=%s, model=%s",
@@ -315,37 +291,9 @@ def run_research_process(
# Override search engine if specified
if search_engine:
try:
- # Temporarily override the search setting
- original_search = settings.search.tool
- settings.search.tool = search_engine
-
- # Initialize all variables with default values
- original_max_results = None
- original_time_period = None
- original_iterations = None
- original_questions = None
-
- # Set other search parameters if provided
- if max_results and hasattr(settings.search, "max_results"):
- original_max_results = settings.search.max_results
- settings.search.max_results = int(max_results)
-
- if time_period and hasattr(settings.search, "time_period"):
- original_time_period = settings.search.time_period
- settings.search.time_period = time_period
-
- if iterations and hasattr(settings.search, "iterations"):
- original_iterations = settings.search.iterations
- settings.search.iterations = int(iterations)
+ if iterations:
system.max_iterations = int(iterations)
-
- if questions_per_iteration and hasattr(
- settings.search, "questions_per_iteration"
- ):
- original_questions = settings.search.questions_per_iteration
- settings.search.questions_per_iteration = int(
- questions_per_iteration
- )
+ if questions_per_iteration:
system.questions_per_iteration = int(questions_per_iteration)
# Create a new search object with these settings
@@ -353,21 +301,6 @@ def run_research_process(
search_tool=search_engine, llm_instance=system.model
)
- # Restore original settings
- settings.search.tool = original_search
-
- if original_max_results is not None:
- settings.search.max_results = original_max_results
-
- if original_time_period is not None:
- settings.search.time_period = original_time_period
-
- if original_iterations is not None:
- settings.search.iterations = original_iterations
-
- if original_questions is not None:
- settings.search.questions_per_iteration = original_questions
-
logger.info("Successfully set search engine to: %s", search_engine)
except Exception as e:
logger.error(
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index 9a1238dab4..0c09158f0f 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -462,50 +462,6 @@ class SettingsManager:
self.db_session.rollback()
return False
- def _load_settings_from_db(self):
- """Load all settings from database into memory cache"""
- if not self.db_session:
- return
-
- try:
- for setting in self.db_session.query(Setting).all():
- self._settings_cache[setting.key] = setting.value
- logger.info(f"Loaded {len(self._settings_cache)} settings from database")
- except SQLAlchemyError as e:
- logger.error(f"Error loading settings from database: {e}")
-
- def _load_settings_from_files_as_fallback(self):
- """Load settings from files into memory cache, but only for keys not already in the database"""
- # Load from main settings file
- if os.path.exists(self.settings_file):
- try:
- with open(self.settings_file, "r") as f:
- data = toml.load(f)
- for section, values in data.items():
- for key, value in values.items():
- full_key = f"{section}.{key}"
- # Only add if not already in cache (from DB)
- if full_key not in self._settings_cache:
- self._settings_cache[full_key] = value
- except Exception as e:
- logger.error(f"Error loading settings from {self.settings_file}: {e}")
-
- # Load from search engines file
- if os.path.exists(self.search_engines_file):
- try:
- with open(self.search_engines_file, "r") as f:
- data = toml.load(f)
- if "search" in data:
- for key, value in data["search"].items():
- full_key = f"search.{key}"
- # Only add if not already in cache (from DB)
- if full_key not in self._settings_cache:
- self._settings_cache[full_key] = value
- except Exception as e:
- logger.error(
- f"Error loading settings from {self.search_engines_file}: {e}"
- )
-
def _write_section_to_file(
self, file_path: Path, section: str, data: Dict[str, Any]
) -> bool:
@@ -559,7 +515,6 @@ class SettingsManager:
elif db_session and not cls._instance.db_session:
# Update existing instance with a session
cls._instance.db_session = db_session
- cls._instance._load_settings_from_db()
return cls._instance
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 02cd398725..c1c96a0e6d 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
@@ -4,6 +4,7 @@ import logging
import os
from typing import Any, Dict, List, Optional, Union
+from ..utilties.db_utils import get_db_setting
from .search_engine_base import BaseSearchEngine
from .search_engines_config import DEFAULT_SEARCH_ENGINE, SEARCH_ENGINES
@@ -39,7 +40,7 @@ def create_search_engine(
# Set default max_results from config if not provided in kwargs
if "max_results" not in kwargs:
- max_results = settings.search.max_results
+ max_results = get_db_setting("search.max_results", settings.search.max_results)
if max_results is None:
max_results = 20
kwargs["max_results"] = max_results