~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
fix(llm): cloud Anthropic model dropdown empty — list models via anthropic SDK (#4586)
LearningCircuit84a6c20b54df
diff --git a/changelog.d/4586.bugfix.md b/changelog.d/4586.bugfix.mdnew file mode 100644index 0000000000..25ceee20c7--- /dev/null+++ b/changelog.d/4586.bugfix.md@@ -0,0 +1 @@+**The cloud Anthropic model dropdown was empty.** The model-list route fetched Claude models correctly, but the auto-discovered-provider pass that ran afterward re-listed them with the OpenAI SDK (`Authorization: Bearer`), which 401s against the Anthropic API (it requires `x-api-key`) and overwrote the good result with an empty list. `AnthropicProvider` now lists models via the `anthropic` SDK, so the dropdown populates again.diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.pyindex 1593aa1661..008a60d45f 100644--- a/src/local_deep_research/llm/providers/implementations/anthropic.py+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py@@ -7,6 +7,7 @@ from loguru import logger# the methods that use them so test patches at the source module# (`local_deep_research.config.thread_settings`) are picked up by the# function-local imports at call time.+from ..base import OPTIONAL_API_KEY_PLACEHOLDERfrom ..openai_base import OpenAICompatibleProviderfrom ....security.ssrf_validator import assert_base_url_safe@@ -130,3 +131,67 @@ class AnthropicProvider(OpenAICompatibleProvider):)return ChatAnthropic(**anthropic_params)++ @classmethod+ def list_models_for_api(cls, api_key=None, base_url=None):+ """List models via the anthropic SDK.++ Overrides the OpenAICompatibleProvider implementation, which uses the+ OpenAI SDK and cannot talk to an Anthropic endpoint — it sends+ ``Authorization: Bearer`` while Anthropic requires ``x-api-key``, so+ the inherited path returns []. Works for both the official cloud+ provider (``base_url`` None → the SDK's api.anthropic.com default) and+ the custom-endpoint subclass (``base_url`` from+ ``llm.anthropic_endpoint.url``, SSRF-guarded). Degrades to [] on any+ failure so model-listing never 500s.+ """+ try:+ # A URL-based (custom-endpoint) provider with no URL configured has+ # no endpoint to query — return [] rather than falling back to the+ # cloud default. ``url_setting`` is None for the cloud provider,+ # where the cloud default IS the intended target.+ if cls.url_setting and not base_url:+ return []++ # SSRF-guard an operator-configured base_url (custom-endpoint+ # subclass). The cloud provider has url_setting=None and base_url+ # None, so it skips this and uses the SDK's cloud default.+ if base_url and cls.url_setting:+ try:+ base_url = assert_base_url_safe(+ base_url, setting_key=cls.url_setting+ )+ except ValueError:+ logger.warning(+ f"{cls.provider_name} base_url failed SSRF "+ f"validation; check {cls.url_setting} config"+ )+ return []++ from anthropic import Anthropic++ # Pass the key explicitly (placeholder when keyless) so the SDK does+ # not read ANTHROPIC_API_KEY from the environment and ship a real+ # cloud key to a self-hosted endpoint.+ client = Anthropic(+ api_key=api_key or OPTIONAL_API_KEY_PLACEHOLDER,+ base_url=base_url or None,+ )++ logger.debug(f"Fetching models from {cls.provider_name}")+ models_response = client.models.list()++ models = []+ for model in models_response.data:+ model_id = getattr(model, "id", None)+ if model_id:+ label = getattr(model, "display_name", None) or model_id+ models.append({"value": model_id, "label": label})++ logger.info(f"Found {len(models)} models from {cls.provider_name}")+ return models++ except Exception:+ # Connection failures are expected when the endpoint isn't running.+ logger.warning(f"Could not list models from {cls.provider_name}")+ return []diff --git a/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.pyindex d92d451fa8..9c4ba39e15 100644--- a/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py+++ b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py@@ -10,8 +10,6 @@ from loguru import loggerfrom ....config.thread_settings import get_setting_from_snapshotfrom ....security.log_sanitizer import redact_secrets-from ....security.ssrf_validator import assert_base_url_safe-from ..base import OPTIONAL_API_KEY_PLACEHOLDERfrom .anthropic import AnthropicProvider@@ -85,71 +83,6 @@ class CustomAnthropicEndpointProvider(AnthropicProvider):return False- @classmethod- def list_models_for_api(cls, api_key=None, base_url=None):- """List models from an Anthropic-format endpoint via the anthropic SDK.-- The inherited (OpenAI-SDK) implementation cannot talk to an Anthropic- endpoint — it sends ``Authorization: Bearer`` while Anthropic expects- ``x-api-key`` — so this override uses the ``anthropic`` SDK pointed at- ``base_url``. SSRF-validated first; degrades to ``[]`` on any failure.-- Args:- api_key: Optional API key (a placeholder is used when keyless).- base_url: The endpoint base URL (from ``llm.anthropic_endpoint.url``).-- Returns:- List of ``{"value", "label"}`` model dicts.- """- try:- # A URL-based (custom-endpoint) provider with no URL configured has- # no endpoint to query — return [] rather than letting the anthropic- # SDK silently fall back to its cloud api.anthropic.com default,- # which the discovered-provider model-list loop would otherwise hit- # on every refresh. The ``cls.url_setting`` guard keeps this correct- # if the method is ever lifted to the cloud AnthropicProvider (whose- # url_setting is None → cloud default is the intended behavior).- if cls.url_setting and not base_url:- return []-- if base_url:- try:- base_url = assert_base_url_safe(- base_url, setting_key=cls.url_setting- )- except ValueError:- logger.warning(- f"{cls.provider_name} base_url failed SSRF "- f"validation; check {cls.url_setting} config"- )- return []-- from anthropic import Anthropic-- # Pass the key explicitly (placeholder when keyless) so the SDK- # does not read ANTHROPIC_API_KEY from the environment and ship a- # real cloud key to a self-hosted endpoint.- client = Anthropic(- api_key=api_key or OPTIONAL_API_KEY_PLACEHOLDER,- base_url=base_url or None,- )-- logger.debug(- f"Fetching models from {cls.provider_name} at {base_url}"- )- models_response = client.models.list()-- models = []- for model in models_response.data:- model_id = getattr(model, "id", None)- if model_id:- label = getattr(model, "display_name", None) or model_id- models.append({"value": model_id, "label": label})-- logger.info(f"Found {len(models)} models from {cls.provider_name}")- return models-- except Exception:- # Connection failures are expected when the endpoint isn't running.- logger.warning(f"Could not list models from {cls.provider_name}")- return []+ # list_models_for_api is inherited from AnthropicProvider, which lists+ # models via the anthropic SDK and honors cls.url_setting (SSRF-guarding+ # the configured base_url; returning [] when no URL is set).diff --git a/tests/llm_providers/implementations/test_anthropic_provider.py b/tests/llm_providers/implementations/test_anthropic_provider.pyindex 249e2a8404..9865fe6c7f 100644--- a/tests/llm_providers/implementations/test_anthropic_provider.py+++ b/tests/llm_providers/implementations/test_anthropic_provider.py@@ -238,3 +238,46 @@ class TestAnthropicIsAvailable:result = AnthropicProvider.is_available()assert result is False+++class TestAnthropicListModels:+ """The cloud provider lists models via the anthropic SDK, not the OpenAI+ SDK it would otherwise inherit from OpenAICompatibleProvider (which sends+ Bearer auth and 401s against the Anthropic API). This is the fix for the+ discovered-provider loop clobbering the cloud Anthropic model list."""++ def test_uses_anthropic_sdk_and_maps_models(self):+ fake_model = Mock(+ id="claude-3-5-sonnet", display_name="Claude 3.5 Sonnet"+ )+ fake_client = Mock()+ fake_client.models.list.return_value = Mock(data=[fake_model])+ with patch("anthropic.Anthropic", return_value=fake_client) as mk:+ models = AnthropicProvider.list_models_for_api(api_key="sk-test")+ assert models == [+ {"value": "claude-3-5-sonnet", "label": "Claude 3.5 Sonnet"}+ ]+ fake_client.models.list.assert_called_once()+ # Cloud provider (url_setting is None) -> SDK uses its cloud default.+ _, kwargs = mk.call_args+ assert kwargs.get("base_url") is None++ def test_cloud_no_base_url_does_not_short_circuit(self):+ """Unlike the custom-endpoint subclass, the cloud provider has+ url_setting=None, so a missing base_url must NOT return [] — it must+ query the cloud default."""+ fake_client = Mock()+ fake_client.models.list.return_value = Mock(data=[])+ with patch("anthropic.Anthropic", return_value=fake_client) as mk:+ AnthropicProvider.list_models_for_api(+ api_key="sk-test", base_url=None+ )+ mk.assert_called_once()++ def test_sdk_error_returns_empty(self):+ fake_client = Mock()+ fake_client.models.list.side_effect = RuntimeError("401 Unauthorized")+ with patch("anthropic.Anthropic", return_value=fake_client):+ assert (+ AnthropicProvider.list_models_for_api(api_key="sk-test") == []+ )diff --git a/tests/web/routes/test_settings_routes_deep_coverage2.py b/tests/web/routes/test_settings_routes_deep_coverage2.pyindex e5bc6d06b4..abd621417b 100644--- a/tests/web/routes/test_settings_routes_deep_coverage2.py+++ b/tests/web/routes/test_settings_routes_deep_coverage2.py@@ -948,11 +948,22 @@ class TestApiGetAvailableModelsAnthropic:"""api_get_available_models fetches Anthropic models when key is set."""def test_anthropic_key_triggers_model_fetch(self):- """When anthropic API key is configured, models are fetched."""+ """Anthropic (cloud) models flow through the auto-discovered-provider+ loop, which calls AnthropicProvider.list_models_for_api (anthropic+ SDK). The previous hardcoded route branch was removed once that method+ listed models correctly."""+ from local_deep_research.llm.providers.auto_discovery import (+ ProviderInfo,+ )+ from local_deep_research.llm.providers.implementations.anthropic import (+ AnthropicProvider,+ )+app = _create_test_app()mock_model = MagicMock()mock_model.id = "claude-3-opus-20240229"+ mock_model.display_name = "Claude 3 Opus"mock_models_resp = MagicMock()mock_models_resp.data = [mock_model]@@ -971,36 +982,41 @@ class TestApiGetAvailableModelsAnthropic:mock_session.query.return_value = mock_cache_querymock_session.query.return_value.delete.return_value = 0- with patch(- "local_deep_research.llm.providers.get_discovered_provider_options",- return_value=[],- ):- with patch(+ with (+ patch(+ "local_deep_research.llm.providers.get_discovered_provider_options",+ return_value=[],+ ),+ patch(f"{MODULE}._get_setting_from_session",side_effect=_setting_side_effect,- ):- with patch(f"{MODULE}.safe_get") as mock_safe_get:- mock_ollama_resp = MagicMock()- mock_ollama_resp.status_code = 200- mock_ollama_resp.text = '{"models": []}'- mock_ollama_resp.json.return_value = {"models": []}- mock_safe_get.return_value = mock_ollama_resp+ ),+ patch(f"{MODULE}._model_list_local_only", return_value=False),+ patch(f"{MODULE}.safe_get") as mock_safe_get,+ patch(+ "local_deep_research.llm.providers.discover_providers",+ return_value={"ANTHROPIC": ProviderInfo(AnthropicProvider)},+ ),+ patch(+ "anthropic.Anthropic", return_value=mock_anthropic_client+ ),+ ):+ mock_ollama_resp = MagicMock()+ mock_ollama_resp.status_code = 200+ mock_ollama_resp.text = '{"models": []}'+ mock_ollama_resp.json.return_value = {"models": []}+ mock_safe_get.return_value = mock_ollama_resp- with patch(- "local_deep_research.llm.providers.discover_providers",- return_value={},- ):- with patch(- "local_deep_research.web.routes.settings_routes.Anthropic",- return_value=mock_anthropic_client,- create=True,- ):- resp = client.get(- f"{SETTINGS_PREFIX}/api/available-models?force_refresh=true"- )+ resp = client.get(+ f"{SETTINGS_PREFIX}/api/available-models?force_refresh=true"+ )assert resp.status_code == 200data = resp.get_json()assert "providers" in data+ # The model fetched via the anthropic SDK made it into the response —+ # proving the discovered-provider loop now lists Anthropic correctly.+ assert "claude-3-opus-20240229" in str(data)+ mock_anthropic_client.models.list.assert_called_once()# ---------------------------------------------------------------------------