~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
Remove redundant Ollama pre-flight HTTP checks from get_llm() code path (#3371)
LearningCircuita208835066a7
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex b7735571f6..fbf52100c5 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -9,7 +9,6 @@ from loguru import loggerfrom ..llm import get_llm_from_registry, is_llm_registeredfrom ..utilities.search_utilities import remove_think_tagsfrom ..utilities.url_utils import normalize_url-from ..security import safe_getfrom .constants import DEFAULT_OLLAMA_URL, DEFAULT_LMSTUDIO_URL# Import providers module to trigger auto-discovery@@ -560,52 +559,6 @@ def get_llm(else DEFAULT_OLLAMA_URL)- # Check if Ollama is available before trying to use it- if not is_ollama_available(settings_snapshot=settings_snapshot):- raise ValueError( # noqa: TRY301 — propagates through except that logs and re-raises- f"Ollama is not available at {base_url}. Please ensure Ollama is running."- )-- # Check if the requested model exists- try:- logger.info(- f"Checking if model '{model_name}' exists in Ollama"- )- response = safe_get(- f"{base_url}/api/tags",- timeout=3,- allow_localhost=True,- allow_private_ips=True,- )- if response.status_code == 200:- # Handle both newer and older Ollama API formats- data = response.json()- models = []- if "models" in data:- # Newer Ollama API- models = data.get("models", [])- else:- # Older Ollama API format- models = data-- # Get list of model names- model_names = [m.get("name", "").lower() for m in models]- logger.info(- f"Available Ollama models: {', '.join(model_names[:5])}{' and more' if len(model_names) > 5 else ''}"- )-- if model_name.lower() not in model_names:- raise ValueError( # noqa: TRY301 — re-raised by except ValueError below- f"Model '{model_name}' not found in Ollama. Available models: {', '.join(model_names[:5])}"- )- except ValueError:- raise- except Exception:- logger.exception(- f"Error checking for model '{model_name}' in Ollama"- )- # Continue anyway, let ChatOllama handle potential errors-logger.info(f"Creating ChatOllama with model={model_name}, base_url={base_url}")diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.pyindex 25547e05f2..49a7edb9a9 100644--- a/src/local_deep_research/llm/providers/implementations/ollama.py+++ b/src/local_deep_research/llm/providers/implementations/ollama.py@@ -124,58 +124,6 @@ class OllamaProvider(BaseLLMProvider):)base_url = normalize_url(raw_base_url)- # Check if Ollama is available before trying to use it- if not cls.is_available(settings_snapshot):- logger.error(f"Ollama not available at {base_url}.")- raise ValueError(f"Ollama not available at {base_url}")-- # Check if the requested model exists- try:- logger.info(f"Checking if model '{model_name}' exists in Ollama")-- # Get authentication headers- headers = cls._get_auth_headers(settings_snapshot=settings_snapshot)-- response = safe_get(- f"{base_url}/api/tags",- timeout=3,- headers=headers,- allow_localhost=True,- allow_private_ips=True,- )- if response.status_code == 200:- # Handle both newer and older Ollama API formats- data = response.json()- models = []- if "models" in data:- # Newer Ollama API- models = data.get("models", [])- else:- # Older Ollama API format- models = data-- # Get list of model names- model_names = [m.get("name", "").lower() for m in models]- logger.info(- f"Available Ollama models: {', '.join(model_names[:5])}{' and more' if len(model_names) > 5 else ''}"- )-- if model_name.lower() not in model_names:- logger.error(- f"Model '{model_name}' not found in Ollama. Available models: {', '.join(model_names[:5])}"- )- raise ValueError( # noqa: TRY301 — re-raised by except ValueError below- f"Model '{model_name}' not found in Ollama"- )- except ValueError:- raise- except Exception:- logger.debug(- f"Error checking for model '{model_name}' in Ollama",- exc_info=True,- )- # Continue anyway, let ChatOllama handle potential errors-logger.info(f"Creating ChatOllama with model={model_name}, base_url={base_url}")diff --git a/tests/config/test_llm_config_extended.py b/tests/config/test_llm_config_extended.pyindex 4d80bb58ea..ff8328ffb9 100644--- a/tests/config/test_llm_config_extended.py+++ b/tests/config/test_llm_config_extended.py@@ -277,12 +277,11 @@ class TestOllamaProvider:return sdef test_model_not_found_raises_error(self):- """Model not in Ollama model list raises ValueError."""+ """Model not in Ollama model list — now handled by ChatOllama itself."""settings = self._ollama_settings()- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {"models": [{"name": "other-model"}]}+ mock_ollama_cls = MagicMock()+ mock_ollama_cls.return_value = MagicMock()with (patch(@@ -294,25 +293,22 @@ class TestOllamaProvider:side_effect=_mock_get_setting(settings),),patch(- "local_deep_research.config.llm_config.is_ollama_available",- return_value=True,+ "local_deep_research.config.llm_config.ChatOllama",+ mock_ollama_cls,),patch(- "local_deep_research.config.llm_config.safe_get",- return_value=mock_response,+ "local_deep_research.config.llm_config.wrap_llm_without_think_tags",+ return_value=MagicMock(),),):- with pytest.raises(ValueError, match="test-model"):- get_llm(provider="ollama", model_name="test-model")+ get_llm(provider="ollama", model_name="test-model")+ # No pre-flight check — ChatOllama is created regardless+ mock_ollama_cls.assert_called_once()def test_model_found_creates_client(self):- """Model found in list creates ChatOllama."""+ """Model creates ChatOllama (no pre-flight model check)."""settings = self._ollama_settings()- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {"models": [{"name": "test-model"}]}-mock_ollama_cls = MagicMock()mock_ollama_instance = MagicMock()mock_ollama_cls.return_value = mock_ollama_instance@@ -326,14 +322,6 @@ class TestOllamaProvider:"local_deep_research.config.llm_config.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(- "local_deep_research.config.llm_config.is_ollama_available",- return_value=True,- ),- patch(- "local_deep_research.config.llm_config.safe_get",- return_value=mock_response,- ),patch("local_deep_research.config.llm_config.ChatOllama",mock_ollama_cls,@@ -348,7 +336,7 @@ class TestOllamaProvider:assert result is mock_ollama_instancedef test_api_tags_exception_continues(self):- """Exception checking model list doesn't crash — continues to create ChatOllama."""+ """No pre-flight check means ChatOllama is always created directly."""settings = self._ollama_settings()mock_ollama_cls = MagicMock()@@ -364,14 +352,6 @@ class TestOllamaProvider:"local_deep_research.config.llm_config.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(- "local_deep_research.config.llm_config.is_ollama_available",- return_value=True,- ),- patch(- "local_deep_research.config.llm_config.safe_get",- side_effect=ConnectionError("refused"),- ),patch("local_deep_research.config.llm_config.ChatOllama",mock_ollama_cls,@@ -382,7 +362,6 @@ class TestOllamaProvider:),):result = get_llm(provider="ollama", model_name="test-model")- # Should still try to create ChatOllama despite API errormock_ollama_cls.assert_called_once()assert result is mock_ollama_instancediff --git a/tests/config/test_llm_config_missing_coverage.py b/tests/config/test_llm_config_missing_coverage.pyindex 4b8ebce908..96400f1ea2 100644--- a/tests/config/test_llm_config_missing_coverage.py+++ b/tests/config/test_llm_config_missing_coverage.py@@ -175,45 +175,41 @@ class TestGetLlmOllamaEdgeCases:return sdef test_ollama_model_not_found_raises_error(self):- """When model is not in the Ollama model list, ValueError is raised (fallback removed)."""+ """When model is not in the Ollama model list, ChatOllama handles it at invoke time (no pre-flight check)."""settings = self._ollama_settings()- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {- "models": [{"name": "llama2"}, {"name": "mistral"}]- }+ mock_ollama_cls = MagicMock()+ mock_ollama_cls.return_value = MagicMock()with (patch(f"{MODULE}.is_llm_registered", return_value=False),patch(f"{MODULE}.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(f"{MODULE}.is_ollama_available", return_value=True),- patch(f"{MODULE}.safe_get", return_value=mock_response),+ patch(f"{MODULE}.ChatOllama", mock_ollama_cls),+ patch(+ f"{MODULE}.wrap_llm_without_think_tags",+ return_value=MagicMock(),+ ),):from local_deep_research.config.llm_config import get_llm- with pytest.raises(ValueError, match="not found in Ollama"):- get_llm(- provider="ollama",- model_name="nonexistent-model",- settings_snapshot=settings,- )+ # No pre-flight check — ChatOllama is created regardless of model existence+ get_llm(+ provider="ollama",+ model_name="nonexistent-model",+ settings_snapshot=settings,+ )+ mock_ollama_cls.assert_called_once()def test_ollama_creation_exception_raises_error(self):"""When ChatOllama() raises, exception is propagated (fallback removed)."""settings = self._ollama_settings()- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {"models": [{"name": "test-model"}]}with (patch(f"{MODULE}.is_llm_registered", return_value=False),patch(f"{MODULE}.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(f"{MODULE}.is_ollama_available", return_value=True),- patch(f"{MODULE}.safe_get", return_value=mock_response),patch(f"{MODULE}.ChatOllama",side_effect=RuntimeError("failed to init"),@@ -231,9 +227,6 @@ class TestGetLlmOllamaEdgeCases:def test_ollama_enable_thinking_true_sets_reasoning(self):"""When enable_thinking is True, reasoning=True is passed to ChatOllama."""settings = self._ollama_settings({"llm.ollama.enable_thinking": True})- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {"models": [{"name": "test-model"}]}mock_ollama_cls = MagicMock()mock_ollama_cls.return_value = MagicMock()with (@@ -242,8 +235,6 @@ class TestGetLlmOllamaEdgeCases:f"{MODULE}.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(f"{MODULE}.is_ollama_available", return_value=True),- patch(f"{MODULE}.safe_get", return_value=mock_response),patch(f"{MODULE}.ChatOllama", mock_ollama_cls),patch(f"{MODULE}.wrap_llm_without_think_tags",@@ -263,9 +254,6 @@ class TestGetLlmOllamaEdgeCases:def test_ollama_enable_thinking_false_sets_reasoning_false(self):"""When enable_thinking is False, reasoning=False is passed to ChatOllama."""settings = self._ollama_settings({"llm.ollama.enable_thinking": False})- mock_response = MagicMock()- mock_response.status_code = 200- mock_response.json.return_value = {"models": [{"name": "test-model"}]}mock_ollama_cls = MagicMock()mock_ollama_cls.return_value = MagicMock()with (@@ -274,8 +262,6 @@ class TestGetLlmOllamaEdgeCases:f"{MODULE}.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(f"{MODULE}.is_ollama_available", return_value=True),- patch(f"{MODULE}.safe_get", return_value=mock_response),patch(f"{MODULE}.ChatOllama", mock_ollama_cls),patch(f"{MODULE}.wrap_llm_without_think_tags",diff --git a/tests/llm_providers/test_ollama_deep_coverage.py b/tests/llm_providers/test_ollama_deep_coverage.pyindex a780648d23..d910b1bfcc 100644--- a/tests/llm_providers/test_ollama_deep_coverage.py+++ b/tests/llm_providers/test_ollama_deep_coverage.py@@ -94,8 +94,8 @@ class TestIsAvailableAdditional:class TestCreateLlmOlderApiFormat:- def test_older_api_format_list_used_for_model_check(self):- """Ollama older API returns a plain list, not {"models": [...]}."""+ def test_create_llm_succeeds_without_preflight(self):+ """create_llm now skips pre-flight checks and creates ChatOllama directly."""def _get_setting(key, default=None, *args, **kwargs):return {@@ -106,20 +106,11 @@ class TestCreateLlmOlderApiFormat:}.get(key, default)with patch(GET_SETTING, side_effect=_get_setting):- with patch.object(- OllamaProvider, "is_available", return_value=True- ):- mock_resp = Mock()- mock_resp.status_code = 200- # Older format: list directly, no "models" key- mock_resp.json.return_value = [{"name": "gemma3:12b"}]-- with patch(f"{MODULE}.safe_get", return_value=mock_resp):- with patch(f"{MODULE}.ChatOllama") as mock_chat:- mock_chat.return_value = Mock()- OllamaProvider.create_llm(model_name="gemma3:12b")+ with patch(f"{MODULE}.ChatOllama") as mock_chat:+ mock_chat.return_value = Mock()+ OllamaProvider.create_llm(model_name="gemma3:12b")- mock_chat.assert_called_once()+ mock_chat.assert_called_once()# ---------------------------------------------------------------------------@@ -139,23 +130,13 @@ class TestCreateLlmContextWindowNone:return mapping.get(key, default)with patch(GET_SETTING, side_effect=_get_setting):- with patch.object(- OllamaProvider, "is_available", return_value=True- ):- mock_resp = Mock()- mock_resp.status_code = 200- mock_resp.json.return_value = {- "models": [{"name": "gemma3:12b"}]- }-- with patch(f"{MODULE}.safe_get", return_value=mock_resp):- with patch(f"{MODULE}.ChatOllama") as mock_chat:- mock_chat.return_value = Mock()- OllamaProvider.create_llm(model_name="gemma3:12b")-- call_kwargs = mock_chat.call_args[1]- assert "num_ctx" not in call_kwargs- assert "max_tokens" not in call_kwargs+ with patch(f"{MODULE}.ChatOllama") as mock_chat:+ mock_chat.return_value = Mock()+ OllamaProvider.create_llm(model_name="gemma3:12b")++ call_kwargs = mock_chat.call_args[1]+ assert "num_ctx" not in call_kwargs+ assert "max_tokens" not in call_kwargs# ---------------------------------------------------------------------------diff --git a/tests/llm_providers/test_ollama_provider.py b/tests/llm_providers/test_ollama_provider.pyindex b4c6d06c1a..07c09f2a8f 100644--- a/tests/llm_providers/test_ollama_provider.py+++ b/tests/llm_providers/test_ollama_provider.py@@ -193,21 +193,6 @@ class TestOllamaCreateLLM:assert "url not configured" in str(exc_info.value).lower()- def test_create_llm_raises_when_unavailable(self):- """Raises ValueError when Ollama not available."""- with patch(- "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot"- ) as mock_get_setting:- mock_get_setting.return_value = "http://localhost:11434"-- with patch.object(- OllamaProvider, "is_available", return_value=False- ):- with pytest.raises(ValueError) as exc_info:- OllamaProvider.create_llm()-- assert "not available" in str(exc_info.value).lower()-def test_create_llm_success(self):"""Successfully creates ChatOllama instance."""@@ -225,28 +210,16 @@ class TestOllamaCreateLLM:) as mock_get_setting:mock_get_setting.side_effect = mock_get_setting_side_effect- with patch.object(- OllamaProvider, "is_available", return_value=True- ):- with patch("requests.get") as mock_get:- # Mock model check response- mock_response = Mock()- mock_response.status_code = 200- mock_response.json.return_value = {- "models": [{"name": "gemma3:12b"}]- }- mock_get.return_value = mock_response-- with patch(- "local_deep_research.llm.providers.implementations.ollama.ChatOllama"- ) as mock_chat_ollama:- mock_llm = Mock()- mock_chat_ollama.return_value = mock_llm-- result = OllamaProvider.create_llm()-- assert result is mock_llm- mock_chat_ollama.assert_called_once()+ with patch(+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"+ ) as mock_chat_ollama:+ mock_llm = Mock()+ mock_chat_ollama.return_value = mock_llm++ result = OllamaProvider.create_llm()++ assert result is mock_llm+ mock_chat_ollama.assert_called_once()def test_create_llm_uses_default_model(self):"""Uses default model when none specified."""@@ -265,26 +238,13 @@ class TestOllamaCreateLLM:) as mock_get_setting:mock_get_setting.side_effect = mock_get_setting_side_effect- with patch.object(- OllamaProvider, "is_available", return_value=True- ):- with patch("requests.get") as mock_get:- mock_response = Mock()- mock_response.status_code = 200- mock_response.json.return_value = {- "models": [{"name": "gemma3:12b"}]- }- mock_get.return_value = mock_response-- with patch(- "local_deep_research.llm.providers.implementations.ollama.ChatOllama"- ) as mock_chat_ollama:- OllamaProvider.create_llm()-- call_kwargs = mock_chat_ollama.call_args[1]- assert (- call_kwargs["model"] == OllamaProvider.default_model- )+ with patch(+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"+ ) as mock_chat_ollama:+ OllamaProvider.create_llm()++ call_kwargs = mock_chat_ollama.call_args[1]+ assert call_kwargs["model"] == OllamaProvider.default_modeldef test_create_llm_with_custom_temperature(self):"""Uses custom temperature."""@@ -303,21 +263,10 @@ class TestOllamaCreateLLM:) as mock_get_setting:mock_get_setting.side_effect = mock_get_setting_side_effect- with patch.object(- OllamaProvider, "is_available", return_value=True- ):- with patch("requests.get") as mock_get:- mock_response = Mock()- mock_response.status_code = 200- mock_response.json.return_value = {- "models": [{"name": "gemma3:12b"}]- }- mock_get.return_value = mock_response-- with patch(- "local_deep_research.llm.providers.implementations.ollama.ChatOllama"- ) as mock_chat_ollama:- OllamaProvider.create_llm(temperature=0.5)-- call_kwargs = mock_chat_ollama.call_args[1]- assert call_kwargs["temperature"] == 0.5+ with patch(+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"+ ) as mock_chat_ollama:+ OllamaProvider.create_llm(temperature=0.5)++ call_kwargs = mock_chat_ollama.call_args[1]+ assert call_kwargs["temperature"] == 0.5