~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(api): single-source the Ollama /api/tags probe (H1) (#4650)
LearningCircuit6495edfc960e
diff --git a/changelog.d/4650.misc.md b/changelog.d/4650.misc.mdnew file mode 100644index 0000000000..c719e371e1--- /dev/null+++ b/changelog.d/4650.misc.md@@ -0,0 +1 @@+The two Ollama health-check endpoints (`/check/ollama_status`, `/check/ollama_model`) now share a single `/api/tags` probe helper instead of separately re-implementing the fetch + new/old API-format parsing + error classification, so "is Ollama up?" answers consistently across them. No change to the endpoints' responses.diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.pyindex 04a23ebcad..a1da380da8 100644--- a/src/local_deep_research/web/routes/api_routes.py+++ b/src/local_deep_research/web/routes/api_routes.py@@ -292,6 +292,61 @@ def api_delete_resource(research_id, resource_id):), 500+def _ollama_base_url_from_config(llm_config):+ """Resolve the Ollama base URL from the LLM config (normalized, with the+ default fallback). Single source so every Ollama probe targets the same+ URL."""+ raw = llm_config.get("ollama_base_url", DEFAULT_OLLAMA_URL)+ return normalize_url(raw) if raw else DEFAULT_OLLAMA_URL+++def _probe_ollama_tags(base_url, timeout=5):+ """Probe Ollama ``/api/tags`` once and classify the outcome.++ Single source for the resolve→fetch→new/old-format-parse→error logic that+ was previously copy-pasted across the status and model-availability checks+ (so "is Ollama up?" can no longer answer differently per caller). Returns+ ``(outcome, probe_result)`` where outcome is one of:++ - ``"ok"`` → probe_result is the list of model dicts (both API formats handled)+ - ``"bad_status"`` → probe_result is the non-200 status code+ - ``"invalid_json"`` → probe_result is None (200 but unparseable body)+ - ``"connection_error"`` / ``"timeout"`` → probe_result is None++ Callers map the outcome onto their own response shape.+ """+ try:+ response = safe_get(+ f"{base_url}/api/tags",+ timeout=timeout,+ allow_localhost=True,+ allow_private_ips=True,+ )+ except requests.exceptions.ConnectionError:+ return "connection_error", None+ except requests.exceptions.Timeout:+ return "timeout", None++ if response.status_code != 200:+ return "bad_status", response.status_code++ try:+ data = response.json()+ except ValueError:+ return "invalid_json", None++ # New Ollama API nests the list under "models"; the older format is a+ # bare list. Mirror the previous inline check exactly (a bare ``"models"+ # in data`` membership test, no isinstance guard) so behavior is identical+ # to the pre-refactor endpoints — a malformed non-dict/non-list body+ # raises here and is handled by each caller's outer except, as before.+ if "models" in data:+ models = data.get("models", [])+ else:+ models = data+ return "ok", models++@api_bp.route("/check/ollama_status", methods=["GET"])@login_requireddef check_ollama_status():@@ -311,99 +366,61 @@ def check_ollama_status():})- # Get Ollama API URL from LLM config- raw_ollama_base_url = llm_config.get(- "ollama_base_url", DEFAULT_OLLAMA_URL- )- ollama_base_url = (- normalize_url(raw_ollama_base_url)- if raw_ollama_base_url- else DEFAULT_OLLAMA_URL- )-+ ollama_base_url = _ollama_base_url_from_config(llm_config)logger.info(f"Checking Ollama status at: {ollama_base_url}")- # Check if Ollama is running- try:- response = safe_get(- f"{ollama_base_url}/api/tags",- timeout=5,- allow_localhost=True,- allow_private_ips=True,- )+ outcome, probe_result = _probe_ollama_tags(ollama_base_url)- # Add response details for debugging- logger.debug(- f"Ollama status check response code: {response.status_code}"+ if outcome == "ok":+ model_count = len(probe_result)+ logger.info(f"Ollama service is running with {model_count} models")+ return jsonify(+ {+ "running": True,+ "message": f"Ollama service is running with {model_count} models",+ "model_count": model_count,+ }+ )+ if outcome == "invalid_json":+ logger.warning("Ollama returned invalid JSON")+ return jsonify(+ {+ "running": True,+ "message": "Ollama service is running but returned invalid data format",+ "error_details": "Invalid response format from the service.",+ }+ )+ if outcome == "bad_status":+ logger.warning(+ f"Ollama returned non-200 status code: {probe_result}")-- if response.status_code == 200:- # Try to validate the response content- try:- data = response.json()-- # Check the format- if "models" in data:- model_count = len(data.get("models", []))- logger.info(- f"Ollama service is running with {model_count} models (new API format)"- )- else:- # Older API format- model_count = len(data)- logger.info(- f"Ollama service is running with {model_count} models (old API format)"- )-- return jsonify(- {- "running": True,- "message": f"Ollama service is running with {model_count} models",- "model_count": model_count,- }- )- except ValueError:- logger.warning("Ollama returned invalid JSON")- # It's running but returned invalid JSON- return jsonify(- {- "running": True,- "message": "Ollama service is running but returned invalid data format",- "error_details": "Invalid response format from the service.",- }- )- else:- logger.warning(- f"Ollama returned non-200 status code: {response.status_code}"- )- return jsonify(- {- "running": False,- "message": f"Ollama service returned status code: {response.status_code}",- "status_code": response.status_code,- }- )-- except requests.exceptions.ConnectionError:- logger.warning("Ollama connection error")return jsonify({"running": False,- "message": "Ollama service is not running or not accessible",- "error_type": "connection_error",- "error_details": "Unable to connect to the service. Please check if the service is running.",+ "message": f"Ollama service returned status code: {probe_result}",+ "status_code": probe_result,})- except requests.exceptions.Timeout:- logger.warning("Ollama request timed out")+ if outcome == "connection_error":+ logger.warning("Ollama connection error")return jsonify({"running": False,- "message": "Ollama service request timed out after 5 seconds",- "error_type": "timeout",- "error_details": "Request timed out. The service may be overloaded.",+ "message": "Ollama service is not running or not accessible",+ "error_type": "connection_error",+ "error_details": "Unable to connect to the service. Please check if the service is running.",})+ # outcome == "timeout"+ logger.warning("Ollama request timed out")+ return jsonify(+ {+ "running": False,+ "message": "Ollama service request timed out after 5 seconds",+ "error_type": "timeout",+ "error_details": "Request timed out. The service may be overloaded.",+ }+ )except Exception:logger.exception("Error checking Ollama status")@@ -462,128 +479,33 @@ def check_ollama_model():# Log which model we're checking for debugginglogger.info(f"Checking availability of Ollama model: {model_name}")- # Get Ollama API URL from LLM config- raw_ollama_base_url = llm_config.get(- "ollama_base_url", DEFAULT_OLLAMA_URL- )- ollama_base_url = (- normalize_url(raw_ollama_base_url)- if raw_ollama_base_url- else DEFAULT_OLLAMA_URL- )-- # Check if the model is available- try:- response = safe_get(- f"{ollama_base_url}/api/tags",- timeout=5,- allow_localhost=True,- allow_private_ips=True,- )-- # Log response details for debugging- logger.debug(f"Ollama API response status: {response.status_code}")+ ollama_base_url = _ollama_base_url_from_config(llm_config)- if response.status_code != 200:- logger.warning(- f"Ollama API returned non-200 status: {response.status_code}"- )- return jsonify(- {- "available": False,- "model": model_name,- "message": f"Could not access Ollama service - status code: {response.status_code}",- "status_code": response.status_code,- }- )-- # Try to parse the response- try:- data = response.json()-- # Debug log the first bit of the response- response_preview = (- str(data)[:500] + "..."- if len(str(data)) > 500- else str(data)- )- logger.debug(f"Ollama API response data: {response_preview}")-- # Get models based on API format- models = []- if "models" in data:- # Newer Ollama API- logger.debug("Using new Ollama API format (models key)")- models = data.get("models", [])- else:- # Older Ollama API format- logger.debug("Using old Ollama API format (array)")- models = data-- # Log available models for debugging- model_names = [m.get("name", "") for m in models]- logger.debug(- f"Available Ollama models: {', '.join(model_names[:10])}"- + (- f" and {len(model_names) - 10} more"- if len(model_names) > 10- else ""- )- )-- # Case-insensitive model name comparison- model_exists = any(- m.get("name", "").lower() == model_name.lower()- for m in models- )-- if model_exists:- logger.info(f"Ollama model {model_name} is available")- return jsonify(- {- "available": True,- "model": model_name,- "message": f"Model {model_name} is available",- "all_models": model_names,- }- )- # Check if models were found at all- if not models:- logger.warning("No models found in Ollama")- message = (- "No models found in Ollama. Please pull models first."- )- else:- logger.warning(- f"Model {model_name} not found among {len(models)} available models"- )- # Don't expose available models for security reasons- message = f"Model {model_name} is not available"-- return jsonify(- {- "available": False,- "model": model_name,- "message": message,- # Remove all_models to prevent information disclosure- }- )- except ValueError as json_err:- # JSON parsing error- logger.exception(- f"Failed to parse Ollama API response: {json_err}"- )- return jsonify(- {- "available": False,- "model": model_name,- "message": "Invalid response from Ollama API",- "error_type": "json_parse_error",- }- )+ outcome, probe_result = _probe_ollama_tags(ollama_base_url)- except requests.exceptions.ConnectionError:- # Connection error+ if outcome == "bad_status":+ logger.warning(+ f"Ollama API returned non-200 status: {probe_result}"+ )+ return jsonify(+ {+ "available": False,+ "model": model_name,+ "message": f"Could not access Ollama service - status code: {probe_result}",+ "status_code": probe_result,+ }+ )+ if outcome == "invalid_json":+ logger.warning("Failed to parse Ollama API response")+ return jsonify(+ {+ "available": False,+ "model": model_name,+ "message": "Invalid response from Ollama API",+ "error_type": "json_parse_error",+ }+ )+ if outcome == "connection_error":logger.warning("Connection error to Ollama API")return jsonify({@@ -594,8 +516,7 @@ def check_ollama_model():"error_details": "Unable to connect to the service. Please check if the service is running.",})- except requests.exceptions.Timeout:- # Timeout error+ if outcome == "timeout":logger.warning("Timeout connecting to Ollama API")return jsonify({@@ -606,6 +527,53 @@ def check_ollama_model():})+ # outcome == "ok"+ models = probe_result+ model_names = [m.get("name", "") for m in models]+ logger.debug(+ f"Available Ollama models: {', '.join(model_names[:10])}"+ + (+ f" and {len(model_names) - 10} more"+ if len(model_names) > 10+ else ""+ )+ )++ # Case-insensitive model name comparison+ model_exists = any(+ m.get("name", "").lower() == model_name.lower() for m in models+ )++ if model_exists:+ logger.info(f"Ollama model {model_name} is available")+ return jsonify(+ {+ "available": True,+ "model": model_name,+ "message": f"Model {model_name} is available",+ "all_models": model_names,+ }+ )+ # Check if models were found at all+ if not models:+ logger.warning("No models found in Ollama")+ message = "No models found in Ollama. Please pull models first."+ else:+ logger.warning(+ f"Model {model_name} not found among {len(models)} available models"+ )+ # Don't expose available models for security reasons+ message = f"Model {model_name} is not available"++ return jsonify(+ {+ "available": False,+ "model": model_name,+ "message": message,+ # Remove all_models to prevent information disclosure+ }+ )+except Exception:# General exceptionlogger.exception("Error checking Ollama model")diff --git a/tests/web/routes/test_api_routes_coverage.py b/tests/web/routes/test_api_routes_coverage.pyindex 16a9b5d2e6..1db771d7dc 100644--- a/tests/web/routes/test_api_routes_coverage.py+++ b/tests/web/routes/test_api_routes_coverage.py@@ -579,3 +579,70 @@ class TestCheckOllamaModelEdgeCases:data = resp.get_json()assert data["available"] is Falseassert data["error_type"] == "exception"+++class TestProbeOllamaTags:+ """Direct tests for the shared _probe_ollama_tags helper — the single+ source the status and model-availability checks both consume, so an+ 'is Ollama up?' answer can no longer drift between them."""++ def _probe(self, base_url="http://localhost:11434"):+ from local_deep_research.web.routes.api_routes import (+ _probe_ollama_tags,+ )++ return _probe_ollama_tags(base_url)++ def test_ok_new_format(self):+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = {"models": [{"name": "llama3"}]}+ with patch(f"{MODULE}.safe_get", return_value=resp):+ outcome, payload = self._probe()+ assert outcome == "ok"+ assert payload == [{"name": "llama3"}]++ def test_ok_old_format(self):+ resp = MagicMock()+ resp.status_code = 200+ resp.json.return_value = [{"name": "a"}, {"name": "b"}]+ with patch(f"{MODULE}.safe_get", return_value=resp):+ outcome, payload = self._probe()+ assert outcome == "ok"+ assert len(payload) == 2++ def test_bad_status_returns_status_code(self):+ resp = MagicMock()+ resp.status_code = 503+ with patch(f"{MODULE}.safe_get", return_value=resp):+ outcome, payload = self._probe()+ assert outcome == "bad_status"+ assert payload == 503++ def test_invalid_json(self):+ resp = MagicMock()+ resp.status_code = 200+ resp.json.side_effect = ValueError("bad")+ with patch(f"{MODULE}.safe_get", return_value=resp):+ outcome, payload = self._probe()+ assert outcome == "invalid_json"+ assert payload is None++ def test_connection_error(self):+ import requests++ with patch(+ f"{MODULE}.safe_get",+ side_effect=requests.exceptions.ConnectionError(),+ ):+ outcome, payload = self._probe()+ assert outcome == "connection_error"++ def test_timeout(self):+ import requests++ with patch(+ f"{MODULE}.safe_get", side_effect=requests.exceptions.Timeout()+ ):+ outcome, payload = self._probe()+ assert outcome == "timeout"