~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(llm): Anthropic-compatible (Messages API) custom endpoint provider (#4559) (#4581)
LearningCircuit6173d33cb929
diff --git a/README.md b/README.mdindex a6bf8ee0cc..e80d6e7909 100644--- a/README.md+++ b/README.md@@ -467,6 +467,10 @@ search(query="copyright fair use precedents", engine="openclaw")- Google (Gemini)- 100+ models via OpenRouter+### Custom Endpoints+- **OpenAI-Compatible Endpoint** — any service speaking the OpenAI chat-completions API (vLLM, llama.cpp, gateways)+- **Anthropic-Compatible Endpoint** — a self-hosted service speaking the Anthropic Messages API (`/v1/messages`); set `llm.anthropic_endpoint.url`+[Model Setup →](docs/env_configuration.md)### Upgrading from earlier versionsdiff --git a/changelog.d/4581.feature.md b/changelog.d/4581.feature.mdnew file mode 100644index 0000000000..cc4762b470--- /dev/null+++ b/changelog.d/4581.feature.md@@ -0,0 +1 @@+**New "Anthropic-Compatible Endpoint" LLM provider** for self-hosted services that speak the Anthropic Messages API (`/v1/messages`) rather than the OpenAI chat-completions format. Select it under Settings → LLM, set `llm.anthropic_endpoint.url` (and an optional `llm.anthropic_endpoint.api_key` — keyless gateways are supported), and LDR builds a `ChatAnthropic` client pointed at your endpoint. The base URL is SSRF-validated before any request, and a real `ANTHROPIC_API_KEY` in the environment is never sent to a self-hosted endpoint. The official cloud Anthropic provider is unchanged.diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 3cc3c83d25..f36bd570f1 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -684,6 +684,10 @@"label": "OpenAI-Compatible Endpoint (llama.cpp, vLLM, etc.)","value": "openai_endpoint"},+ {+ "label": "Anthropic-Compatible Endpoint (Messages API)",+ "value": "anthropic_endpoint"+ },{"label": "Google Gemini API","value": "google"@@ -727,6 +731,34 @@"value": "","visible": true},+ "llm.anthropic_endpoint.url": {+ "category": null,+ "description": "Base URL of a self-hosted service implementing the Anthropic Messages API (/v1/messages). The client appends the API path. Example: http://localhost:9090. Required when using the Anthropic-Compatible Endpoint provider.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Anthropic Endpoint Url",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "text",+ "value": "",+ "visible": true+ },+ "llm.anthropic_endpoint.api_key": {+ "category": "llm_general",+ "description": "Optional API key for your Anthropic-compatible endpoint. Leave blank for self-hosted servers that don't require authentication.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Anthropic Endpoint API Key",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "password",+ "value": "",+ "visible": true+ },"llm.openai.api_key": {"category": "llm_general","description": "Your OpenAI API key for GPT models. Get one at platform.openai.com. Required when using the OpenAI provider.",diff --git a/src/local_deep_research/llm/providers/auto_discovery.py b/src/local_deep_research/llm/providers/auto_discovery.pyindex 3c59885f12..febd2e475c 100644--- a/src/local_deep_research/llm/providers/auto_discovery.py+++ b/src/local_deep_research/llm/providers/auto_discovery.py@@ -129,6 +129,12 @@ class ProviderDiscovery:and issubclass(obj, BaseLLMProvider)and obj is not OpenAICompatibleProviderand obj is not BaseLLMProvider+ # Only register classes DEFINED in this module, not ones+ # merely imported into its namespace (e.g.+ # custom_anthropic_endpoint imports AnthropicProvider as+ # its base). Without this, the imported base would be+ # re-registered from every module that imports it.+ and obj.__module__ == module.__name__):# Found a provider classprovider_info = ProviderInfo(obj)diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.pyindex b9e8722bb3..1593aa1661 100644--- a/src/local_deep_research/llm/providers/implementations/anthropic.py+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py@@ -8,6 +8,7 @@ from loguru import logger# (`local_deep_research.config.thread_settings`) are picked up by the# function-local imports at call time.from ..openai_base import OpenAICompatibleProvider+from ....security.ssrf_validator import assert_base_url_safeclass AnthropicProvider(OpenAICompatibleProvider):@@ -24,7 +25,9 @@ class AnthropicProvider(OpenAICompatibleProvider):# Metadata for auto-discoveryprovider_key = "ANTHROPIC"company_name = "Anthropic"- is_cloud = True+ # Annotated so subclasses (e.g. the custom-endpoint provider, which may be+ # local or cloud) can set is_cloud = None without a type conflict.+ is_cloud: bool | None = True@classmethoddef create_llm(cls, model_name=None, temperature=0.7, **kwargs):@@ -46,8 +49,16 @@ class AnthropicProvider(OpenAICompatibleProvider):settings_snapshot = kwargs.get("settings_snapshot")# resolve_api_key raises ValueError when the required key is missing- # (preserves the legacy behavior with a unified error message).- api_key = cls.resolve_api_key(settings_snapshot)+ # (preserves the legacy behavior with a unified error message). When+ # api_key_optional is True (custom self-hosted endpoints), fall back+ # to the shared placeholder instead of raising — and pass it+ # explicitly so langchain_anthropic does not silently read a real+ # ANTHROPIC_API_KEY from the environment and ship it to the endpoint.+ api_key: str | None+ if cls.api_key_optional:+ api_key = cls.resolve_api_key_or_placeholder(settings_snapshot)+ else:+ api_key = cls.resolve_api_key(settings_snapshot)# Require an explicit model — no silent fallback to a hardcoded default.if not model_name or not model_name.strip():@@ -85,6 +96,34 @@ class AnthropicProvider(OpenAICompatibleProvider):except NoSettingsContextError:pass # Optional parameter+ # Operator-configurable base_url for self-hosted Anthropic-format+ # endpoints. No-op for the official cloud provider, whose url_setting+ # is None (so it always talks to api.anthropic.com via the SDK+ # default). Subclasses like CustomAnthropicEndpointProvider set+ # url_setting to opt in.+ if cls.url_setting:+ from ....config.thread_settings import get_setting_from_snapshot++ custom_url = get_setting_from_snapshot(+ cls.url_setting,+ default=None,+ settings_snapshot=settings_snapshot,+ )+ custom_url = str(custom_url).strip() if custom_url else ""+ if not custom_url:+ # No silent fallback to the cloud endpoint — a custom-endpoint+ # provider with no URL is a misconfiguration, not a default.+ raise ValueError(+ f"{cls.provider_name} requires a base URL. "+ f"Please set {cls.url_setting} in settings."+ )+ # SSRF guard before constructing the client. Cloud-metadata IPs+ # stay blocked even under the permissive localhost/private-IP+ # posture that legitimate self-hosted endpoints rely on.+ anthropic_params["base_url"] = assert_base_url_safe(+ custom_url, setting_key=cls.url_setting+ )+logger.info(f"Creating {cls.provider_name} LLM with model: {model_name}, "f"temperature: {temperature}"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.pynew file mode 100644index 0000000000..d92d451fa8--- /dev/null+++ b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py@@ -0,0 +1,155 @@+"""Custom Anthropic-compatible (Messages API) endpoint provider.++Connects to a self-hosted LLM service that speaks the Anthropic Messages API+(``/v1/messages``) rather than the OpenAI chat-completions format. Mirrors+``CustomOpenAIEndpointProvider`` but builds a ``ChatAnthropic`` client (via the+parent ``AnthropicProvider``) pointed at an operator-configured ``base_url``.+"""++from loguru import logger++from ....config.thread_settings import get_setting_from_snapshot+from ....security.log_sanitizer import redact_secrets+from ....security.ssrf_validator import assert_base_url_safe+from ..base import OPTIONAL_API_KEY_PLACEHOLDER+from .anthropic import AnthropicProvider+++class CustomAnthropicEndpointProvider(AnthropicProvider):+ """Custom Anthropic-format endpoint provider.++ Lets users connect to any service implementing the Anthropic Messages API+ by specifying a base URL in settings. The URL is SSRF-validated and passed+ to ``ChatAnthropic`` by the inherited ``create_llm`` (which activates its+ URL/keyless branch because ``url_setting`` is set here).+ """++ provider_name = "Anthropic-Compatible Endpoint"+ api_key_setting = "llm.anthropic_endpoint.api_key"+ # Many self-hosted Anthropic-format gateways don't require auth; fall back+ # to the shared placeholder instead of raising at construction time.+ api_key_optional = True+ url_setting = "llm.anthropic_endpoint.url" # type: ignore[assignment]++ # Metadata for auto-discovery (registered as the "anthropic_endpoint"+ # provider string). The egress policy classifies it generically via+ # ``llm.anthropic_endpoint.url`` — keep the setting name in sync.+ provider_key = "ANTHROPIC_ENDPOINT"+ company_name = "Anthropic-Compatible"+ is_cloud = None # Unknown — could be local or cloud++ @classmethod+ def requires_auth_for_models(cls):+ """Self-hosted Anthropic-format endpoints may allow keyless listing.++ Return False so model listing is attempted without an API key. If the+ endpoint requires auth, the Anthropic client raises and we degrade to+ an empty list.+ """+ return False++ @classmethod+ def is_available(cls, settings_snapshot=None):+ """Available when either an API key or a custom URL is configured.++ Unlike the cloud Anthropic provider, this custom endpoint supports+ keyless local servers — so a configured URL alone makes it usable.+ """+ api_key = None+ try:+ api_key = get_setting_from_snapshot(+ cls.api_key_setting,+ default=None,+ settings_snapshot=settings_snapshot,+ )+ if api_key and str(api_key).strip():+ return True+ except Exception as e:+ # Redact in case a settings-layer error message embeds the key.+ safe_msg = redact_secrets(str(e), api_key)+ logger.debug(f"Error checking provider availability: {safe_msg}")++ try:+ custom_url = get_setting_from_snapshot(+ cls.url_setting,+ default=None,+ settings_snapshot=settings_snapshot,+ )+ if custom_url and str(custom_url).strip():+ return True+ except Exception:+ logger.debug(+ f"Error reading URL setting '{cls.url_setting}'",+ exc_info=True,+ )++ 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 []diff --git a/src/local_deep_research/web/static/js/components/context-overflow.js b/src/local_deep_research/web/static/js/components/context-overflow.jsindex 4958be0b13..628bddb9d7 100644--- a/src/local_deep_research/web/static/js/components/context-overflow.js+++ b/src/local_deep_research/web/static/js/components/context-overflow.js@@ -74,6 +74,7 @@if (!provider) return 'N/A';const providerMap = {'openai_endpoint': 'OpenAI Endpoint',+ 'anthropic_endpoint': 'Anthropic Endpoint','ollama': 'Ollama','openai': 'OpenAI','anthropic': 'Anthropic',diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 72c19f9674..a4e8cdff08 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -16,6 +16,8 @@let modelProviderSelect = null;let customEndpointInput = null;let endpointContainer = null;+ let anthropicEndpointUrlInput = null;+ let anthropicEndpointContainer = null;let ollamaUrlInput = null;let ollamaUrlContainer = null;let lmstudioUrlInput = null;@@ -37,6 +39,8 @@let ionosApiKeyContainer = null;let openaiEndpointApiKeyInput = null;let openaiEndpointApiKeyContainer = null;+ let anthropicEndpointApiKeyInput = null;+ let anthropicEndpointApiKeyContainer = null;let ollamaApiKeyInput = null;let ollamaApiKeyContainer = null;let lmstudioApiKeyInput = null;@@ -254,6 +258,8 @@modelProviderSelect = document.getElementById('model_provider');customEndpointInput = document.getElementById('custom_endpoint');endpointContainer = document.getElementById('endpoint_container');+ anthropicEndpointUrlInput = document.getElementById('anthropic_endpoint_url');+ anthropicEndpointContainer = document.getElementById('anthropic_endpoint_container');ollamaUrlInput = document.getElementById('ollama_url');ollamaUrlContainer = document.getElementById('ollama_url_container');lmstudioUrlInput = document.getElementById('lmstudio_url');@@ -276,6 +282,8 @@ionosApiKeyContainer = document.getElementById('ionos_api_key_container');openaiEndpointApiKeyInput = document.getElementById('openai_endpoint_api_key');openaiEndpointApiKeyContainer = document.getElementById('openai_endpoint_api_key_container');+ anthropicEndpointApiKeyInput = document.getElementById('anthropic_endpoint_api_key');+ anthropicEndpointApiKeyContainer = document.getElementById('anthropic_endpoint_api_key_container');ollamaApiKeyInput = document.getElementById('ollama_api_key');ollamaApiKeyContainer = document.getElementById('ollama_api_key_container');lmstudioApiKeyInput = document.getElementById('lmstudio_api_key');@@ -748,6 +756,11 @@endpointContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ // Show Anthropic endpoint input if Anthropic endpoint is selected+ if (anthropicEndpointContainer) {+ anthropicEndpointContainer.style.display = provider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }+// Show Ollama URL input if Ollama is selectedif (ollamaUrlContainer) {ollamaUrlContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';@@ -785,6 +798,9 @@if (openaiEndpointApiKeyContainer) {openaiEndpointApiKeyContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ if (anthropicEndpointApiKeyContainer) {+ anthropicEndpointApiKeyContainer.style.display = provider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }if (ollamaApiKeyContainer) {ollamaApiKeyContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';}@@ -935,6 +951,18 @@saveSearchSetting('llm.openai_endpoint.api_key', this.value);});}+ if (anthropicEndpointUrlInput) {+ anthropicEndpointUrlInput.addEventListener('change', function() {+ const url = this.value;+ SafeLogger.log('Anthropic endpoint URL changed to:', url);+ saveSearchSetting('llm.anthropic_endpoint.url', url);+ });+ }+ if (anthropicEndpointApiKeyInput) {+ anthropicEndpointApiKeyInput.addEventListener('change', function() {+ saveSearchSetting('llm.anthropic_endpoint.api_key', this.value);+ });+ }if (ollamaApiKeyInput) {ollamaApiKeyInput.addEventListener('change', function() {saveSearchSetting('llm.ollama.api_key', this.value);@@ -1029,6 +1057,12 @@SafeLogger.warn('Endpoint container not found');}+ // Show Anthropic endpoint input if Anthropic endpoint is selected+ if (anthropicEndpointContainer) {+ const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();+ anthropicEndpointContainer.style.display = selectedProvider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }+// Show Ollama URL input if Ollama is selectedif (ollamaUrlContainer) {const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();@@ -1070,6 +1104,9 @@if (openaiEndpointApiKeyContainer) {openaiEndpointApiKeyContainer.style.display = selectedProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ if (anthropicEndpointApiKeyContainer) {+ anthropicEndpointApiKeyContainer.style.display = selectedProvider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }if (ollamaApiKeyContainer) {ollamaApiKeyContainer.style.display = selectedProvider === 'OLLAMA' ? 'block' : 'none';}@@ -1398,6 +1435,7 @@const providerSetting = data.settings["llm.provider"];const modelSetting = data.settings["llm.model"];const customEndpointUrlSetting = data.settings["llm.openai_endpoint.url"];+ const anthropicEndpointUrlSetting = data.settings["llm.anthropic_endpoint.url"];// Update provider dropdown if we have a valid providerif (providerSetting && modelProviderSelect) {@@ -1438,6 +1476,12 @@providerValue === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ // Display Anthropic endpoint container if using Anthropic endpoint+ if (anthropicEndpointContainer) {+ anthropicEndpointContainer.style.display =+ providerValue === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }+// Display Ollama URL container if using Ollamaif (ollamaUrlContainer) {ollamaUrlContainer.style.display =@@ -1477,6 +1521,9 @@if (openaiEndpointApiKeyContainer) {openaiEndpointApiKeyContainer.style.display = providerValue === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ if (anthropicEndpointApiKeyContainer) {+ anthropicEndpointApiKeyContainer.style.display = providerValue === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }if (ollamaApiKeyContainer) {ollamaApiKeyContainer.style.display = providerValue === 'OLLAMA' ? 'block' : 'none';}@@ -1493,6 +1540,14 @@customEndpointInput.disabled = !customEndpointUrlSetting.editable;}+ // Update the Anthropic endpoint URL if we have one.+ if (anthropicEndpointUrlSetting && anthropicEndpointUrlInput) {+ const anthropicEndpointUrlValue = anthropicEndpointUrlSetting.value;+ SafeLogger.log('Current Anthropic endpoint URL:', anthropicEndpointUrlValue);+ anthropicEndpointUrlInput.value = anthropicEndpointUrlValue;+ anthropicEndpointUrlInput.disabled = !anthropicEndpointUrlSetting.editable;+ }+// Update the Ollama URL if we have oneconst ollamaUrlSetting = data.settings['llm.ollama.url'];if (ollamaUrlSetting && ollamaUrlInput) {@@ -1561,6 +1616,12 @@openaiEndpointApiKeyInput.disabled = !openaiEndpointApiKeySetting.editable;}+ const anthropicEndpointApiKeySetting = data.settings['llm.anthropic_endpoint.api_key'];+ if (anthropicEndpointApiKeySetting && anthropicEndpointApiKeyInput) {+ anthropicEndpointApiKeyInput.value = anthropicEndpointApiKeySetting.value || '';+ anthropicEndpointApiKeyInput.disabled = !anthropicEndpointApiKeySetting.editable;+ }+const ollamaApiKeySetting = data.settings['llm.ollama.api_key'];if (ollamaApiKeySetting && ollamaApiKeyInput) {ollamaApiKeyInput.value = ollamaApiKeySetting.value || '';@@ -1748,6 +1809,11 @@endpointContainer.style.display =provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ // Show/hide Anthropic endpoint input if needed+ if (anthropicEndpointContainer) {+ anthropicEndpointContainer.style.display =+ provider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }// Show/hide Ollama URL input if neededif (ollamaUrlContainer) {ollamaUrlContainer.style.display =@@ -1784,6 +1850,9 @@if (openaiEndpointApiKeyContainer) {openaiEndpointApiKeyContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';}+ if (anthropicEndpointApiKeyContainer) {+ anthropicEndpointApiKeyContainer.style.display = provider === 'ANTHROPIC_ENDPOINT' ? 'block' : 'none';+ }if (ollamaApiKeyContainer) {ollamaApiKeyContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';}diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 40b0282249..dc37650780 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -4542,6 +4542,7 @@{ value: 'OPENAI', label: 'OpenAI (Cloud)' },{ value: 'ANTHROPIC', label: 'Anthropic (Cloud)' },{ value: 'OPENAI_ENDPOINT', label: 'OpenAI-Compatible Endpoint (llama.cpp, vLLM, etc.)' },+ { value: 'ANTHROPIC_ENDPOINT', label: 'Anthropic-Compatible Endpoint (Messages API)' },{ value: 'LMSTUDIO', label: 'LM Studio (Local)' },{ value: 'LLAMACPP', label: 'Llama.cpp (Local GGUF files only)' }];diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex d548314b01..ffa457b76e 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -168,6 +168,13 @@<span class="ldr-input-help">Enter the OpenAI-compatible API endpoint URL</span></div>+ <!-- Anthropic-Compatible Endpoint (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="anthropic_endpoint_container" style="display: none;">+ <label for="anthropic_endpoint_url">{{ tooltip("Anthropic-Compatible Endpoint", "Anthropic Messages API URL (e.g., https://your-anthropic-endpoint/v1). Used for self-hosted or alternative Anthropic-compatible API providers.") }}</label>+ <input type="text" id="anthropic_endpoint_url" name="anthropic_endpoint_url" class="ldr-form-control" placeholder="https://your-anthropic-endpoint/v1" value="{{ settings.llm_anthropic_endpoint_url }}">+ <span class="ldr-input-help">Enter the Anthropic Messages API endpoint URL</span>+ </div>+<!-- Ollama URL (hidden by default) --><div class="ldr-form-group ldr-half" id="ollama_url_container" style="display: none;"><label for="ollama_url">{{ tooltip("Ollama Endpoint", "Where Ollama is running. Default localhost:11434. If connection fails, check that Ollama is installed and running (ollama serve).") }}</label>@@ -245,6 +252,14 @@<span class="ldr-input-help">Leave blank for local servers (llama.cpp, vLLM, LM Studio). Required only for hosted services (OpenRouter, Groq, Together, etc.).</span></div>+ <!-- Anthropic Endpoint API Key (hidden by default) -->+ <div class="ldr-form-group ldr-half" id="anthropic_endpoint_api_key_container" style="display: none;">+ <label for="anthropic_endpoint_api_key">Endpoint API Key (Optional)</label>+ <input type="password" id="anthropic_endpoint_api_key" name="anthropic_endpoint_api_key" class="ldr-form-control"+ placeholder="Optional, leave empty if not required" autocomplete="off">+ <span class="ldr-input-help">Leave blank for keyless local Anthropic-compatible servers.</span>+ </div>+<!-- Ollama API Key (hidden by default, optional for authenticated instances) --><div class="ldr-form-group ldr-half" id="ollama_api_key_container" style="display: none;"><label for="ollama_api_key">Ollama API Key (Optional)</label>diff --git a/tests/llm/test_provider_base_url_ssrf.py b/tests/llm/test_provider_base_url_ssrf.pyindex 001fbe97f0..6bea532ace 100644--- a/tests/llm/test_provider_base_url_ssrf.py+++ b/tests/llm/test_provider_base_url_ssrf.py@@ -436,3 +436,64 @@ class TestPublicApi:from local_deep_research.security import redact_url_for_logassert callable(redact_url_for_log)+++class TestCustomAnthropicEndpointSsrf:+ """CustomAnthropicEndpointProvider gates its operator-configured+ base_url (``llm.anthropic_endpoint.url``) through the SSRF guard in the+ inherited AnthropicProvider.create_llm, and in list_models_for_api. The+ SDK is ChatAnthropic / the anthropic SDK, both of which use their own+ httpx client that bypasses safe_requests — so the guard is load-bearing."""++ def test_create_llm_rejects_aws_metadata(self):+ from local_deep_research.llm.providers.implementations.custom_anthropic_endpoint import (+ CustomAnthropicEndpointProvider,+ )++ snapshot = {"llm.anthropic_endpoint.url": "http://169.254.169.254/"}+ with pytest.raises(ValueError, match="failed SSRF validation"):+ CustomAnthropicEndpointProvider.create_llm(+ model_name="claude-3-5-sonnet", settings_snapshot=snapshot+ )++ def test_create_llm_validate_runs_before_chatanthropic_constructor(+ self, monkeypatch+ ):+ """Make assert_base_url_safe raise; ChatAnthropic must never be+ instantiated. Both names are bound in anthropic.py (the parent's+ create_llm), so patch them there."""+ from local_deep_research.llm.providers.implementations.custom_anthropic_endpoint import (+ CustomAnthropicEndpointProvider,+ )++ mock_ctor = MagicMock(return_value=Mock())+ monkeypatch.setattr(+ "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic",+ mock_ctor,+ )+ monkeypatch.setattr(+ "local_deep_research.llm.providers.implementations.anthropic.assert_base_url_safe",+ Mock(side_effect=ValueError("simulated SSRF rejection")),+ )++ with pytest.raises(ValueError):+ CustomAnthropicEndpointProvider.create_llm(+ model_name="claude-3-5-sonnet",+ settings_snapshot={+ "llm.anthropic_endpoint.url": "http://example.com/"+ },+ )+ assert mock_ctor.call_count == 0, (+ "ChatAnthropic was instantiated despite SSRF guard raising — "+ "ordering regression"+ )++ def test_list_models_for_api_returns_empty_on_metadata_url(self):+ from local_deep_research.llm.providers.implementations.custom_anthropic_endpoint import (+ CustomAnthropicEndpointProvider,+ )++ result = CustomAnthropicEndpointProvider.list_models_for_api(+ api_key="test", base_url="http://169.254.169.254/"+ )+ assert result == []diff --git a/tests/llm_providers/test_custom_anthropic_endpoint_high_value.py b/tests/llm_providers/test_custom_anthropic_endpoint_high_value.pynew file mode 100644index 0000000000..9624ff39e0--- /dev/null+++ b/tests/llm_providers/test_custom_anthropic_endpoint_high_value.py@@ -0,0 +1,183 @@+"""High-value tests for the custom Anthropic-compatible endpoint provider.++Covers the URL-based is_available logic, create_llm base_url passthrough ++keyless/empty-URL handling, env-key-leak prevention, model listing via the+anthropic SDK, and class metadata. Mirrors test_custom_openai_high_value.py.+"""++from unittest.mock import Mock, patch++import pytest++from local_deep_research.llm.providers.base import OPTIONAL_API_KEY_PLACEHOLDER+from local_deep_research.llm.providers.implementations.anthropic import (+ AnthropicProvider,+)+from local_deep_research.llm.providers.implementations.custom_anthropic_endpoint import (+ CustomAnthropicEndpointProvider as P,+)++ANTHRO_MOD = "local_deep_research.llm.providers.implementations.custom_anthropic_endpoint"+GET_SETTING = f"{ANTHRO_MOD}.get_setting_from_snapshot"+# create_llm (inherited from AnthropicProvider) binds ChatAnthropic in anthropic.py+CHAT = (+ "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"+)++URL_KEY = "llm.anthropic_endpoint.url"+KEY_KEY = "llm.anthropic_endpoint.api_key"+++class TestCustomAnthropicIsAvailable:+ """is_available is True when either an API key OR a URL is configured."""++ def test_available_with_api_key_only(self):+ def side_effect(key, default=None, **kwargs):+ if key == KEY_KEY:+ return "my-key"+ return default++ with patch(GET_SETTING, side_effect=side_effect):+ assert P.is_available() is True++ def test_available_with_url_only(self):+ def side_effect(key, default=None, **kwargs):+ if key == URL_KEY:+ return "http://localhost:9090"+ return default++ with patch(GET_SETTING, side_effect=side_effect):+ assert P.is_available() is True++ def test_not_available_with_neither(self):+ with patch(GET_SETTING, return_value=None):+ assert P.is_available() is False++ def test_whitespace_key_and_url_not_available(self):+ def side_effect(key, default=None, **kwargs):+ return " "++ with patch(GET_SETTING, side_effect=side_effect):+ assert P.is_available() is False++ def test_exception_in_api_key_check_falls_through_to_url(self):+ def side_effect(key, default=None, **kwargs):+ if key == KEY_KEY:+ raise RuntimeError("settings error")+ if key == URL_KEY:+ return "http://myserver:9090"+ return default++ with patch(GET_SETTING, side_effect=side_effect):+ assert P.is_available() is True++ def test_both_exceptions_return_false(self):+ with patch(GET_SETTING, side_effect=RuntimeError("boom")):+ assert P.is_available() is False+++class TestCustomAnthropicCreateLlm:+ """create_llm passes the configured URL as base_url and handles keys."""++ def test_custom_url_passed_as_base_url(self):+ snap = {URL_KEY: "http://localhost:9090", KEY_KEY: "k"}+ with patch(CHAT) as mock_ctor:+ mock_ctor.return_value = Mock()+ P.create_llm(model_name="claude-3-5-sonnet", settings_snapshot=snap)+ _, kwargs = mock_ctor.call_args+ assert kwargs["base_url"] == "http://localhost:9090"+ assert kwargs["anthropic_api_key"] == "k"++ def test_keyless_uses_placeholder(self):+ snap = {URL_KEY: "http://localhost:9090"}+ with patch(CHAT) as mock_ctor:+ mock_ctor.return_value = Mock()+ P.create_llm(model_name="claude-3-5-sonnet", settings_snapshot=snap)+ _, kwargs = mock_ctor.call_args+ assert kwargs["anthropic_api_key"] == OPTIONAL_API_KEY_PLACEHOLDER++ def test_empty_url_raises(self):+ with pytest.raises(ValueError, match="requires a base URL"):+ P.create_llm(model_name="claude-3", settings_snapshot={URL_KEY: ""})++ def test_empty_model_raises(self):+ with pytest.raises(ValueError, match="model not configured"):+ P.create_llm(+ model_name="",+ settings_snapshot={URL_KEY: "http://localhost:9090"},+ )++ def test_env_api_key_not_leaked_to_endpoint(self, monkeypatch):+ """A real ANTHROPIC_API_KEY in the env must NOT be sent to a+ self-hosted endpoint: the explicit placeholder kwarg wins."""+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-real-cloud-key")+ snap = {URL_KEY: "http://localhost:9090"} # no endpoint key configured+ with patch(CHAT) as mock_ctor:+ mock_ctor.return_value = Mock()+ P.create_llm(model_name="claude-3-5-sonnet", settings_snapshot=snap)+ _, kwargs = mock_ctor.call_args+ assert kwargs["anthropic_api_key"] == OPTIONAL_API_KEY_PLACEHOLDER+ assert kwargs["anthropic_api_key"] != "sk-real-cloud-key"+++class TestCustomAnthropicClassAttributes:+ def test_inherits_from_anthropic_provider(self):+ assert issubclass(P, AnthropicProvider)++ def test_provider_key(self):+ assert P.provider_key == "ANTHROPIC_ENDPOINT"++ def test_is_cloud_is_none(self):+ assert P.is_cloud is None++ def test_api_key_optional(self):+ assert P.api_key_optional is True++ def test_url_setting(self):+ assert P.url_setting == URL_KEY++ def test_requires_auth_for_models_false(self):+ assert P.requires_auth_for_models() is False+++class TestCustomAnthropicListModels:+ def test_list_models_success(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 = P.list_models_for_api(+ api_key="k", base_url="http://localhost:9090"+ )+ assert models == [+ {"value": "claude-3-5-sonnet", "label": "Claude 3.5 Sonnet"}+ ]+ mk.assert_called_once()++ def test_list_models_falls_back_to_id_label(self):+ fake_model = Mock(id="custom-model", display_name=None)+ fake_client = Mock()+ fake_client.models.list.return_value = Mock(data=[fake_model])+ with patch("anthropic.Anthropic", return_value=fake_client):+ models = P.list_models_for_api(base_url="http://localhost:9090")+ assert models == [{"value": "custom-model", "label": "custom-model"}]++ def test_list_models_ssrf_blocked_returns_empty(self):+ """A metadata-IP base_url is rejected and degrades to []."""+ assert P.list_models_for_api(base_url="http://169.254.169.254/") == []++ def test_list_models_no_base_url_returns_empty_without_calling_sdk(self):+ """With no URL configured there is no endpoint — return [] and never+ fall back to the anthropic SDK's cloud default."""+ with patch("anthropic.Anthropic") as mk:+ assert P.list_models_for_api(api_key="k", base_url=None) == []+ assert P.list_models_for_api(api_key="k", base_url="") == []+ mk.assert_not_called()++ def test_list_models_sdk_error_returns_empty(self):+ fake_client = Mock()+ fake_client.models.list.side_effect = RuntimeError("connection refused")+ with patch("anthropic.Anthropic", return_value=fake_client):+ assert P.list_models_for_api(base_url="http://localhost:9090") == []diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.pyindex 59f9937092..b9d02d772d 100644--- a/tests/security/test_egress_policy.py+++ b/tests/security/test_egress_policy.py@@ -1810,11 +1810,12 @@ def test_every_llm_provider_is_classified_by_egress_policy():_LOCAL_DEFAULT_LLM_PROVIDERS,)- # openai_endpoint is classified by its configured URL (not a static set).+ # openai_endpoint and anthropic_endpoint are classified by their configured+ # URL (llm.<provider>.url), not a static set.classified = (_CLOUD_LLM_PROVIDERS| _LOCAL_DEFAULT_LLM_PROVIDERS- | {"openai_endpoint"}+ | {"openai_endpoint", "anthropic_endpoint"})providers = discover_providers()assert providers, "no providers discovered — test wiring issue"diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex e8c9787acf..f5a10d00a7 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -1120,6 +1120,34 @@"value": "","visible": true},+ "llm.anthropic_endpoint.api_key": {+ "category": "llm_general",+ "description": "Optional API key for your Anthropic-compatible endpoint. Leave blank for self-hosted servers that don't require authentication.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Anthropic Endpoint API Key",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "password",+ "value": "",+ "visible": true+ },+ "llm.anthropic_endpoint.url": {+ "category": null,+ "description": "Base URL of a self-hosted service implementing the Anthropic Messages API (/v1/messages). The client appends the API path. Example: http://localhost:9090. Required when using the Anthropic-Compatible Endpoint provider.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Anthropic Endpoint Url",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "text",+ "value": "",+ "visible": true+ },"llm.context_window_size": {"category": "llm_parameters","description": "Maximum context window size in tokens for cloud LLMs. Only used when unrestricted context is disabled.",@@ -1461,6 +1489,10 @@"label": "OpenAI-Compatible Endpoint (llama.cpp, vLLM, etc.)","value": "openai_endpoint"},+ {+ "label": "Anthropic-Compatible Endpoint (Messages API)",+ "value": "anthropic_endpoint"+ },{"label": "Google Gemini API","value": "google"diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.pyindex c565418408..b37ce0d567 100644--- a/tests/settings/test_settings_defaults_integrity.py+++ b/tests/settings/test_settings_defaults_integrity.py@@ -228,6 +228,7 @@ def _is_dynamic_setting(key: str) -> bool:"llm.ollama.","llm.lmstudio.","llm.openai_endpoint.",+ "llm.anthropic_endpoint.","llm.deepseek.",# News subsystem: many settings consumed by JS frontend or# batch-loaded by news scheduler