~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
feat: Add programmatic API settings management without database dependency
LearningCircuitfc48711a3b21
diff --git a/.github/workflows/llm-tests.yml b/.github/workflows/llm-tests.ymlindex b81562d428..7690553369 100644--- a/.github/workflows/llm-tests.yml+++ b/.github/workflows/llm-tests.yml@@ -126,4 +126,4 @@ jobs:-e LDR_USE_FALLBACK_LLM=true \-w /app \ldr-test \- sh -c "timeout 60s python examples/llm_integration/custom_research_example.py || true"\ No newline at end of file+ sh -c "timeout 60s python examples/llm_integration/custom_research_example.py || true"diff --git a/pdm.lock b/pdm.lockindex 2bc314d33a..18e2a75969 100644--- a/pdm.lock+++ b/pdm.lock@@ -5,7 +5,7 @@groups = ["default", "dev"]strategy = ["inherit_metadata"]lock_version = "4.5.0"-content_hash = "sha256:8c75e91ac506b726f5d971710ad7d11a8b2c2120cbfc925e87ae077a1942d506"+content_hash = "sha256:cc820cec60581db04d7fff3734332b6e79421127936ffd4cec04caca24ea5f00"[[metadata.targets]]requires_python = ">=3.10"diff --git a/pyproject.toml b/pyproject.tomlindex 899b0cfde1..4e50ead61b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -92,6 +92,7 @@ include-package-data = true+[tool.pdm]distribution = trueversion = { source = "file", path = "src/local_deep_research/__version__.py" }@@ -107,11 +108,11 @@ dev = ["cookiecutter>=2.6.0","pandas>=2.2.3","optuna>=4.3.0",- "pytest-mock>=3.14.0",- "pytest>=8.3.5",- "pytest-cov>=6.1.1",+ "pytest-mock>=3.14.1",+ "pytest>=8.4.1",+ "pytest-cov>=6.2.1","pytest-timeout>=2.3.1",- "pytest-asyncio>=0.23.0",+ "pytest-asyncio>=1.0.0","ruff>=0.11.12","freezegun>=1.5.2",]diff --git a/src/local_deep_research/api/__init__.py b/src/local_deep_research/api/__init__.pyindex 0993196a60..f5fde09d37 100644--- a/src/local_deep_research/api/__init__.py+++ b/src/local_deep_research/api/__init__.py@@ -9,10 +9,18 @@ from .research_functions import (generate_report,quick_summary,)+from .settings_utils import (+ create_settings_snapshot,+ get_default_settings_snapshot,+ extract_setting_value,+)__all__ = ["analyze_documents","detailed_research","generate_report","quick_summary",+ "create_settings_snapshot",+ "get_default_settings_snapshot",+ "extract_setting_value",]diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 27ffb74f87..225e5ad1c4 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -14,6 +14,7 @@ from ..report_generator import IntegratedReportGeneratorfrom ..search_system import AdvancedSearchSystemfrom ..utilities.db_utils import no_db_settingsfrom ..utilities.search_utilities import remove_think_tags+from .settings_utils import create_settings_snapshotdef _init_search_system(@@ -134,6 +135,12 @@ def quick_summary(retrievers: Optional[Dict[str, Any]] = None,llms: Optional[Dict[str, Any]] = None,username: Optional[str] = None,+ provider: Optional[str] = None,+ api_key: Optional[str] = None,+ temperature: Optional[float] = None,+ max_search_results: Optional[int] = None,+ settings: Optional[Dict[str, Any]] = None,+ settings_override: Optional[Dict[str, Any]] = None,**kwargs: Any,) -> Dict[str, Any]:"""@@ -144,7 +151,13 @@ def quick_summary(research_id: Optional research ID (int or UUID string) for tracking metricsretrievers: Optional dictionary of {name: retriever} pairs to use as search enginesllms: Optional dictionary of {name: llm} pairs to use as language models- **kwargs: Configuration for the search system. Will be forwarded to+ provider: LLM provider to use (e.g., 'openai', 'anthropic'). For programmatic API only.+ api_key: API key for the provider. For programmatic API only.+ temperature: LLM temperature (0.0-1.0). For programmatic API only.+ max_search_results: Maximum number of search results to return. For programmatic API only.+ settings: Base settings dict to use instead of defaults. For programmatic API only.+ settings_override: Dictionary of settings to override (e.g., {"llm.max_tokens": 4000}). For programmatic API only.+ **kwargs: Additional configuration for the search system. Will be forwarded to`_init_search_system()`.Returns:@@ -153,9 +166,48 @@ def quick_summary(- 'findings': List of detailed findings from each search- 'iterations': Number of iterations performed- 'questions': Questions generated during research++ Examples:+ # Simple usage with defaults+ result = quick_summary("What is quantum computing?")++ # With custom provider+ result = quick_summary(+ "What is quantum computing?",+ provider="anthropic",+ api_key="sk-ant-..."+ )++ # With advanced settings+ result = quick_summary(+ "What is quantum computing?",+ temperature=0.2,+ settings_override={"search.engines.arxiv.enabled": True}+ )"""logger.info("Generating quick summary for query: %s", query)+ # Only create settings snapshot if not already provided (programmatic API)+ if "settings_snapshot" not in kwargs:+ # Build kwargs for create_settings_snapshot from explicit parameters+ snapshot_kwargs = {}+ if provider is not None:+ snapshot_kwargs["provider"] = provider+ if api_key is not None:+ snapshot_kwargs["api_key"] = api_key+ if temperature is not None:+ snapshot_kwargs["temperature"] = temperature+ if max_search_results is not None:+ snapshot_kwargs["max_search_results"] = max_search_results++ # Create settings snapshot for programmatic use+ kwargs["settings_snapshot"] = create_settings_snapshot(+ base_settings=settings,+ overrides=settings_override,+ **snapshot_kwargs,+ )+ logger.debug("Created settings snapshot for programmatic API")+# Generate a research_id if none providedif research_id is None:import uuiddiff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.pynew file mode 100644index 0000000000..a124933286--- /dev/null+++ b/src/local_deep_research/api/settings_utils.py@@ -0,0 +1,233 @@+"""+Utilities for managing settings in the programmatic API.++This module provides functions to create settings snapshots for the API+without requiring database access, reusing the same mechanisms as the+web interface.+"""++import os+import copy+from typing import Any, Dict, Optional, Union+from loguru import logger++from ..settings import CachedSettingsManager+from ..settings.base import ISettingsManager+++class InMemorySettingsManager(ISettingsManager):+ """+ In-memory settings manager that doesn't require database access.++ This is used for the programmatic API to provide settings without+ needing a database connection.+ """++ def __init__(self):+ """Initialize with default settings from JSON file."""+ # Create a base manager to get default settings+ self._base_manager = CachedSettingsManager(db_session=None)+ self._settings = {}+ self._load_defaults()++ def _load_defaults(self):+ """Load default settings from the JSON file."""+ # Get default settings from the base manager+ defaults = self._base_manager.default_settings++ # Convert to the format expected by get_all_settings+ for key, setting_data in defaults.items():+ self._settings[key] = setting_data.copy()++ # Check environment variable override+ env_key = f"LDR_{key.upper().replace('.', '_')}"+ env_value = os.environ.get(env_key)+ if env_value is not None:+ # Convert based on type+ if setting_data.get("ui_element") == "checkbox":+ self._settings[key]["value"] = env_value.lower() in (+ "true",+ "1",+ "yes",+ "on",+ )+ elif setting_data.get("ui_element") in ("number", "range"):+ try:+ self._settings[key]["value"] = float(env_value)+ except ValueError:+ logger.warning(+ f"Invalid numeric value for {env_key}: {env_value}"+ )+ else:+ self._settings[key]["value"] = env_value++ def get_setting(+ self, key: str, default: Any = None, check_env: bool = True+ ) -> Any:+ """Get a setting value."""+ if key in self._settings:+ return self._settings[key].get("value", default)+ return default++ def set_setting(self, key: str, value: Any, commit: bool = True) -> bool:+ """Set a setting value (in memory only)."""+ if key in self._settings:+ self._settings[key]["value"] = value+ return True+ return False++ def get_all_settings(self) -> Dict[str, Any]:+ """Get all settings with metadata."""+ return self._settings.copy()++ def load_from_defaults_file(+ self, commit: bool = True, **kwargs: Any+ ) -> None:+ """Reload defaults (already done in __init__)."""+ self._load_defaults()++ def create_or_update_setting(+ self, setting: Union[Dict[str, Any], Any], commit: bool = True+ ) -> Optional[Any]:+ """Create or update a setting (in memory only)."""+ if isinstance(setting, dict) and "key" in setting:+ key = setting["key"]+ self._settings[key] = setting+ return setting+ return None++ def delete_setting(self, key: str, commit: bool = True) -> bool:+ """Delete a setting (in memory only)."""+ if key in self._settings:+ del self._settings[key]+ return True+ return False++ def import_settings(+ self,+ settings_data: Dict[str, Any],+ commit: bool = True,+ overwrite: bool = True,+ delete_extra: bool = False,+ ) -> None:+ """Import settings from a dictionary."""+ if delete_extra:+ self._settings.clear()++ for key, value in settings_data.items():+ if overwrite or key not in self._settings:+ self._settings[key] = value+++def get_default_settings_snapshot() -> Dict[str, Any]:+ """+ Get a complete settings snapshot with default values.++ This uses the same mechanism as the web interface but without+ requiring database access. Environment variables are checked+ for overrides.++ Returns:+ Dict mapping setting keys to their values and metadata+ """+ manager = InMemorySettingsManager()+ return manager.get_all_settings()+++def create_settings_snapshot(+ base_settings: Optional[Dict[str, Any]] = None,+ overrides: Optional[Dict[str, Any]] = None,+ **kwargs,+) -> Dict[str, Any]:+ """+ Create a settings snapshot for the programmatic API.++ Args:+ base_settings: Base settings dict (defaults to get_default_settings_snapshot())+ overrides: Dict of setting overrides (e.g., {"llm.provider": "openai"})+ **kwargs: Common setting shortcuts:+ - provider: Maps to "llm.provider"+ - api_key: Maps to "llm.{provider}.api_key"+ - temperature: Maps to "llm.temperature"+ - max_search_results: Maps to "search.max_results"+ - search_engines: Maps to enabled search engines++ Returns:+ Complete settings snapshot for use with the API+ """+ # Start with base settings or defaults+ if base_settings is None:+ settings = get_default_settings_snapshot()+ else:+ settings = copy.deepcopy(base_settings)++ # Apply overrides if provided+ if overrides:+ for key, value in overrides.items():+ if key in settings:+ if isinstance(settings[key], dict) and "value" in settings[key]:+ settings[key]["value"] = value+ else:+ settings[key] = value+ else:+ # Create a simple setting entry for unknown keys+ settings[key] = {"value": value}++ # Handle common kwargs shortcuts+ if "provider" in kwargs:+ provider = kwargs["provider"]+ if "llm.provider" in settings:+ settings["llm.provider"]["value"] = provider+ else:+ settings["llm.provider"] = {"value": provider}++ # Handle api_key if provided+ if "api_key" in kwargs:+ api_key = kwargs["api_key"]+ api_key_setting = f"llm.{provider}.api_key"+ if api_key_setting in settings:+ settings[api_key_setting]["value"] = api_key+ else:+ settings[api_key_setting] = {"value": api_key}++ if "temperature" in kwargs:+ if "llm.temperature" in settings:+ settings["llm.temperature"]["value"] = kwargs["temperature"]+ else:+ settings["llm.temperature"] = {"value": kwargs["temperature"]}++ if "max_search_results" in kwargs:+ if "search.max_results" in settings:+ settings["search.max_results"]["value"] = kwargs[+ "max_search_results"+ ]+ else:+ settings["search.max_results"] = {+ "value": kwargs["max_search_results"]+ }++ # Add any other common shortcuts here...++ return settings+++def extract_setting_value(+ settings_snapshot: Dict[str, Any], key: str, default: Any = None+) -> Any:+ """+ Extract a setting value from a settings snapshot.++ Args:+ settings_snapshot: Settings snapshot dict+ key: Setting key (e.g., "llm.provider")+ default: Default value if not found++ Returns:+ The setting value+ """+ if key in settings_snapshot:+ setting = settings_snapshot[key]+ if isinstance(setting, dict) and "value" in setting:+ return setting["value"]+ return setting+ return defaultdiff --git a/tests/test_api_settings.py b/tests/test_api_settings.pynew file mode 100644index 0000000000..25334b217e--- /dev/null+++ b/tests/test_api_settings.py@@ -0,0 +1,224 @@+"""Tests for the programmatic API settings functionality."""++from unittest.mock import patch, MagicMock++from src.local_deep_research.api.settings_utils import (+ InMemorySettingsManager,+ get_default_settings_snapshot,+ create_settings_snapshot,+ extract_setting_value,+)+++class TestInMemorySettingsManager:+ """Test the InMemorySettingsManager class."""++ def test_initialization(self):+ """Test that the manager initializes with default settings."""+ manager = InMemorySettingsManager()+ settings = manager.get_all_settings()++ # Should have loaded default settings+ assert len(settings) > 0+ assert "llm.provider" in settings+ assert "llm.temperature" in settings++ def test_get_setting(self):+ """Test getting individual settings."""+ manager = InMemorySettingsManager()++ # Get existing setting+ provider = manager.get_setting("llm.provider")+ assert provider is not None++ # Get non-existent setting with default+ missing = manager.get_setting("non.existent", "default_value")+ assert missing == "default_value"++ def test_set_setting(self):+ """Test setting values."""+ manager = InMemorySettingsManager()++ # Set existing setting+ result = manager.set_setting("llm.temperature", 0.5)+ assert result is True+ assert manager.get_setting("llm.temperature") == 0.5++ # Try to set non-existent setting+ result = manager.set_setting("non.existent", "value")+ assert result is False++ def test_environment_override(self, monkeypatch):+ """Test that environment variables override defaults."""+ # Set environment variables+ monkeypatch.setenv("LDR_LLM_PROVIDER", "anthropic")+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.3")++ manager = InMemorySettingsManager()++ assert manager.get_setting("llm.provider") == "anthropic"+ assert manager.get_setting("llm.temperature") == 0.3+++class TestSettingsSnapshot:+ """Test settings snapshot creation and manipulation."""++ def test_get_default_settings_snapshot(self):+ """Test getting the default settings snapshot."""+ snapshot = get_default_settings_snapshot()++ assert isinstance(snapshot, dict)+ assert len(snapshot) > 0++ # Check structure+ assert "llm.provider" in snapshot+ provider_setting = snapshot["llm.provider"]+ assert "value" in provider_setting+ assert "type" in provider_setting+ assert "description" in provider_setting++ def test_create_settings_snapshot_with_defaults(self):+ """Test creating a snapshot with default settings."""+ snapshot = create_settings_snapshot()++ assert isinstance(snapshot, dict)+ assert len(snapshot) > 0++ def test_create_settings_snapshot_with_kwargs(self):+ """Test creating a snapshot with keyword arguments."""+ snapshot = create_settings_snapshot(+ provider="openai",+ api_key="test-key-123",+ temperature=0.2,+ max_search_results=10,+ )++ # Check provider was set+ assert snapshot["llm.provider"]["value"] == "openai"++ # Check API key was set for the right provider+ assert snapshot["llm.openai.api_key"]["value"] == "test-key-123"++ # Check temperature was set+ assert snapshot["llm.temperature"]["value"] == 0.2++ # Check search results was set+ assert snapshot["search.max_results"]["value"] == 10++ def test_create_settings_snapshot_with_overrides(self):+ """Test creating a snapshot with settings overrides."""+ snapshot = create_settings_snapshot(+ overrides={+ "llm.max_tokens": 2000,+ "search.max_results": 5,+ "new.setting": "custom_value",+ }+ )++ # Check existing settings were overridden+ assert snapshot["llm.max_tokens"]["value"] == 2000+ assert snapshot["search.max_results"]["value"] == 5++ # Check new setting was added+ assert "new.setting" in snapshot+ assert snapshot["new.setting"]["value"] == "custom_value"++ def test_create_settings_snapshot_with_base_settings(self):+ """Test creating a snapshot with custom base settings."""+ base = {"custom.setting": {"value": "base_value", "type": "CUSTOM"}}++ snapshot = create_settings_snapshot(+ base_settings=base, overrides={"custom.setting": "override_value"}+ )++ # Should have the base setting with override+ assert snapshot["custom.setting"]["value"] == "override_value"+ assert snapshot["custom.setting"]["type"] == "CUSTOM"++ def test_extract_setting_value(self):+ """Test extracting values from settings snapshot."""+ snapshot = {+ "setting1": {"value": "test1"},+ "setting2": "direct_value",+ "setting3": {"other": "data"},+ }++ # Extract from dict with value key+ assert extract_setting_value(snapshot, "setting1") == "test1"++ # Extract direct value+ assert extract_setting_value(snapshot, "setting2") == "direct_value"++ # Extract dict without value key+ assert extract_setting_value(snapshot, "setting3") == {"other": "data"}++ # Extract with default+ assert (+ extract_setting_value(snapshot, "missing", "default") == "default"+ )+++class TestProgrammaticAPIIntegration:+ """Test integration with the programmatic API functions."""++ @patch("src.local_deep_research.api.research_functions._init_search_system")+ def test_quick_summary_creates_snapshot(self, mock_init):+ """Test that quick_summary creates a settings snapshot when not provided."""+ from src.local_deep_research.api import quick_summary++ # Configure mock+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Test summary",+ "findings": [],+ "iterations": 1,+ "questions": {},+ "formatted_findings": "Test findings",+ "all_links_of_system": [],+ }+ mock_init.return_value = mock_system++ # Call without settings_snapshot+ _ = quick_summary(+ "Test query",+ provider="anthropic",+ api_key="test-key",+ temperature=0.5,+ )++ # Check that settings_snapshot was created and passed+ call_kwargs = mock_init.call_args[1]+ assert "settings_snapshot" in call_kwargs+ snapshot = call_kwargs["settings_snapshot"]++ # Verify snapshot contains our settings+ assert snapshot["llm.provider"]["value"] == "anthropic"+ assert snapshot["llm.anthropic.api_key"]["value"] == "test-key"+ assert snapshot["llm.temperature"]["value"] == 0.5++ @patch("src.local_deep_research.api.research_functions._init_search_system")+ def test_quick_summary_uses_provided_snapshot(self, mock_init):+ """Test that quick_summary uses provided settings_snapshot."""+ from src.local_deep_research.api import quick_summary++ # Configure mock+ mock_system = MagicMock()+ mock_system.analyze_topic.return_value = {+ "current_knowledge": "Test summary",+ "findings": [],+ "iterations": 1,+ "questions": {},+ "formatted_findings": "Test findings",+ "all_links_of_system": [],+ }+ mock_init.return_value = mock_system++ # Create custom snapshot+ custom_snapshot = {"test": "snapshot"}++ # Call with settings_snapshot+ _ = quick_summary("Test query", settings_snapshot=custom_snapshot)++ # Check that our snapshot was passed through+ call_kwargs = mock_init.call_args[1]+ assert call_kwargs["settings_snapshot"] == custom_snapshot