~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
refactor: deduplicate provider availability checks and settings wrapper (#2054) (#2066)
LearningCircuite69bc6afa646
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 9043ed60de..49b5838530 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -39,90 +39,52 @@ VALID_PROVIDERS = [def is_openai_available(settings_snapshot=None):- """Check if OpenAI is available"""+ """Check if OpenAI is available by delegating to the provider class."""try:- api_key = get_setting_from_snapshot(- "llm.openai.api_key",- default=None,- settings_snapshot=settings_snapshot,- )- return bool(api_key)+ from ..llm.providers.implementations.openai import OpenAIProvider++ return OpenAIProvider.is_available(settings_snapshot)+ except ImportError:+ return Falseexcept Exception:return Falsedef is_anthropic_available(settings_snapshot=None):- """Check if Anthropic is available"""+ """Check if Anthropic is available by delegating to the provider class."""try:- api_key = get_setting_from_snapshot(- "llm.anthropic.api_key",- default=None,- settings_snapshot=settings_snapshot,- )- return bool(api_key)+ from ..llm.providers.implementations.anthropic import AnthropicProvider++ return AnthropicProvider.is_available(settings_snapshot)+ except ImportError:+ return Falseexcept Exception:return Falsedef is_openai_endpoint_available(settings_snapshot=None):- """Check if OpenAI endpoint is available"""+ """Check if OpenAI endpoint is available by delegating to the provider class."""try:- api_key = get_setting_from_snapshot(- "llm.openai_endpoint.api_key",- default=None,- settings_snapshot=settings_snapshot,+ from ..llm.providers.implementations.custom_openai_endpoint import (+ CustomOpenAIEndpointProvider,)- return bool(api_key)++ return CustomOpenAIEndpointProvider.is_available(settings_snapshot)+ except ImportError:+ return Falseexcept Exception:return Falsedef is_ollama_available(settings_snapshot=None):- """Check if Ollama is running"""+ """Check if Ollama is running by delegating to the provider class."""try:- import requests-- raw_base_url = get_setting_from_snapshot(- "llm.ollama.url",- "http://localhost:11434",- settings_snapshot=settings_snapshot,- )- base_url = (- normalize_url(raw_base_url)- if raw_base_url- else "http://localhost:11434"- )- logger.info(f"Checking Ollama availability at {base_url}/api/tags")+ from ..llm.providers.implementations.ollama import OllamaProvider- try:- response = safe_get(- f"{base_url}/api/tags",- timeout=3.0,- allow_localhost=True,- allow_private_ips=True,- )- if response.status_code == 200:- logger.info(- f"Ollama is available. Status code: {response.status_code}"- )- # Log first 100 chars of response to debug- logger.info(f"Response preview: {str(response.text)[:100]}")- return True- else:- logger.warning(- f"Ollama API returned status code: {response.status_code}"- )- return False- except requests.exceptions.RequestException as req_error:- logger.exception(- f"Request error when checking Ollama: {req_error!s}"- )- return False- except Exception:- logger.exception("Unexpected error when checking Ollama")- return False+ return OllamaProvider.is_available(settings_snapshot)+ except ImportError:+ return Falseexcept Exception:- logger.exception("Error in is_ollama_available")return False@@ -144,23 +106,13 @@ def is_vllm_available():def is_lmstudio_available(settings_snapshot=None):- """Check if LM Studio is available"""+ """Check if LM Studio is available by delegating to the provider class."""try:- lmstudio_url = get_setting_from_snapshot(- "llm.lmstudio.url",- "http://localhost:1234/v1",- settings_snapshot=settings_snapshot,- )- # Use URL as-is (default already includes /v1)- base_url = normalize_url(lmstudio_url)- # LM Studio typically uses OpenAI-compatible endpoints- response = safe_get(- f"{base_url}/models",- timeout=1.0,- allow_localhost=True,- allow_private_ips=True,- )- return response.status_code == 200+ from ..llm.providers.implementations.lmstudio import LMStudioProvider++ return LMStudioProvider.is_available(settings_snapshot)+ except ImportError:+ return Falseexcept Exception:return Falsediff --git a/src/local_deep_research/database/queue_service.py b/src/local_deep_research/database/queue_service.pyindex 588796dc8b..bcc6c381fd 100644--- a/src/local_deep_research/database/queue_service.py+++ b/src/local_deep_research/database/queue_service.py@@ -150,27 +150,23 @@ class UserQueueService:status = self.session.query(QueueStatus).first()return status.queued_tasks if status else 0- def _increment_queue_count(self):- """Increment the queued task count."""+ def _get_or_create_status(self) -> QueueStatus:+ """Get existing queue status or create a new one with zero counts."""status = self.session.query(QueueStatus).first()- if status:- status.queued_tasks += 1- status.last_checked = datetime.now(UTC)- else:- status = QueueStatus(queued_tasks=1, active_tasks=0)+ if status is None:+ status = QueueStatus(queued_tasks=0, active_tasks=0)self.session.add(status)+ return status++ def _increment_queue_count(self):+ """Increment the queued task count."""+ status = self._get_or_create_status()+ status.queued_tasks += 1+ status.last_checked = datetime.now(UTC)def _update_queue_counts(self, queued_delta: int, active_delta: int):"""Update queue counts by deltas."""- status = self.session.query(QueueStatus).first()- if status:- status.queued_tasks = max(0, status.queued_tasks + queued_delta)- status.active_tasks = max(0, status.active_tasks + active_delta)- status.last_checked = datetime.now(UTC)- else:- # Create new status if doesn't exist- status = QueueStatus(- queued_tasks=max(0, queued_delta),- active_tasks=max(0, active_delta),- )- self.session.add(status)+ status = self._get_or_create_status()+ status.queued_tasks = max(0, status.queued_tasks + queued_delta)+ status.active_tasks = max(0, status.active_tasks + active_delta)+ status.last_checked = datetime.now(UTC)diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.pyindex 3f3873d899..8cbdabfda1 100644--- a/tests/config/test_llm_config.py+++ b/tests/config/test_llm_config.py@@ -51,9 +51,9 @@ class TestGetSettingFromSnapshot:"""Tests for get_setting_from_snapshot wrapper."""def test_enables_fallback_llm_check(self):- """Should enable check_fallback_llm."""+ """Should enable check_fallback_llm via get_llm_setting_from_snapshot."""with patch(- "local_deep_research.config.llm_config._get_setting_from_snapshot"+ "local_deep_research.config.thread_settings.get_setting_from_snapshot") as mock:mock.return_value = "value"get_setting_from_snapshot("key", "default")@@ -63,114 +63,99 @@ class TestGetSettingFromSnapshot:class TestIsOpenaiAvailable:- """Tests for is_openai_available function."""+ """Tests for is_openai_available function (delegates to OpenAIProvider)."""def test_returns_true_when_api_key_set(self):"""Should return True when API key is configured."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="sk-test-key",+ "local_deep_research.llm.providers.implementations.openai.OpenAIProvider.is_available",+ return_value=True,):assert is_openai_available() is Truedef test_returns_false_when_no_api_key(self):"""Should return False when no API key."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value=None,+ "local_deep_research.llm.providers.implementations.openai.OpenAIProvider.is_available",+ return_value=False,):assert is_openai_available() is Falsedef test_returns_false_on_exception(self):"""Should return False on exception."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",+ "local_deep_research.llm.providers.implementations.openai.OpenAIProvider.is_available",side_effect=Exception("error"),):assert is_openai_available() is Falseclass TestIsAnthropicAvailable:- """Tests for is_anthropic_available function."""+ """Tests for is_anthropic_available function (delegates to AnthropicProvider)."""def test_returns_true_when_api_key_set(self):"""Should return True when API key is configured."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="sk-ant-test",+ "local_deep_research.llm.providers.implementations.anthropic.AnthropicProvider.is_available",+ return_value=True,):assert is_anthropic_available() is Truedef test_returns_false_when_no_api_key(self):"""Should return False when no API key."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value=None,+ "local_deep_research.llm.providers.implementations.anthropic.AnthropicProvider.is_available",+ return_value=False,):assert is_anthropic_available() is Falseclass TestIsOpenaiEndpointAvailable:- """Tests for is_openai_endpoint_available function."""+ """Tests for is_openai_endpoint_available function (delegates to CustomOpenAIEndpointProvider)."""def test_returns_true_when_api_key_set(self):"""Should return True when API key is configured."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="custom-key",+ "local_deep_research.llm.providers.openai_base.OpenAICompatibleProvider.is_available",+ return_value=True,):assert is_openai_endpoint_available() is Truedef test_returns_false_when_no_api_key(self):"""Should return False when no API key."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value=None,+ "local_deep_research.llm.providers.openai_base.OpenAICompatibleProvider.is_available",+ return_value=False,):assert is_openai_endpoint_available() is Falseclass TestIsOllamaAvailable:- """Tests for is_ollama_available function."""+ """Tests for is_ollama_available function (delegates to OllamaProvider)."""def test_returns_true_when_ollama_responds(self):- """Should return True when Ollama responds with 200."""- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.text = '{"models": []}'-+ """Should return True when OllamaProvider reports available."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="http://localhost:11434",+ "local_deep_research.llm.providers.implementations.ollama.OllamaProvider.is_available",+ return_value=True,):- with patch("requests.get", return_value=mock_response):- assert is_ollama_available() is True+ assert is_ollama_available() is Truedef test_returns_false_when_ollama_not_running(self):- """Should return False when Ollama not responding."""- import requests-+ """Should return False when OllamaProvider reports unavailable."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="http://localhost:11434",+ "local_deep_research.llm.providers.implementations.ollama.OllamaProvider.is_available",+ return_value=False,):- with patch(- "requests.get",- side_effect=requests.exceptions.ConnectionError("refused"),- ):- assert is_ollama_available() is False-- def test_returns_false_on_non_200_status(self):- """Should return False on non-200 status code."""- mock_response = MagicMock()- mock_response.status_code = 500+ assert is_ollama_available() is False+ def test_returns_false_on_exception(self):+ """Should return False on exception."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="http://localhost:11434",+ "local_deep_research.llm.providers.implementations.ollama.OllamaProvider.is_available",+ side_effect=Exception("error"),):- with patch("requests.get", return_value=mock_response):- assert is_ollama_available() is False+ assert is_ollama_available() is Falseclass TestIsVllmAvailable:@@ -189,30 +174,23 @@ class TestIsVllmAvailable:class TestIsLmstudioAvailable:- """Tests for is_lmstudio_available function."""+ """Tests for is_lmstudio_available function (delegates to LMStudioProvider)."""def test_returns_true_when_lmstudio_responds(self):- """Should return True when LM Studio responds with 200."""- mock_response = MagicMock()- mock_response.status_code = 200-+ """Should return True when LMStudioProvider reports available."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="http://localhost:1234",+ "local_deep_research.llm.providers.implementations.lmstudio.LMStudioProvider.is_available",+ return_value=True,):- with patch("requests.get", return_value=mock_response):- assert is_lmstudio_available() is True+ assert is_lmstudio_available() is Truedef test_returns_false_when_not_running(self):- """Should return False when LM Studio not responding."""+ """Should return False when LMStudioProvider reports unavailable."""with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot",- return_value="http://localhost:1234",+ "local_deep_research.llm.providers.implementations.lmstudio.LMStudioProvider.is_available",+ return_value=False,):- with patch(- "requests.get", side_effect=Exception("connection error")- ):- assert is_lmstudio_available() is False+ assert is_lmstudio_available() is Falseclass TestIsLlamacppAvailable: