Skip to content

~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.

refactor(llm-providers): collapse dual-path LLM construction; fix Ollama enable_thinking (#3984)

LearningCircuit564f228ee837
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 4e19f8f7c5..d7d1bc7e57 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -265,8 +265,14 @@ regexes = [
# Allow api_key type hints and docstrings
'''api_key:\s*Optional''',
'''api_key\s*=\s*None''',
- # Allow placeholder API key for local servers without auth
+ # Allow placeholder API keys for local servers without auth.
+ # "not-required" is the unified placeholder (providers/base.py
+ # OPTIONAL_API_KEY_PLACEHOLDER). The other strings are kept for
+ # backward compat with any third-party provider classes that haven't
+ # migrated to the constant yet.
+ '''api_key\s*=\s*"not-required"''',
'''api_key\s*=\s*"not-needed"''',
+ '''api_key\s*=\s*"lm-studio"''',
# Allow research_id, user_password in notification flow docs (example code)
'''research_id,\s*user_password''',
# Allow CSRF token patterns in HTML templates
diff --git a/changelog.d/3984.bugfix.md b/changelog.d/3984.bugfix.md
new file mode 100644
index 0000000000..1117a32143
--- /dev/null
+++ b/changelog.d/3984.bugfix.md
@@ -0,0 +1,34 @@
+Fix Ollama `enable_thinking` setting being silently dropped on the live class
+construction path. Reasoning models (deepseek-r1, qwen2.5) now correctly
+receive `reasoning=True/False` per the user's `llm.ollama.enable_thinking`
+setting. Also apply the 80%-of-context-window `max_tokens` cap on every
+provider's `create_llm` (was previously only applied in dead procedural
+code that never ran in production) and unify the optional-API-key
+placeholder string across all providers (`"not-required"`). Note: users
+who set `llm.context_window_unrestricted = false` together with a small
+`llm.context_window_size` will now have `max_tokens` capped at 80% of
+that window for OpenAI/Anthropic too — previously the cap only applied
+to Ollama. For LM Studio and llama.cpp the cap is always active, keyed
+to `llm.local_context_window_size` (default 20480 → effective cap 16384
+with the default `llm.max_tokens` of 30000). `llm.supports_max_tokens =
+false` is now honored on the live path (previously the kwarg was sent
+regardless), and whitespace-only API keys for required-key providers now
+raise a clear error at construction instead of being sent to the API.
+
+Ollama's `num_ctx` now resolves through the same shared helper as the
+context-overflow bookkeeping, so the reported `context_limit` always
+matches the window the model actually runs with (previously an absent or
+null `llm.local_context_window_size` produced `num_ctx` 4096/server-default
+while overflow detection assumed 8192). The ineffective `max_tokens`
+kwarg is no longer passed to `ChatOllama` (it was silently ignored;
+`num_ctx` is the effective control). A keyless `openai_endpoint`
+configuration is now permitted — it previously raised "API key not
+configured" at construction, blocking keyless local servers (vLLM,
+text-generation-webui); a warning is logged so endpoints that do
+require a key remain diagnosable.
+
+Also fix `llama.cpp` provider availability check: instances behind an
+authentication proxy now correctly report as available when
+`llm.llamacpp.api_key` is configured. Previously the probe was sent
+without credentials and was always rejected, so users with auth-proxied
+llama-server saw the provider as unavailable regardless of server state.
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 2a7d8049ba..f0436041bb 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -388,12 +388,13 @@ class BaseSearchStrategy(ABC):
### LLM Provider Interface
-All providers extend `OpenAICompatibleProvider`:
+All providers extend `BaseLLMProvider` (most extend `OpenAICompatibleProvider`):
```python
-class OpenAICompatibleProvider:
+class OpenAICompatibleProvider(BaseLLMProvider):
provider_name: str
- api_key_setting: str
+ api_key_setting: str | None # Settings key, or None for no-key providers
+ api_key_optional: bool = False # If True, missing key uses placeholder
url_setting: str
default_base_url: str
default_model: str
diff --git a/docs/developing/EXTENDING.md b/docs/developing/EXTENDING.md
index 5de319ef76..ad3ab743fb 100644
--- a/docs/developing/EXTENDING.md
+++ b/docs/developing/EXTENDING.md
@@ -497,12 +497,12 @@ Create in `src/local_deep_research/llm/providers/implementations/`:
```python
# my_provider.py
-from typing import Any, Dict, Optional
+from typing import Dict, Optional
from langchain_core.language_models import BaseChatModel
from langchain_openai import ChatOpenAI
-from ..openai_compatible import OpenAICompatibleProvider
+from ..openai_base import OpenAICompatibleProvider
class MyProvider(OpenAICompatibleProvider):
@@ -513,6 +513,9 @@ class MyProvider(OpenAICompatibleProvider):
url_setting = "llm.my_provider.url"
default_base_url = "https://api.myprovider.com/v1"
default_model = "my-model-v1"
+ # Optional: set to True if missing key should fall back to a placeholder
+ # rather than raising ValueError.
+ api_key_optional = False
@classmethod
def create_llm(
@@ -534,16 +537,18 @@ class MyProvider(OpenAICompatibleProvider):
Returns:
LangChain chat model instance
"""
- settings_snapshot = settings_snapshot or {}
+ from ....config.thread_settings import get_setting_from_snapshot
- # Get API key from settings
- api_key = cls._get_setting(settings_snapshot, cls.api_key_setting)
- if not api_key:
- raise ValueError(f"API key not found in {cls.api_key_setting}")
+ # Resolve API key via the base helper. Raises ValueError when
+ # required and missing, returns the unified placeholder when
+ # api_key_optional=True and the key is unset.
+ api_key = cls.resolve_api_key_or_placeholder(settings_snapshot)
# Get base URL
- base_url = cls._get_setting(
- settings_snapshot, cls.url_setting, cls.default_base_url
+ base_url = get_setting_from_snapshot(
+ cls.url_setting,
+ cls.default_base_url,
+ settings_snapshot=settings_snapshot,
)
return ChatOpenAI(
@@ -562,7 +567,17 @@ class MyProvider(OpenAICompatibleProvider):
### Register in Auto-Discovery
-Add to `auto_discovery.py`:
+Drop the provider class file into
+`src/local_deep_research/llm/providers/implementations/`. Auto-discovery
+will scan that directory at import time and register every class whose
+name ends with `Provider`, subclasses `BaseLLMProvider`, and has
+`provider_name` set to a real value (i.e., overridden away from the
+``"unknown"`` default). Setting `provider_name = "unknown"` — or leaving
+it unset on the class — will cause the class to be **silently filtered
+out** of auto-discovery, which is a common gotcha when copying an
+existing provider as a template.
+
+Optional cloud-metadata registration in `auto_discovery.py`:
```python
PROVIDER_METADATA = {
@@ -625,6 +640,22 @@ register_llm("my_factory", create_my_llm)
llm = get_llm_from_registry("my_factory")
```
+### Registry caveat
+
+The built-in providers (ollama, openai, anthropic, ...) live in the same
+registry, auto-registered at import time. `clear_llm_registry()` removes
+them too, and `get_llm()` has no other construction path — every provider
+will raise "was not registered by auto-discovery" until you restore them:
+
+```python
+from local_deep_research.llm.providers import discover_providers
+
+discover_providers(force_refresh=True)
+```
+
+Prefer `unregister_llm("<your name>")` over `clear_llm_registry()` to
+remove only your own registrations.
+
---
## See Also
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 0fbefced80..7e4c8c9c9d 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -1,33 +1,20 @@
from functools import cache
from typing import Any
-from langchain_anthropic import ChatAnthropic
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import AIMessage
-from langchain_ollama import ChatOllama
-from langchain_openai import ChatOpenAI
from loguru import logger
from ..llm import get_llm_from_registry, is_llm_registered
from ..utilities.search_utilities import remove_think_tags
-from ..utilities.url_utils import normalize_url
-from .constants import (
- DEFAULT_LLAMACPP_URL,
- DEFAULT_LMSTUDIO_URL,
- DEFAULT_OLLAMA_URL,
-)
-
-# Import providers module to trigger auto-discovery
-try:
- from ..llm.providers import discover_providers # noqa: F401
- # Auto-discovery happens on module import
-except ImportError:
- logger.debug("Providers module not available yet")
+
+# Import providers module to trigger auto-discovery. get_llm() has no
+# fallback construction path: if this import fails (e.g. a broken
+# langchain install), the module must fail loudly here rather than start
+# with an empty registry and confusing per-call errors.
+from ..llm.providers import discover_providers # noqa: F401
from ..llm.providers.base import normalize_provider
-from .thread_settings import (
- get_setting_from_snapshot,
- NoSettingsContextError,
-)
+from .thread_settings import get_setting_from_snapshot
# Valid provider options
VALID_PROVIDERS = [
@@ -207,6 +194,12 @@ def _get_context_window_for_provider(provider_type, settings_snapshot=None):
Local providers (ollama, llamacpp, lmstudio) use a smaller default to prevent
memory issues. Cloud providers check if unrestricted mode is enabled.
+ NOTE: This is a near-duplicate of providers/_helpers.get_context_window_for_provider.
+ Both copies are intentionally kept (rather than aliased): consolidating here
+ breaks ~17 tests that patch ``llm_config.get_setting_from_snapshot`` directly,
+ while the helpers module uses a function-local import. Until those tests
+ migrate to patching the source module, the duplicate is the cheaper option.
+
Returns:
int or None: The context window size, or None for unrestricted cloud providers.
"""
@@ -253,8 +246,13 @@ def get_llm(
model_name: Name of the model to use (if None, uses database setting)
temperature: Model temperature (if None, uses database setting)
provider: Provider to use (if None, uses database setting)
- openai_endpoint_url: Custom endpoint URL to use (if None, uses database
- setting)
+ openai_endpoint_url: NON-FUNCTIONAL, kept for API compatibility.
+ The endpoint URL is read exclusively from the
+ ``llm.openai_endpoint.url`` setting by
+ CustomOpenAIEndpointProvider. This parameter was already
+ ignored before the procedural-chain removal (the registry
+ dispatch never consumed it); honoring or removing it is
+ tracked as a follow-up.
research_id: Optional research ID for token tracking
research_context: Optional research context for enhanced token tracking
@@ -433,16 +431,13 @@ def get_llm(
f"Getting LLM with model: {model_name}, temperature: {temperature}, provider: {provider}"
)
- # Common parameters for all models
- common_params = {
- "temperature": temperature,
- }
-
+ # Set context_limit on research_context for overflow detection. The
+ # actual max_tokens calculation lives in each provider's create_llm
+ # (via providers/_helpers.compute_max_tokens) so the cap is consistent
+ # across the live registered-LLM path.
context_window_size = _get_context_window_for_provider(
provider, settings_snapshot
)
-
- # Add context limit to research context for overflow detection
if research_context and context_window_size:
research_context["context_limit"] = context_window_size
logger.info(
@@ -450,353 +445,29 @@ def get_llm(
)
else:
logger.debug(
- f"Context limit not set: research_context={bool(research_context)}, context_window_size={context_window_size}"
- )
-
- max_tokens = None
- if get_setting_from_snapshot(
- "llm.supports_max_tokens", True, settings_snapshot=settings_snapshot
- ):
- # Use 80% of context window to leave room for prompts
- if context_window_size is not None:
- max_tokens = min(
- int(
- get_setting_from_snapshot(
- "llm.max_tokens",
- 100000,
- settings_snapshot=settings_snapshot,
- )
- ),
- int(context_window_size * 0.8),
- )
- common_params["max_tokens"] = max_tokens
- else:
- # Unrestricted context: use provider's default max_tokens
- max_tokens = int(
- get_setting_from_snapshot(
- "llm.max_tokens",
- 100000,
- settings_snapshot=settings_snapshot,
- )
- )
- common_params["max_tokens"] = max_tokens
-
- # Handle different providers
- if provider == "anthropic":
- api_key = get_setting_from_snapshot(
- "llm.anthropic.api_key", settings_snapshot=settings_snapshot
- )
-
- if not api_key:
- raise ValueError(
- "Anthropic API key not configured. Please set llm.anthropic.api_key in settings."
- )
-
- llm: BaseChatModel = ChatAnthropic(
- model=model_name,
- anthropic_api_key=api_key,
- **common_params, # type: ignore[call-arg]
- )
- return wrap_llm_without_think_tags(
- llm,
- research_id=research_id,
- provider=provider,
- research_context=research_context,
- settings_snapshot=settings_snapshot,
- )
-
- if provider == "openai":
- api_key = get_setting_from_snapshot(
- "llm.openai.api_key", settings_snapshot=settings_snapshot
- )
-
- if not api_key:
- raise ValueError(
- "OpenAI API key not configured. Please set llm.openai.api_key in settings."
- )
-
- # Build OpenAI-specific parameters
- openai_params = {
- "model": model_name,
- "api_key": api_key,
- **common_params,
- }
-
- # Add optional parameters if they exist in settings
- try:
- api_base = get_setting_from_snapshot(
- "llm.openai.api_base",
- default=None,
- settings_snapshot=settings_snapshot,
- )
- if api_base:
- openai_params["openai_api_base"] = api_base
- except NoSettingsContextError:
- pass # Optional parameter
-
- try:
- organization = get_setting_from_snapshot(
- "llm.openai.organization",
- default=None,
- settings_snapshot=settings_snapshot,
- )
- if organization:
- openai_params["openai_organization"] = organization
- except NoSettingsContextError:
- pass # Optional parameter
-
- try:
- streaming = get_setting_from_snapshot(
- "llm.streaming",
- default=None,
- settings_snapshot=settings_snapshot,
- )
- except NoSettingsContextError:
- streaming = None # Optional parameter
- if streaming is not None:
- openai_params["streaming"] = streaming
-
- try:
- max_retries = get_setting_from_snapshot(
- "llm.max_retries",
- default=None,
- settings_snapshot=settings_snapshot,
- )
- if max_retries is not None:
- openai_params["max_retries"] = max_retries
- except NoSettingsContextError:
- pass # Optional parameter
-
- try:
- request_timeout = get_setting_from_snapshot(
- "llm.request_timeout",
- default=None,
- settings_snapshot=settings_snapshot,
- )
- if request_timeout is not None:
- openai_params["request_timeout"] = request_timeout
- except NoSettingsContextError:
- pass # Optional parameter
-
- llm = ChatOpenAI(**openai_params) # type: ignore[assignment]
- return wrap_llm_without_think_tags(
- llm,
- research_id=research_id,
- provider=provider,
- research_context=research_context,
- settings_snapshot=settings_snapshot,
- )
-
- if provider == "openai_endpoint":
- api_key = get_setting_from_snapshot(
- "llm.openai_endpoint.api_key", settings_snapshot=settings_snapshot
- )
-
- # Local servers (e.g. llama.cpp) don't require an API key.
- # Use a placeholder so ChatOpenAI doesn't reject the request.
- if not api_key:
- logger.info(
- "No API key configured for openai_endpoint provider. "
- "Using placeholder key. If you are connecting to a hosted "
- "service, set llm.openai_endpoint.api_key in settings."
- )
- api_key = "not-needed" # noqa: S105 # gitleaks:allow
-
- # Get endpoint URL from settings
- if openai_endpoint_url is None:
- openai_endpoint_url = get_setting_from_snapshot(
- "llm.openai_endpoint.url",
- "https://openrouter.ai/api/v1",
- settings_snapshot=settings_snapshot,
- )
- openai_endpoint_url = normalize_url(openai_endpoint_url)
-
- llm = ChatOpenAI( # type: ignore[assignment, call-arg]
- model=model_name,
- api_key=api_key,
- openai_api_base=openai_endpoint_url,
- **common_params,
- )
- return wrap_llm_without_think_tags(
- llm,
- research_id=research_id,
- provider=provider,
- research_context=research_context,
- settings_snapshot=settings_snapshot,
- )
-
- if provider == "ollama":
- try:
- # Use the configurable Ollama base URL
- raw_base_url = get_setting_from_snapshot(
- "llm.ollama.url",
- DEFAULT_OLLAMA_URL,
- settings_snapshot=settings_snapshot,
- )
- base_url = (
- normalize_url(raw_base_url)
- if raw_base_url
- else DEFAULT_OLLAMA_URL
- )
-
- logger.info(
- f"Creating ChatOllama with model={model_name}, base_url={base_url}"
- )
- try:
- # Add num_ctx parameter for Ollama context window size
- ollama_params = {**common_params}
- if context_window_size is not None:
- ollama_params["num_ctx"] = context_window_size
-
- # Thinking/reasoning handling for models like deepseek-r1:
- # The 'reasoning' parameter controls both:
- # 1. Whether the model performs thinking (makes it smarter when True)
- # 2. Whether thinking is separated from the answer (always separated when True)
- #
- # When reasoning=True:
- # - Model performs thinking/reasoning
- # - Thinking goes to additional_kwargs["reasoning_content"] (discarded by LDR)
- # - Only the final answer appears in response.content
- #
- # When reasoning=False:
- # - Model does NOT perform thinking (faster but less smart)
- # - Gives direct answers
-
- enable_thinking = get_setting_from_snapshot(
- "llm.ollama.enable_thinking",
- True, # Default: enable thinking (smarter responses)
- settings_snapshot=settings_snapshot,
- )
-
- if enable_thinking is not None and isinstance(
- enable_thinking, bool
- ):
- ollama_params["reasoning"] = enable_thinking
- logger.debug(
- f"Ollama thinking enabled: {enable_thinking} "
- f"(thinking will be {'shown internally but discarded' if enable_thinking else 'disabled'})"
- )
-
- llm = ChatOllama( # type: ignore[assignment]
- model=model_name, base_url=base_url, **ollama_params
- )
-
- # Log the actual client configuration after creation
- logger.debug(
- f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}"
- )
- if hasattr(llm, "_client"):
- client = llm._client
- logger.debug(f"ChatOllama _client type: {type(client)}")
- if hasattr(client, "_client"):
- inner_client = client._client
- logger.debug(
- f"ChatOllama inner client type: {type(inner_client)}"
- )
- if hasattr(inner_client, "base_url"):
- logger.debug(
- f"ChatOllama inner client base_url: {inner_client.base_url}"
- )
-
- return wrap_llm_without_think_tags(
- llm,
- research_id=research_id,
- provider=provider,
- research_context=research_context,
- settings_snapshot=settings_snapshot,
- )
- except Exception:
- logger.exception("Error creating or testing ChatOllama")
- raise
- except Exception:
- logger.exception("Error in Ollama provider section")
- raise
-
- elif provider == "lmstudio":
- # LM Studio supports OpenAI API format, so we can use ChatOpenAI directly
- lmstudio_url = get_setting_from_snapshot(
- "llm.lmstudio.url",
- DEFAULT_LMSTUDIO_URL,
- settings_snapshot=settings_snapshot,
- )
- _normalized = normalize_url(lmstudio_url)
- base_url = (
- _normalized
- if _normalized.rstrip("/").endswith("/v1")
- else _normalized.rstrip("/") + "/v1"
- )
- # Optional API key for LM Studio with auth enabled. Empty/whitespace
- # falls back to a placeholder ChatOpenAI accepts; a no-auth LM Studio
- # ignores it. Whitespace stripping mirrors LMStudioProvider.create_llm.
- lmstudio_auth_raw = get_setting_from_snapshot( # gitleaks:allow
- "llm.lmstudio.api_key", "", settings_snapshot=settings_snapshot
- )
- lmstudio_auth = (
- str(lmstudio_auth_raw or "").strip()
- or "lm-studio" # gitleaks:allow
- )
-
- llm = ChatOpenAI( # type: ignore[assignment, call-arg, arg-type]
- model=model_name,
- api_key=lmstudio_auth, # gitleaks:allow
- base_url=base_url,
- temperature=temperature,
- max_tokens=max_tokens, # Use calculated max_tokens based on context size
- )
- return wrap_llm_without_think_tags(
- llm,
- research_id=research_id,
- provider=provider,
- research_context=research_context,
- settings_snapshot=settings_snapshot,
- )
-
- elif provider == "llamacpp":
- # llama.cpp's `llama-server` exposes an OpenAI-compatible API, so we
- # use ChatOpenAI directly (same pattern as lmstudio above).
- llamacpp_url = get_setting_from_snapshot(
- "llm.llamacpp.url",
- DEFAULT_LLAMACPP_URL,
- settings_snapshot=settings_snapshot,
- )
- base_url = normalize_url(llamacpp_url)
- # Optional API key for setups behind an auth proxy. Empty falls back
- # to a placeholder ChatOpenAI accepts; a no-auth llama-server ignores it.
- llamacpp_auth = ( # gitleaks:allow
- get_setting_from_snapshot(
- "llm.llamacpp.api_key", "", settings_snapshot=settings_snapshot
- )
- or "lm-studio" # gitleaks:allow
+ f"Context limit not set: research_context={bool(research_context)}, "
+ f"context_window_size={context_window_size}"
)
- llm = ChatOpenAI( # type: ignore[assignment, call-arg, arg-type]
- model=model_name,
- api_key=llamacpp_auth, # gitleaks:allow
- base_url=base_url,
- temperature=temperature,
- max_tokens=max_tokens,
- )
- return wrap_llm_without_think_tags(
- llm,
- research_id=research_id,
- provider=provider,
- research_context=research_context,
- settings_snapshot=settings_snapshot,
- )
-
- elif provider == "none":
+ # Reaching here means the registered-LLM branch above did NOT fire,
+ # which is unusual — auto-discovery normally registers all 6+ built-in
+ # providers (anthropic, openai, openai_endpoint, ollama, lmstudio,
+ # llamacpp + xai/ionos/openrouter via OpenAICompatibleProvider) at
+ # import time. Two specific guards preserve the user-facing error
+ # messages for known-bad cases.
+ if provider == "none":
raise ValueError(
"No LLM provider configured. Please set llm.provider in settings "
"to a valid provider (e.g., 'ollama', 'openai', 'anthropic')."
)
-
- else:
- # Provider validated above but not handled - this shouldn't happen
- # since VALID_PROVIDERS check above would catch unknown providers
- raise ValueError(
- f"Provider '{provider}' is valid but not implemented. "
- f"This is a bug - please report it."
- )
+ raise ValueError(
+ f"Provider '{provider}' was not registered by auto-discovery. "
+ f"This usually indicates an import error during startup — check the "
+ f"logs for 'Error loading provider from <module>' messages. "
+ f"Note that clear_llm_registry()/unregister_llm() also remove "
+ f"built-in providers; discover_providers(force_refresh=True) "
+ f"restores them."
+ )
def wrap_llm_without_think_tags(
diff --git a/src/local_deep_research/llm/providers/_helpers.py b/src/local_deep_research/llm/providers/_helpers.py
new file mode 100644
index 0000000000..2fd29841c5
--- /dev/null
+++ b/src/local_deep_research/llm/providers/_helpers.py
@@ -0,0 +1,97 @@
+"""Shared utilities for LLM provider construction.
+
+These helpers were previously inlined in ``config/llm_config.get_llm``'s
+procedural ``if/elif`` chain (which is now removed). They live here so
+provider-class ``create_llm`` methods are the single source of truth for
+LLM construction logic — no per-provider drift.
+"""
+
+DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE = 8192
+DEFAULT_CLOUD_CONTEXT_WINDOW_SIZE = 128000
+LOCAL_PROVIDERS = ("ollama", "llamacpp", "lmstudio")
+
+
+def get_context_window_for_provider(provider_type, settings_snapshot=None):
+ """Resolve effective context window size for a provider.
+
+ Local providers (ollama, llamacpp, lmstudio) use a smaller default to
+ prevent memory issues. Cloud providers respect
+ ``llm.context_window_unrestricted`` and return ``None`` when
+ unrestricted (the provider auto-handles its own context window).
+ """
+ from ...config.thread_settings import get_setting_from_snapshot
+
+ if provider_type in LOCAL_PROVIDERS:
+ window_size = get_setting_from_snapshot(
+ "llm.local_context_window_size",
+ DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE,
+ settings_snapshot=settings_snapshot,
+ )
+ return (
+ int(window_size)
+ if window_size is not None
+ else DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE
+ )
+ use_unrestricted = get_setting_from_snapshot(
+ "llm.context_window_unrestricted",
+ True,
+ settings_snapshot=settings_snapshot,
+ )
+ if use_unrestricted:
+ return None
+ window_size = get_setting_from_snapshot(
+ "llm.context_window_size",
+ DEFAULT_CLOUD_CONTEXT_WINDOW_SIZE,
+ settings_snapshot=settings_snapshot,
+ )
+ return (
+ int(window_size)
+ if window_size is not None
+ else DEFAULT_CLOUD_CONTEXT_WINDOW_SIZE
+ )
+
+
+def compute_max_tokens(
+ settings_snapshot=None, context_window_size=None
+) -> int | None:
+ """Resolve effective max_tokens for ``ChatXxx(max_tokens=...)``.
+
+ Caps at 80% of ``context_window_size`` (when provided) to leave room
+ for the prompt. Returns ``None`` (caller should omit the kwarg) when:
+
+ - ``llm.supports_max_tokens`` is False, OR
+ - ``llm.max_tokens`` is unset / explicitly None in the snapshot.
+
+ Omitting the kwarg when the setting is absent matches the pre-refactor
+ live-class behavior (the provider SDK's own default applies); a
+ hardcoded fallback like the dead chain's 100000 exceeds the output
+ limit of most cloud models. Production users have ``llm.max_tokens``
+ populated from ``default_settings.json`` (currently 30000), so the
+ unset branch only fires for partial-snapshot programmatic callers.
+
+ Raises:
+ NoSettingsContextError: when ``llm.max_tokens`` is absent from the
+ provided snapshot (or no snapshot is given) and no thread
+ settings context is available. A snapshot being present does
+ NOT prevent the raise — callers must wrap construction in
+ ``except NoSettingsContextError`` and omit the kwarg.
+ """
+ from ...config.thread_settings import get_setting_from_snapshot
+
+ if not get_setting_from_snapshot(
+ "llm.supports_max_tokens",
+ True,
+ settings_snapshot=settings_snapshot,
+ ):
+ return None
+ raw = get_setting_from_snapshot(
+ "llm.max_tokens",
+ None,
+ settings_snapshot=settings_snapshot,
+ )
+ if raw is None:
+ return None
+ max_tokens = int(raw)
+ if context_window_size is not None:
+ max_tokens = min(max_tokens, int(context_window_size * 0.8))
+ return max_tokens
diff --git a/src/local_deep_research/llm/providers/auto_discovery.py b/src/local_deep_research/llm/providers/auto_discovery.py
index 41a5b4728a..3c59885f12 100644
--- a/src/local_deep_research/llm/providers/auto_discovery.py
+++ b/src/local_deep_research/llm/providers/auto_discovery.py
@@ -118,10 +118,14 @@ class ProviderDiscovery:
logger.debug(
f" Found class: {name}, bases: {obj.__bases__}"
)
- # Check if it's a Provider class (ends with "Provider" and has provider_name)
+ # Check if it's a Provider class with a real provider_name.
+ # BaseLLMProvider now sets a default "unknown" so all
+ # subclasses inherit the attribute; skip ones that
+ # haven't customized it (incomplete fixture classes etc.).
if (
name.endswith("Provider")
- and hasattr(obj, "provider_name")
+ and getattr(obj, "provider_name", "unknown")
+ not in (None, "", "unknown")
and issubclass(obj, BaseLLMProvider)
and obj is not OpenAICompatibleProvider
and obj is not BaseLLMProvider
diff --git a/src/local_deep_research/llm/providers/base.py b/src/local_deep_research/llm/providers/base.py
index c89e2201c0..7859f5cddb 100644
--- a/src/local_deep_research/llm/providers/base.py
+++ b/src/local_deep_research/llm/providers/base.py
@@ -1,5 +1,11 @@
"""Base class for LLM providers."""
+# Single placeholder for ChatOpenAI(api_key=...) when no real key is
+# configured (unauthenticated local LM Studio, llama.cpp, etc.). Subclasses
+# MUST NOT override this constant; per-provider drift here was the reason
+# we previously had three different placeholder strings.
+OPTIONAL_API_KEY_PLACEHOLDER = "not-required" # noqa: S105
+
def normalize_provider(provider):
"""Normalize provider name to lowercase canonical form.
@@ -13,16 +19,61 @@ def normalize_provider(provider):
class BaseLLMProvider:
"""Base class for all LLM providers.
- Defines the minimum interface that all providers
- must satisfy. Subclasses should override these
- methods as needed.
+ Defines the minimum interface that all providers must satisfy.
+ Subclasses should override the methods below as needed.
+
+ **Class attribute contract:**
+
+ - ``api_key_setting`` — settings key for the provider's API key
+ (e.g. ``"llm.openai.api_key"``), or ``None`` for providers that have
+ no API key concept at all.
+ - ``api_key_optional`` — when ``True``, a missing/whitespace-only key
+ returns ``None`` from ``resolve_api_key()`` instead of raising.
+ Construction-time callers can then substitute
+ ``OPTIONAL_API_KEY_PLACEHOLDER`` (typical for local providers like
+ LM Studio that may or may not have auth enabled).
+ - ``provider_name`` — display name used in error messages and logs.
+ Subclasses MUST override this away from the ``"unknown"`` default
+ or auto-discovery will skip them.
+
+ **Helper methods (use these instead of reading settings directly):**
+
+ - ``resolve_api_key(snapshot)`` → ``str | None``. Returns the
+ stripped key, ``None`` for optional providers when missing, or
+ raises ``ValueError`` for required providers when missing.
+ - ``resolve_api_key_or_placeholder(snapshot)`` → ``str``. Same as
+ above but substitutes the placeholder when optional+missing — use
+ this when constructing ``ChatOpenAI(api_key=...)``.
+ - ``build_bearer_header(snapshot)`` → ``dict``. Returns
+ ``{"Authorization": "Bearer <key>"}`` or ``{}``. Use this when
+ sending Authorization headers to a provider's REST API.
+ - ``has_api_key(snapshot)`` → ``bool``. Use in ``is_available()``
+ overrides to fail-closed when a required key is missing.
+
+ **`create_llm()` contract:** subclass implementations return a *bare*
+ LangChain ``BaseChatModel``. Wrapping (rate limiting, token counting,
+ think-tag stripping) is applied by ``llm_config.get_llm()`` after the
+ provider class returns. Do NOT wrap inside ``create_llm()``.
"""
+ # Settings key for this provider's API key. None means the provider
+ # has no API key concept at all.
+ api_key_setting: str | None = None
+
+ # Display name used in error messages and logs. Subclasses set this.
+ provider_name: str = "unknown"
+
+ # When True, a missing/whitespace-only key returns None (callers may
+ # substitute OPTIONAL_API_KEY_PLACEHOLDER) instead of raising.
+ api_key_optional: bool = False
+
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
"""Create and return a LangChain chat model instance.
- Subclasses MUST override this method.
+ Subclasses MUST override this method. The returned LLM is BARE —
+ wrapping (rate limiting, token counting, think-tag stripping) is
+ applied by ``llm_config.get_llm()`` after this returns.
Args:
model_name: Name of the model to use
@@ -54,3 +105,70 @@ class BaseLLMProvider:
unauthenticated model listing (e.g., local providers).
"""
return True
+
+ @classmethod
+ def resolve_api_key(cls, settings_snapshot=None) -> str | None:
+ """Read this provider's API key from settings, normalized.
+
+ Returns:
+ The stripped key if non-empty; None if optional and missing
+ or whitespace-only, or if api_key_setting is None.
+ Raises:
+ ValueError if required (api_key_optional=False) and missing.
+ """
+ from ...config.thread_settings import get_setting_from_snapshot
+
+ if not cls.api_key_setting:
+ return None
+ raw = get_setting_from_snapshot(
+ cls.api_key_setting, "", settings_snapshot=settings_snapshot
+ )
+ key = str(raw or "").strip()
+ if key:
+ return key
+ if cls.api_key_optional:
+ return None
+ raise ValueError(
+ f"{cls.provider_name} API key not configured. "
+ f"Please set {cls.api_key_setting} in settings."
+ )
+
+ @classmethod
+ def resolve_api_key_or_placeholder(cls, settings_snapshot=None) -> str:
+ """For ``ChatOpenAI(api_key=...)``-style construction.
+
+ Always returns a string. Real key when set; otherwise the unified
+ ``OPTIONAL_API_KEY_PLACEHOLDER`` so the langchain client doesn't
+ reject the construction call.
+ """
+ key = cls.resolve_api_key(settings_snapshot)
+ return key if key else OPTIONAL_API_KEY_PLACEHOLDER
+
+ @classmethod
+ def build_bearer_header(cls, settings_snapshot=None) -> dict[str, str]:
+ """Build an ``Authorization: Bearer`` header from the resolved key.
+
+ Returns an empty dict when no real key is configured (so callers
+ can spread it conditionally). Required-key providers that raise
+ from ``resolve_api_key`` are treated as "no header" here too —
+ the construction-time error happens elsewhere.
+ """
+ try:
+ key = cls.resolve_api_key(settings_snapshot)
+ except ValueError:
+ return {}
+ return {"Authorization": f"Bearer {key}"} if key else {}
+
+ @classmethod
+ def has_api_key(cls, settings_snapshot=None) -> bool:
+ """True if a real key is configured.
+
+ Returns False for missing/whitespace keys (required providers raise
+ ValueError; we swallow it). Also returns False on broader settings
+ errors so callers like ``is_available()`` fail closed instead of
+ propagating settings infrastructure failures.
+ """
+ try:
+ return cls.resolve_api_key(settings_snapshot) is not None
+ except Exception:
+ return False
diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.py
index fb8a6b07fb..b9e8722bb3 100644
--- a/src/local_deep_research/llm/providers/implementations/anthropic.py
+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py
@@ -3,10 +3,10 @@
from langchain_anthropic import ChatAnthropic
from loguru import logger
-from ....config.thread_settings import (
- get_setting_from_snapshot,
- NoSettingsContextError,
-)
+# get_setting_from_snapshot and NoSettingsContextError are imported inside
+# 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 ..openai_base import OpenAICompatibleProvider
@@ -41,21 +41,13 @@ class AnthropicProvider(OpenAICompatibleProvider):
Raises:
ValueError: If API key is not configured
"""
- settings_snapshot = kwargs.get("settings_snapshot")
+ from ....config.thread_settings import NoSettingsContextError
- # Get API key from settings
- api_key = get_setting_from_snapshot(
- cls.api_key_setting,
- default=None,
- settings_snapshot=settings_snapshot,
- )
+ settings_snapshot = kwargs.get("settings_snapshot")
- if not api_key:
- logger.error(f"{cls.provider_name} API key not found in settings")
- raise ValueError(
- f"{cls.provider_name} API key not configured. "
- f"Please set {cls.api_key_setting} in settings."
- )
+ # 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)
# Require an explicit model — no silent fallback to a hardcoded default.
if not model_name or not model_name.strip():
@@ -73,15 +65,23 @@ class AnthropicProvider(OpenAICompatibleProvider):
"temperature": temperature,
}
- # Add max_tokens if specified in settings
+ # Apply context-window-aware max_tokens cap (was previously only
+ # applied in dead code in llm_config.get_llm).
+ from .._helpers import (
+ compute_max_tokens,
+ get_context_window_for_provider,
+ )
+
try:
- max_tokens = get_setting_from_snapshot(
- "llm.max_tokens",
- default=None,
+ context_window_size = get_context_window_for_provider(
+ "anthropic", settings_snapshot=settings_snapshot
+ )
+ max_tokens = compute_max_tokens(
settings_snapshot=settings_snapshot,
+ context_window_size=context_window_size,
)
- if max_tokens:
- anthropic_params["max_tokens"] = int(max_tokens)
+ if max_tokens: # Treat 0 as unset (matches legacy behavior)
+ anthropic_params["max_tokens"] = max_tokens
except NoSettingsContextError:
pass # Optional parameter
diff --git a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
index 1e90bd5c4e..e9b5b9ba92 100644
--- a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
+++ b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
@@ -17,6 +17,10 @@ class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
provider_name = "OpenAI-Compatible Endpoint"
api_key_setting = "llm.openai_endpoint.api_key"
+ # Many OpenAI-compatible servers (vLLM, local LLMs, etc.) don't require
+ # auth. Optional flag lets the resolver fall back to a placeholder when
+ # no key is configured, instead of raising at LLM construction time.
+ api_key_optional = True
url_setting = "llm.openai_endpoint.url" # type: ignore[assignment] # Settings key for URL
default_base_url = "https://api.openai.com/v1"
default_model = "" # User must explicitly pick a model — no silent fallback
@@ -84,6 +88,16 @@ class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
"""Override to get URL from settings."""
settings_snapshot = kwargs.get("settings_snapshot")
+ # Keyless construction is supported (vLLM, text-generation-webui),
+ # but a key-requiring endpoint (e.g. OpenRouter) fails with an
+ # opaque upstream 401 — warn so the misconfiguration is traceable.
+ if cls.resolve_api_key(settings_snapshot) is None:
+ logger.warning(
+ "No API key configured for openai_endpoint provider; "
+ "proceeding with a placeholder. If your endpoint requires "
+ "an API key, set llm.openai_endpoint.api_key in settings."
+ )
+
# Get custom endpoint URL from settings
custom_url = get_setting_from_snapshot(
"llm.openai_endpoint.url",
diff --git a/src/local_deep_research/llm/providers/implementations/llamacpp.py b/src/local_deep_research/llm/providers/implementations/llamacpp.py
index aa9a193c2f..fbfbe4cb91 100644
--- a/src/local_deep_research/llm/providers/implementations/llamacpp.py
+++ b/src/local_deep_research/llm/providers/implementations/llamacpp.py
@@ -19,10 +19,11 @@ class LlamaCppProvider(OpenAICompatibleProvider):
"""
provider_name = "llama.cpp"
- # api_key_setting=None tells the parent class no key is *required*; the
- # create_llm override below still reads `llm.llamacpp.api_key` for the
- # optional auth-enabled case and falls back to a placeholder otherwise.
- api_key_setting = None # type: ignore[assignment]
+ # llama-server HAS an API key concept (for setups behind an auth proxy);
+ # api_key_optional makes the base resolver fall back to a placeholder
+ # when no key is set, instead of raising.
+ api_key_setting = "llm.llamacpp.api_key"
+ api_key_optional = True
url_setting = "llm.llamacpp.url" # type: ignore[assignment]
default_base_url = DEFAULT_LLAMACPP_URL
default_model = "" # User must specify the model loaded by llama-server
@@ -44,23 +45,26 @@ class LlamaCppProvider(OpenAICompatibleProvider):
cls.default_base_url,
settings_snapshot=settings_snapshot,
)
- api_key = get_setting_from_snapshot(
- "llm.llamacpp.api_key",
- "",
- settings_snapshot=settings_snapshot,
- )
kwargs["base_url"] = normalize_url(url)
- # If the user configured an API key (e.g. llama-server behind an
- # auth proxy), use it. Otherwise pass a placeholder so ChatOpenAI
- # doesn't reject the request — a no-auth llama-server ignores it.
- kwargs["api_key"] = api_key or "lm-studio" # gitleaks:allow
+ # Real key when configured (llama-server behind an auth proxy),
+ # otherwise the unified placeholder; a no-auth llama-server
+ # ignores it.
+ kwargs["api_key"] = cls.resolve_api_key_or_placeholder(
+ settings_snapshot
+ ) # gitleaks:allow
return super()._create_llm_instance(model_name, temperature, **kwargs)
@classmethod
def is_available(cls, settings_snapshot=None):
- """Check whether llama-server is reachable."""
+ """Check whether llama-server is reachable.
+
+ Sends ``Authorization: Bearer`` when an API key is configured so
+ llama-server instances behind an auth proxy are correctly detected
+ as available. Empty key → no auth header → unauthenticated installs
+ still work. Mirrors the LMStudio pattern at lmstudio.py:_get_auth_headers.
+ """
try:
from ....config.thread_settings import get_setting_from_snapshot
from ....security import safe_get
@@ -74,6 +78,9 @@ class LlamaCppProvider(OpenAICompatibleProvider):
response = safe_get(
f"{base_url}/models",
timeout=1,
+ headers=cls.build_bearer_header(
+ settings_snapshot=settings_snapshot
+ ),
allow_localhost=True,
allow_private_ips=True,
)
diff --git a/src/local_deep_research/llm/providers/implementations/lmstudio.py b/src/local_deep_research/llm/providers/implementations/lmstudio.py
index b59d68ca97..9786ab0951 100644
--- a/src/local_deep_research/llm/providers/implementations/lmstudio.py
+++ b/src/local_deep_research/llm/providers/implementations/lmstudio.py
@@ -14,10 +14,12 @@ class LMStudioProvider(OpenAICompatibleProvider):
"""
provider_name = "LM Studio"
- # api_key_setting=None tells the parent class no key is *required*; the
- # create_llm override below still reads `llm.lmstudio.api_key` for the
- # optional auth-enabled case and falls back to a placeholder otherwise.
- api_key_setting = None # type: ignore[assignment]
+ # LM Studio HAS an API key setting; it's just optional (newer LM Studio
+ # versions can require auth on the local server). The api_key_optional
+ # flag tells the base resolver to fall back to a placeholder when no
+ # key is configured, instead of raising.
+ api_key_setting = "llm.lmstudio.api_key"
+ api_key_optional = True
url_setting = "llm.lmstudio.url" # type: ignore[assignment] # Settings key for URL
default_base_url = DEFAULT_LMSTUDIO_URL
default_model = (
@@ -37,11 +39,6 @@ class LMStudioProvider(OpenAICompatibleProvider):
company_name = "LM Studio"
is_cloud = False # Local provider
- # Hardcoded since `api_key_setting` is None at the class level (the route
- # reads via `cls.api_key_setting`; LM Studio handles the key inside its
- # own methods instead, so the route's path stays neutral).
- _API_KEY_PATH = "llm.lmstudio.api_key"
-
@classmethod
def _get_auth_headers(cls, settings_snapshot=None):
"""Build Authorization header from the optional API key setting.
@@ -49,17 +46,7 @@ class LMStudioProvider(OpenAICompatibleProvider):
Returns an empty dict when no key is configured so unauthenticated
LM Studio instances continue to work.
"""
- from ....config.thread_settings import get_setting_from_snapshot
-
- headers: dict[str, str] = {}
- api_key = get_setting_from_snapshot(
- cls._API_KEY_PATH,
- "",
- settings_snapshot=settings_snapshot,
- )
- if api_key and str(api_key).strip():
- headers["Authorization"] = f"Bearer {str(api_key).strip()}"
- return headers
+ return cls.build_bearer_header(settings_snapshot=settings_snapshot)
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
@@ -74,18 +61,15 @@ class LMStudioProvider(OpenAICompatibleProvider):
cls.default_base_url,
settings_snapshot=settings_snapshot,
)
- api_key = get_setting_from_snapshot(
- cls._API_KEY_PATH,
- "",
- settings_snapshot=settings_snapshot,
- )
kwargs["base_url"] = cls._ensure_v1_suffix(lmstudio_url)
- # If user configured a real API key (LM Studio with auth enabled), use
- # it. Otherwise pass a placeholder ChatOpenAI accepts; a no-auth
- # LM Studio ignores it.
- kwargs["api_key"] = api_key or "not-required" # gitleaks:allow
+ # Real key when configured (LM Studio with auth enabled), otherwise
+ # the unified placeholder ChatOpenAI accepts; a no-auth LM Studio
+ # ignores it.
+ kwargs["api_key"] = cls.resolve_api_key_or_placeholder(
+ settings_snapshot
+ ) # gitleaks:allow
# Use parent's create_llm but bypass API key check
return super()._create_llm_instance(model_name, temperature, **kwargs)
@@ -145,12 +129,7 @@ class LMStudioProvider(OpenAICompatibleProvider):
from ....config.thread_settings import get_setting_from_snapshot
if not api_key:
- raw = get_setting_from_snapshot(
- cls._API_KEY_PATH,
- "",
- settings_snapshot=None,
- )
- api_key = str(raw or "").strip() or None
+ api_key = cls.resolve_api_key()
if not base_url:
base_url = get_setting_from_snapshot(
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index 1af14fe7a2..5b04e7932f 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -19,6 +19,9 @@ class OllamaProvider(BaseLLMProvider):
provider_name = "Ollama"
default_model = ""
api_key_setting = "llm.ollama.api_key" # Optional API key for authenticated Ollama instances
+ api_key_optional = (
+ True # Bare Ollama needs no auth; key only matters behind a proxy
+ )
url_setting = "llm.ollama.url" # URL setting for model listing
# Metadata for auto-discovery
@@ -31,27 +34,16 @@ class OllamaProvider(BaseLLMProvider):
"""Get authentication headers for Ollama API requests.
Args:
- api_key: Optional API key to use (takes precedence)
+ api_key: Optional API key to use (takes precedence over settings)
settings_snapshot: Optional settings snapshot to get API key from
Returns:
Dict of headers, empty if no API key configured
"""
- headers = {}
-
- # Use provided API key or get from settings
- if api_key is None and settings_snapshot is not None:
- api_key = get_setting_from_snapshot(
- cls.api_key_setting,
- "", # Empty string instead of None to avoid NoSettingsContextError
- settings_snapshot=settings_snapshot,
- )
-
- if api_key:
- # Support Bearer token authentication for proxied Ollama instances
- headers["Authorization"] = f"Bearer {api_key}"
-
- return headers
+ if api_key is not None:
+ key = str(api_key).strip()
+ return {"Authorization": f"Bearer {key}"} if key else {}
+ return cls.build_bearer_header(settings_snapshot=settings_snapshot)
@classmethod
def list_models_for_api(cls, api_key=None, base_url=None):
@@ -149,32 +141,32 @@ class OllamaProvider(BaseLLMProvider):
# ChatOllama supports auth via headers parameter
ollama_params["headers"] = headers
- # Get context window size from settings for local providers
- context_window_size = get_setting_from_snapshot(
- "llm.local_context_window_size",
- 4096,
+ # Resolve the context window through the shared helper so num_ctx
+ # always matches the context_limit reported for overflow detection
+ # (wrap_llm_without_think_tags uses the same resolution). No
+ # max_tokens kwarg: ChatOllama ignores it (its output-length control
+ # is num_predict), so passing it would only feign a cap.
+ from .._helpers import get_context_window_for_provider
+
+ context_window_size = get_context_window_for_provider(
+ "ollama", settings_snapshot=settings_snapshot
+ )
+ ollama_params["num_ctx"] = context_window_size
+
+ # Thinking/reasoning support for models like deepseek-r1 / qwen2.5.
+ # When True, the model performs reasoning and the reasoning content
+ # is separated into additional_kwargs (and discarded by LDR). When
+ # False, the model gives direct answers without thinking. This was
+ # previously only applied in the dead procedural code at
+ # llm_config.get_llm("ollama"); reproducing it here so the live
+ # path honors the setting too.
+ enable_thinking = get_setting_from_snapshot(
+ "llm.ollama.enable_thinking",
+ True,
settings_snapshot=settings_snapshot,
)
- if context_window_size is not None:
- ollama_params["num_ctx"] = int(context_window_size)
-
- # Add max_tokens if specified in settings and supported
- if get_setting_from_snapshot(
- "llm.supports_max_tokens", True, settings_snapshot=settings_snapshot
- ):
- # Use 80% of context window to leave room for prompts
- if context_window_size is not None:
- max_tokens = min(
- int(
- get_setting_from_snapshot(
- "llm.max_tokens",
- 100000,
- settings_snapshot=settings_snapshot,
- )
- ),
- int(context_window_size * 0.8),
- )
- ollama_params["max_tokens"] = max_tokens
+ if isinstance(enable_thinking, bool):
+ ollama_params["reasoning"] = enable_thinking
llm = ChatOllama(**ollama_params)
diff --git a/src/local_deep_research/llm/providers/implementations/openai.py b/src/local_deep_research/llm/providers/implementations/openai.py
index de08fbc435..07e24fe846 100644
--- a/src/local_deep_research/llm/providers/implementations/openai.py
+++ b/src/local_deep_research/llm/providers/implementations/openai.py
@@ -3,10 +3,11 @@
from langchain_openai import ChatOpenAI
from loguru import logger
-from ....config.thread_settings import (
- get_setting_from_snapshot,
- NoSettingsContextError,
-)
+# get_setting_from_snapshot and NoSettingsContextError are imported inside
+# create_llm() so test patches at the source module
+# (`local_deep_research.config.thread_settings`) are picked up by the
+# function-local import at call time. Module-level binding here would be
+# unaffected by the source-module patch.
from ..openai_base import OpenAICompatibleProvider
@@ -41,21 +42,16 @@ class OpenAIProvider(OpenAICompatibleProvider):
Raises:
ValueError: If API key is not configured
"""
- settings_snapshot = kwargs.get("settings_snapshot")
-
- # Get API key from settings
- api_key = get_setting_from_snapshot(
- cls.api_key_setting,
- default=None,
- settings_snapshot=settings_snapshot,
+ from ....config.thread_settings import (
+ get_setting_from_snapshot,
+ NoSettingsContextError,
)
- if not api_key:
- logger.error(f"{cls.provider_name} API key not found in settings")
- raise ValueError(
- f"{cls.provider_name} API key not configured. "
- f"Please set {cls.api_key_setting} in settings."
- )
+ 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)
# Require an explicit model — no silent fallback to a hardcoded default.
if not model_name or not model_name.strip():
@@ -128,15 +124,23 @@ class OpenAIProvider(OpenAICompatibleProvider):
except NoSettingsContextError:
pass # Optional parameter
- # Add max_tokens if specified in settings
+ # Apply context-window-aware max_tokens cap (was previously only
+ # applied in dead code in llm_config.get_llm).
+ from .._helpers import (
+ compute_max_tokens,
+ get_context_window_for_provider,
+ )
+
try:
- max_tokens = get_setting_from_snapshot(
- "llm.max_tokens",
- default=None,
+ context_window_size = get_context_window_for_provider(
+ "openai", settings_snapshot=settings_snapshot
+ )
+ max_tokens = compute_max_tokens(
settings_snapshot=settings_snapshot,
+ context_window_size=context_window_size,
)
- if max_tokens:
- openai_params["max_tokens"] = int(max_tokens)
+ if max_tokens: # Treat 0 as unset (matches legacy behavior)
+ openai_params["max_tokens"] = max_tokens
except NoSettingsContextError:
pass # Optional parameter
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 959fc3522d..848d90bf72 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -3,10 +3,11 @@
from langchain_openai import ChatOpenAI
from loguru import logger
-from ...config.thread_settings import (
- get_setting_from_snapshot,
- NoSettingsContextError,
-)
+# get_setting_from_snapshot and NoSettingsContextError are imported inside
+# 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. A module-level binding here would
+# be unaffected by patching the source module.
from ...security.log_sanitizer import redact_secrets
from ...utilities.url_utils import normalize_url
from .base import BaseLLMProvider
@@ -43,27 +44,17 @@ class OpenAICompatibleProvider(BaseLLMProvider):
Raises:
ValueError: If API key is not configured
"""
+ from ...config.thread_settings import (
+ get_setting_from_snapshot,
+ NoSettingsContextError,
+ )
+
settings_snapshot = kwargs.get("settings_snapshot")
- # Get API key from settings (if provider requires one)
- if cls.api_key_setting:
- api_key = get_setting_from_snapshot(
- cls.api_key_setting,
- default=None,
- settings_snapshot=settings_snapshot,
- )
-
- if not api_key:
- logger.error(
- f"{cls.provider_name} API key not found in settings"
- )
- raise ValueError(
- f"{cls.provider_name} API key not configured. "
- f"Please set {cls.api_key_setting} in settings."
- )
- else:
- # Provider doesn't require API key (e.g., LM Studio)
- api_key = kwargs.get("api_key", "dummy-key")
+ # Resolve API key. resolve_api_key_or_placeholder raises for required
+ # providers when missing (matches legacy behavior) and falls back to
+ # the unified OPTIONAL_API_KEY_PLACEHOLDER for optional providers.
+ api_key = cls.resolve_api_key_or_placeholder(settings_snapshot)
# Require an explicit model — no silent fallback to a hardcoded default.
if not model_name or not model_name.strip():
@@ -85,15 +76,25 @@ class OpenAICompatibleProvider(BaseLLMProvider):
"temperature": temperature,
}
- # Add max_tokens if specified in settings
+ # Apply context-window-aware max_tokens cap (was previously only
+ # applied in dead code in llm_config.get_llm). 80% of context window
+ # leaves room for the prompt itself.
+ from ._helpers import (
+ compute_max_tokens,
+ get_context_window_for_provider,
+ )
+
try:
- max_tokens = get_setting_from_snapshot(
- "llm.max_tokens",
- default=None,
+ context_window_size = get_context_window_for_provider(
+ getattr(cls, "provider_key", "").lower(),
settings_snapshot=settings_snapshot,
)
- if max_tokens:
- llm_params["max_tokens"] = int(max_tokens)
+ max_tokens = compute_max_tokens(
+ settings_snapshot=settings_snapshot,
+ context_window_size=context_window_size,
+ )
+ if max_tokens: # Treat 0 as unset (matches legacy behavior)
+ llm_params["max_tokens"] = max_tokens
except NoSettingsContextError:
pass # Optional parameter
@@ -146,6 +147,8 @@ class OpenAICompatibleProvider(BaseLLMProvider):
This bypasses API key checking for providers that handle auth differently.
"""
+ from ...config.thread_settings import NoSettingsContextError
+
settings_snapshot = kwargs.get("settings_snapshot")
# Require an explicit model — no silent fallback to a hardcoded default.
@@ -160,8 +163,13 @@ class OpenAICompatibleProvider(BaseLLMProvider):
base_url = kwargs.get("base_url", cls.default_base_url)
base_url = normalize_url(base_url) if base_url else cls.default_base_url
- # Get API key from kwargs (caller is responsible for providing it)
- api_key = kwargs.get("api_key", "dummy-key")
+ # Get API key from kwargs (caller is responsible for providing it).
+ # Defensive default uses the unified OPTIONAL_API_KEY_PLACEHOLDER so
+ # any future direct caller of _create_llm_instance without an
+ # explicit api_key sees the same string as everywhere else.
+ from .base import OPTIONAL_API_KEY_PLACEHOLDER
+
+ api_key = kwargs.get("api_key", OPTIONAL_API_KEY_PLACEHOLDER)
# Build parameters for OpenAI client
llm_params = {
@@ -171,15 +179,23 @@ class OpenAICompatibleProvider(BaseLLMProvider):
"temperature": temperature,
}
- # Add optional parameters (same as in create_llm)
+ # Apply context-window-aware max_tokens cap (matches create_llm above).
+ from ._helpers import (
+ compute_max_tokens,
+ get_context_window_for_provider,
+ )
+
try:
- max_tokens = get_setting_from_snapshot(
- "llm.max_tokens",
- default=None,
+ context_window_size = get_context_window_for_provider(
+ getattr(cls, "provider_key", "").lower(),
settings_snapshot=settings_snapshot,
)
- if max_tokens:
- llm_params["max_tokens"] = int(max_tokens)
+ max_tokens = compute_max_tokens(
+ settings_snapshot=settings_snapshot,
+ context_window_size=context_window_size,
+ )
+ if max_tokens: # Treat 0 as unset (matches legacy behavior)
+ llm_params["max_tokens"] = max_tokens
except NoSettingsContextError:
pass
@@ -189,26 +205,27 @@ class OpenAICompatibleProvider(BaseLLMProvider):
def is_available(cls, settings_snapshot=None):
"""Check if this provider is available.
+ This base implementation is a *configuration* check only — it does
+ not probe the server. Local optional-key providers (LM Studio,
+ llama.cpp) override this with an HTTP reachability probe, so the
+ ``api_key_optional`` branch below is effectively reached only by an
+ optional-key provider that does NOT override is_available(); for
+ such a provider "configured" reduces to "available" and the
+ placeholder key is used at construction time.
+
Args:
settings_snapshot: Optional settings snapshot to use
Returns:
- True if API key is configured (or not needed), False otherwise
+ True if API key is configured (or not needed), False otherwise.
"""
- try:
- # If provider doesn't require API key, it's available
- if not cls.api_key_setting:
- return True
-
- # Check if API key is configured
- api_key = get_setting_from_snapshot(
- cls.api_key_setting,
- default=None,
- settings_snapshot=settings_snapshot,
- )
- return bool(api_key and str(api_key).strip())
- except Exception:
- return False
+ # Provider has no key concept at all → available.
+ # Provider with optional key but no key configured → available
+ # (the placeholder will be used at construction time).
+ # Provider with required key → available iff a real key is set.
+ if not cls.api_key_setting or cls.api_key_optional:
+ return True
+ return cls.has_api_key(settings_snapshot=settings_snapshot)
@classmethod
def requires_auth_for_models(cls):
@@ -234,6 +251,8 @@ class OpenAICompatibleProvider(BaseLLMProvider):
Returns:
The base URL string to use for model listing
"""
+ from ...config.thread_settings import get_setting_from_snapshot
+
if cls.url_setting:
# Use get_setting_from_snapshot which handles both settings_snapshot
# and thread-local context, with proper fallback
@@ -331,6 +350,8 @@ class OpenAICompatibleProvider(BaseLLMProvider):
Returns:
List of model dictionaries with 'value' and 'label' keys
"""
+ from ...config.thread_settings import get_setting_from_snapshot
+
try:
# Get API key from settings if auth is required
api_key = None
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index a922915330..d91d03b42c 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -200,10 +200,15 @@ def _get_setting_from_session(key: str | None, default=None):
treats ``key=None`` as "return all settings" (a real feature used by
``get_all_settings`` for enumeration); this route helper is for
fetching one named setting and must not inherit that bulk-read
- semantic. Without the guard, callers like the auto-discovered
- model-listing loop would receive a dict of every setting (including
- other providers' API keys) when a provider declares
- ``api_key_setting = None`` (LM Studio, Llama.cpp).
+ semantic. Without the guard, callers would receive a dict of every
+ setting (including other providers' API keys) when a provider
+ declares ``api_key_setting = None``.
+
+ NOTE: As of the LLM construction collapse (PR follow-up to #3957),
+ LM Studio and Llama.cpp now declare real ``api_key_setting`` values
+ with ``api_key_optional = True``, so this None guard fires only for
+ truly key-less providers (custom subclasses that don't use settings
+ at all).
"""
if key is None:
return default
diff --git a/tests/config/test_get_llm_dispatch_integration.py b/tests/config/test_get_llm_dispatch_integration.py
new file mode 100644
index 0000000000..671d0ea27d
--- /dev/null
+++ b/tests/config/test_get_llm_dispatch_integration.py
@@ -0,0 +1,334 @@
+"""Integration tests for get_llm() dispatch through the provider registry.
+
+PR #3984 removed the procedural if/elif provider chain in get_llm(); the
+registry path (auto-discovery -> provider class create_llm) is now the only
+construction path. These tests pin the full dispatch chain end to end:
+
+ get_llm(provider=..., settings_snapshot=...)
+ -> _llm_registry (populated by discover_providers() at import)
+ -> <Provider>.create_llm
+ -> langchain client constructor (patched at the provider module)
+
+Only the langchain client class itself is patched — settings resolution,
+registry dispatch, URL handling, key resolution, and the max_tokens cap all
+execute real production code.
+"""
+
+import pytest
+from unittest.mock import patch
+
+from langchain_core.language_models.fake_chat_models import FakeListChatModel
+
+from local_deep_research.config.llm_config import VALID_PROVIDERS, get_llm
+from local_deep_research.llm import is_llm_registered
+
+OPENAI_CHAT = (
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
+)
+ANTHROPIC_CHAT = (
+ "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
+)
+OLLAMA_CHAT = (
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+)
+# LM Studio and llama.cpp construct their client in the shared parent
+# (OpenAICompatibleProvider._create_llm_instance), so the patch point is
+# openai_base, not the implementation module.
+OPENAI_BASE_CHAT = "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+
+
[email protected](autouse=True, scope="module")
+def _ensure_providers_registered():
+ """Re-run auto-discovery in case an earlier test cleared the registry."""
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
+
+
+def _snapshot(**overrides):
+ """Minimal permissive settings snapshot for the live dispatch path."""
+ snap = {
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "rate_limiting.llm_enabled": False,
+ "search.tool": "searxng",
+ }
+ snap.update(overrides)
+ return snap
+
+
+def _fake_llm():
+ return FakeListChatModel(responses=["ok"])
+
+
+class TestRegistryPopulation:
+ """Every built-in provider must be reachable through the registry,
+ since get_llm() no longer has any per-provider construction code."""
+
+ def test_all_valid_providers_are_registered(self):
+ unregistered = [
+ p
+ for p in VALID_PROVIDERS
+ if p != "none" and not is_llm_registered(p)
+ ]
+ assert unregistered == [], (
+ f"Providers missing from the LLM registry: {unregistered}. "
+ "get_llm() has no fallback construction path for these anymore."
+ )
+
+
+class TestCloudProviderDispatch:
+ def test_openai_dispatches_through_provider_class(self):
+ snapshot = _snapshot(**{"llm.openai.api_key": "sk-test-key"})
+ fake = _fake_llm()
+ with patch(OPENAI_CHAT, return_value=fake) as mock_chat:
+ result = get_llm(
+ provider="openai",
+ model_name="gpt-4o-mini",
+ temperature=0.5,
+ settings_snapshot=snapshot,
+ )
+ kwargs = mock_chat.call_args.kwargs
+ assert kwargs["model"] == "gpt-4o-mini"
+ assert kwargs["api_key"] == "sk-test-key"
+ assert kwargs["temperature"] == 0.5
+ assert result.base_llm is fake
+
+ def test_anthropic_dispatches_through_provider_class(self):
+ snapshot = _snapshot(**{"llm.anthropic.api_key": "sk-ant-test"})
+ fake = _fake_llm()
+ with patch(ANTHROPIC_CHAT, return_value=fake) as mock_chat:
+ result = get_llm(
+ provider="anthropic",
+ model_name="claude-sonnet-4-5",
+ settings_snapshot=snapshot,
+ )
+ kwargs = mock_chat.call_args.kwargs
+ assert kwargs["model"] == "claude-sonnet-4-5"
+ assert kwargs["anthropic_api_key"] == "sk-ant-test"
+ assert result.base_llm is fake
+
+ def test_anthropic_missing_key_raises_value_error(self):
+ """Required-key semantics survive on the live path: no placeholder."""
+ with pytest.raises(ValueError, match="API key not configured"):
+ get_llm(
+ provider="anthropic",
+ model_name="claude-sonnet-4-5",
+ settings_snapshot=_snapshot(),
+ )
+
+
+class TestLocalProviderDispatch:
+ def test_lmstudio_appends_v1_suffix(self):
+ """#4532: a URL without /v1 gets the suffix on the live path."""
+ snapshot = _snapshot(**{"llm.lmstudio.url": "http://localhost:1234"})
+ with patch(OPENAI_BASE_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="lmstudio",
+ model_name="qwen2.5-7b",
+ settings_snapshot=snapshot,
+ )
+ kwargs = mock_chat.call_args.kwargs
+ assert kwargs["base_url"] == "http://localhost:1234/v1"
+ assert kwargs["api_key"] == "not-required"
+
+ def test_lmstudio_does_not_double_v1_suffix(self):
+ snapshot = _snapshot(**{"llm.lmstudio.url": "http://localhost:1234/v1"})
+ with patch(OPENAI_BASE_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="lmstudio",
+ model_name="qwen2.5-7b",
+ settings_snapshot=snapshot,
+ )
+ assert (
+ mock_chat.call_args.kwargs["base_url"] == "http://localhost:1234/v1"
+ )
+
+ def test_lmstudio_real_api_key_passed_through(self):
+ snapshot = _snapshot(
+ **{
+ "llm.lmstudio.url": "http://localhost:1234/v1",
+ "llm.lmstudio.api_key": "lms-real-key",
+ }
+ )
+ with patch(OPENAI_BASE_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="lmstudio",
+ model_name="qwen2.5-7b",
+ settings_snapshot=snapshot,
+ )
+ assert mock_chat.call_args.kwargs["api_key"] == "lms-real-key"
+
+ def test_llamacpp_uses_placeholder_key_and_verbatim_url(self):
+ """llama.cpp does NOT force /v1 — the user-provided URL is used as-is."""
+ snapshot = _snapshot(**{"llm.llamacpp.url": "http://localhost:8080"})
+ with patch(OPENAI_BASE_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="llamacpp",
+ model_name="llama-3.1-8b",
+ settings_snapshot=snapshot,
+ )
+ kwargs = mock_chat.call_args.kwargs
+ assert kwargs["base_url"] == "http://localhost:8080"
+ assert kwargs["api_key"] == "not-required"
+
+ def test_ollama_enable_thinking_false_reaches_chatollama(self):
+ """#3984's headline bug fix: llm.ollama.enable_thinking was silently
+ ignored on the live path before this PR."""
+ snapshot = _snapshot(
+ **{
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.ollama.enable_thinking": False,
+ }
+ )
+ fake = _fake_llm()
+ with patch(OLLAMA_CHAT, return_value=fake) as mock_chat:
+ result = get_llm(
+ provider="ollama",
+ model_name="deepseek-r1:14b",
+ settings_snapshot=snapshot,
+ )
+ kwargs = mock_chat.call_args.kwargs
+ assert kwargs["reasoning"] is False
+ assert kwargs["model"] == "deepseek-r1:14b"
+ assert result.base_llm is fake
+
+ def test_ollama_enable_thinking_default_true(self):
+ snapshot = _snapshot(**{"llm.ollama.url": "http://localhost:11434"})
+ with patch(OLLAMA_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="ollama",
+ model_name="deepseek-r1:14b",
+ settings_snapshot=snapshot,
+ )
+ assert mock_chat.call_args.kwargs["reasoning"] is True
+
+
+class TestMaxTokensCap:
+ """The 80%-of-context-window cap previously lived only in dead code;
+ these pin it on the live path end to end through get_llm()."""
+
+ def test_cloud_max_tokens_capped_at_80_percent_of_window(self):
+ snapshot = _snapshot(
+ **{
+ "llm.openai.api_key": "sk-test-key",
+ "llm.context_window_unrestricted": False,
+ "llm.context_window_size": 10000,
+ "llm.max_tokens": 200000,
+ }
+ )
+ with patch(OPENAI_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="openai",
+ model_name="gpt-4o-mini",
+ settings_snapshot=snapshot,
+ )
+ assert mock_chat.call_args.kwargs["max_tokens"] == 8000
+
+ def test_cloud_unrestricted_window_passes_max_tokens_uncapped(self):
+ snapshot = _snapshot(
+ **{
+ "llm.openai.api_key": "sk-test-key",
+ "llm.context_window_unrestricted": True,
+ "llm.max_tokens": 200000,
+ }
+ )
+ with patch(OPENAI_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="openai",
+ model_name="gpt-4o-mini",
+ settings_snapshot=snapshot,
+ )
+ assert mock_chat.call_args.kwargs["max_tokens"] == 200000
+
+ def test_ollama_num_ctx_from_shared_helper_no_max_tokens(self):
+ """Ollama's window resolves through the shared helper (same source
+ as context_limit bookkeeping); no max_tokens kwarg is passed since
+ ChatOllama silently ignores it."""
+ snapshot = _snapshot(
+ **{
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.local_context_window_size": 4096,
+ "llm.max_tokens": 200000,
+ }
+ )
+ with patch(OLLAMA_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="ollama",
+ model_name="llama3.1:8b",
+ settings_snapshot=snapshot,
+ )
+ kwargs = mock_chat.call_args.kwargs
+ assert kwargs["num_ctx"] == 4096
+ assert "max_tokens" not in kwargs
+
+ def test_lmstudio_capped_by_local_window_not_cloud_window(self):
+ """LM Studio resolves its window via provider_key through the
+ LOCAL_PROVIDERS branch — the cloud llm.context_window_size must
+ play no role."""
+ snapshot = _snapshot(
+ **{
+ "llm.lmstudio.url": "http://localhost:1234/v1",
+ "llm.context_window_unrestricted": False,
+ "llm.context_window_size": 128000,
+ "llm.local_context_window_size": 4096,
+ "llm.max_tokens": 200000,
+ }
+ )
+ with patch(OPENAI_BASE_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="lmstudio",
+ model_name="qwen2.5-7b",
+ settings_snapshot=snapshot,
+ )
+ assert mock_chat.call_args.kwargs["max_tokens"] == int(4096 * 0.8)
+
+ def test_unset_max_tokens_omits_kwarg(self):
+ """Partial snapshots without llm.max_tokens must not inject a
+ hardcoded default — the provider SDK's own default applies."""
+ snapshot = _snapshot(**{"llm.openai.api_key": "sk-test-key"})
+ del snapshot["llm.max_tokens"]
+ with patch(OPENAI_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="openai",
+ model_name="gpt-4o-mini",
+ settings_snapshot=snapshot,
+ )
+ assert "max_tokens" not in mock_chat.call_args.kwargs
+
+ def test_supports_max_tokens_false_omits_kwarg(self):
+ snapshot = _snapshot(
+ **{
+ "llm.openai.api_key": "sk-test-key",
+ "llm.supports_max_tokens": False,
+ }
+ )
+ with patch(OPENAI_CHAT, return_value=_fake_llm()) as mock_chat:
+ get_llm(
+ provider="openai",
+ model_name="gpt-4o-mini",
+ settings_snapshot=snapshot,
+ )
+ assert "max_tokens" not in mock_chat.call_args.kwargs
+
+
+class TestContextLimitBookkeeping:
+ def test_context_limit_set_in_research_context(self):
+ """Overflow detection relies on context_limit being populated even
+ though the registered path returns before get_llm's own bookkeeping."""
+ snapshot = _snapshot(
+ **{
+ "llm.openai.api_key": "sk-test-key",
+ "llm.context_window_unrestricted": False,
+ "llm.context_window_size": 10000,
+ }
+ )
+ research_context = {}
+ with patch(OPENAI_CHAT, return_value=_fake_llm()):
+ get_llm(
+ provider="openai",
+ model_name="gpt-4o-mini",
+ settings_snapshot=snapshot,
+ research_context=research_context,
+ )
+ assert research_context["context_limit"] == 10000
diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.py
index 43bf800cc3..3d3eaf12b5 100644
--- a/tests/config/test_llm_config.py
+++ b/tests/config/test_llm_config.py
@@ -401,7 +401,18 @@ class TestWrapLlmWithoutThinkTags:
class TestGetLlm:
- """Tests for get_llm function."""
+ """Tests for get_llm function.
+
+ Many historical tests in this class mocked ``is_llm_registered=False``
+ to force the procedural ``if/elif`` chain in ``get_llm`` (lines
+ ~405-707 prior to the dead-code deletion). That chain has been
+ removed; equivalent live-path coverage now lives in
+ ``tests/llm_providers/implementations/test_*_provider.py``. The
+ remaining tests below exercise the registered-LLM branch and the
+ coordinator surface (provider normalization, model-name validation,
+ final guards). The deleted tests are replaced 1:1 by their class-path
+ equivalents — see commit history for the mapping.
+ """
def test_uses_custom_registered_llm(self):
"""Should use custom LLM when registered."""
@@ -518,301 +529,6 @@ class TestGetLlm:
):
get_llm()
- def test_anthropic_provider_creates_chat_anthropic(self):
- """Should create ChatAnthropic when provider is anthropic."""
- from langchain_anthropic import ChatAnthropic
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "claude-3-sonnet",
- "llm.temperature": 0.7,
- "llm.provider": "anthropic",
- "llm.anthropic.api_key": "sk-ant-test",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatAnthropic, "__init__", return_value=None
- ) as mock_init:
- get_llm(provider="anthropic", settings_snapshot={})
- mock_init.assert_called_once()
- # Check it was called with model and api_key
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["model"] == "claude-3-sonnet"
- assert call_kwargs["anthropic_api_key"] == "sk-ant-test"
-
- def test_anthropic_without_api_key_raises_error(self):
- """Test that missing Anthropic API key raises ValueError."""
- import pytest
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "claude-3-sonnet",
- "llm.temperature": 0.7,
- "llm.provider": "anthropic",
- "llm.anthropic.api_key": None,
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with pytest.raises(
- ValueError, match="Anthropic API key not configured"
- ):
- get_llm(provider="anthropic", settings_snapshot={})
-
- def test_openai_provider_creates_chat_openai(self):
- """Should create ChatOpenAI when provider is openai."""
- from langchain_openai import ChatOpenAI
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "gpt-4",
- "llm.temperature": 0.7,
- "llm.provider": "openai",
- "llm.openai.api_key": "sk-test",
- "llm.openai.api_base": None,
- "llm.openai.organization": None,
- "llm.streaming": None,
- "llm.max_retries": None,
- "llm.request_timeout": None,
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init:
- get_llm(provider="openai", settings_snapshot={})
- mock_init.assert_called_once()
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["model"] == "gpt-4"
- assert call_kwargs["api_key"] == "sk-test"
-
- def test_openai_without_api_key_raises_error(self):
- """Test that missing OpenAI API key raises ValueError."""
- import pytest
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "gpt-4",
- "llm.temperature": 0.7,
- "llm.provider": "openai",
- "llm.openai.api_key": None,
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with pytest.raises(
- ValueError, match="OpenAI API key not configured"
- ):
- get_llm(provider="openai", settings_snapshot={})
-
- def test_openai_endpoint_creates_chat_openai(self):
- """Should create ChatOpenAI with custom endpoint when provider is openai_endpoint."""
- from langchain_openai import ChatOpenAI
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "custom-model",
- "llm.temperature": 0.7,
- "llm.provider": "openai_endpoint",
- "llm.openai_endpoint.api_key": "custom-key",
- "llm.openai_endpoint.url": "https://custom.api.com/v1",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init:
- get_llm(provider="openai_endpoint", settings_snapshot={})
- mock_init.assert_called_once()
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["model"] == "custom-model"
- assert call_kwargs["api_key"] == "custom-key"
- assert "custom.api.com" in call_kwargs.get(
- "openai_api_base", ""
- )
-
- def test_openai_endpoint_without_api_key_uses_placeholder(self):
- """Should succeed without API key for local servers like llama.cpp."""
- from langchain_openai import ChatOpenAI
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "local-model",
- "llm.temperature": 0.7,
- "llm.provider": "openai_endpoint",
- "llm.openai_endpoint.api_key": None,
- "llm.openai_endpoint.url": "http://localhost:8080/v1",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init:
- # Should not raise even without an API key
- get_llm(provider="openai_endpoint", settings_snapshot={})
- mock_init.assert_called_once()
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["model"] == "local-model"
- # A placeholder key should be passed, not None
- assert call_kwargs["api_key"] is not None
- assert call_kwargs["api_key"] != ""
-
- def test_lmstudio_creates_chat_openai(self):
- """Should create ChatOpenAI with LM Studio URL when provider is lmstudio."""
- from langchain_openai import ChatOpenAI
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "local-model",
- "llm.temperature": 0.7,
- "llm.provider": "lmstudio",
- "llm.lmstudio.url": "http://localhost:1234",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": False,
- "llm.context_window_size": 8192,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init:
- get_llm(provider="lmstudio")
- mock_init.assert_called_once()
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["model"] == "local-model"
- assert "localhost:1234" in call_kwargs.get("base_url", "")
-
- def test_lmstudio_passes_configured_api_key(self):
- """User-set llm.lmstudio.api_key flows through the direct get_llm path."""
- from langchain_openai import ChatOpenAI
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "local-model",
- "llm.temperature": 0.7,
- "llm.provider": "lmstudio",
- "llm.lmstudio.url": "http://localhost:1234",
- "llm.lmstudio.api_key": "my-secret-key",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": False,
- "llm.context_window_size": 8192,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init:
- get_llm(provider="lmstudio")
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["api_key"] == "my-secret-key"
-
- def test_lmstudio_falls_back_to_placeholder_when_no_api_key(self):
- """Empty/missing llm.lmstudio.api_key falls back to the placeholder."""
- from langchain_openai import ChatOpenAI
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "local-model",
- "llm.temperature": 0.7,
- "llm.provider": "lmstudio",
- "llm.lmstudio.url": "http://localhost:1234",
- "llm.lmstudio.api_key": "",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": False,
- "llm.context_window_size": 8192,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- with patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init:
- get_llm(provider="lmstudio")
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["api_key"] == "lm-studio"
-
def test_custom_factory_function_is_called(self):
"""Should call factory function for custom registered LLM."""
from langchain_core.language_models import BaseChatModel
@@ -910,81 +626,6 @@ class TestGetLlm:
):
get_llm(provider="bad_factory", settings_snapshot={})
- def test_context_window_size_for_local_providers(self):
- """Should use local context window size for local providers."""
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get:
- calls = []
-
- def track_calls(key, default=None, **kwargs):
- calls.append(key)
- settings = {
- "llm.model": "test-model",
- "llm.temperature": 0.7,
- "llm.provider": "lmstudio",
- "llm.lmstudio.url": "http://localhost:1234",
- "llm.local_context_window_size": 2048, # Custom local size
- "llm.context_window_size": 128000,
- "llm.context_window_unrestricted": False,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }
- return settings.get(key, default)
-
- mock_get.side_effect = track_calls
-
- from langchain_openai import ChatOpenAI
-
- with patch.object(ChatOpenAI, "__init__", return_value=None):
- get_llm(provider="lmstudio")
- # Should have checked local_context_window_size
- assert "llm.local_context_window_size" in calls
-
- def test_research_context_is_mutable_parameter(self):
- """Should accept research_context parameter."""
-
- research_context = {"existing": "value"}
- mock_llm = MagicMock()
-
- with patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ):
- with (
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot"
- ) as mock_get,
- patch(
- "local_deep_research.config.llm_config.ChatAnthropic",
- return_value=mock_llm,
- ),
- ):
- mock_get.side_effect = lambda key, default=None, **kwargs: {
- "llm.model": "test-model",
- "llm.temperature": 0.7,
- "llm.provider": "anthropic",
- "llm.anthropic.api_key": "test-key",
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
-
- result = get_llm(
- provider="anthropic",
- research_context=research_context,
- settings_snapshot={},
- )
- assert hasattr(result, "base_llm")
- # Original key should still be there
- assert research_context["existing"] == "value"
-
class TestWrapperStringResponse:
"""Tests for wrapper handling string responses."""
diff --git a/tests/config/test_llm_config_deep_coverage.py b/tests/config/test_llm_config_deep_coverage.py
index af64a87a33..cb5892cdd9 100644
--- a/tests/config/test_llm_config_deep_coverage.py
+++ b/tests/config/test_llm_config_deep_coverage.py
@@ -324,28 +324,3 @@ class TestGetLlmNameCleaning:
)
except Exception:
pass # ChatOpenAI init may fail, we just care about name cleaning
-
- def test_provider_lowercased(self):
- """Provider is lowercased before validation."""
- with (
- patch(f"{MODULE}.is_llm_registered", return_value=False),
- patch(f"{MODULE}.get_setting_from_snapshot") as mock_setting,
- ):
- mock_setting.side_effect = (
- lambda key, default=None, settings_snapshot=None: {
- "llm.model": "gpt-4",
- "llm.temperature": 0.7,
- "llm.provider": "OpenAI",
- "llm.openai.api_key": None,
- "llm.supports_max_tokens": False,
- "llm.context_window_unrestricted": True,
- "rate_limiting.llm_enabled": False,
- }.get(key, default)
- )
-
- from local_deep_research.config.llm_config import get_llm
-
- # Should raise ValueError about API key (not about invalid provider),
- # proving that "OpenAI" was lowercased to "openai" successfully.
- with pytest.raises(ValueError, match="API key not configured"):
- get_llm(settings_snapshot={})
diff --git a/tests/config/test_llm_config_extended.py b/tests/config/test_llm_config_extended.py
deleted file mode 100644
index f46c455441..0000000000
--- a/tests/config/test_llm_config_extended.py
+++ /dev/null
@@ -1,271 +0,0 @@
-"""Extended tests for llm_config provider paths (LlamaCpp, Ollama, OpenAI)."""
-
-from unittest.mock import MagicMock, patch
-
-
-from local_deep_research.config.llm_config import get_llm
-
-
-def _settings_dict(overrides=None):
- """Base settings dict shared across tests."""
- base = {
- "llm.model": "test-model",
- "llm.temperature": 0.5,
- "llm.provider": "ollama",
- "llm.local_context_window_size": 4096,
- "llm.context_window_unrestricted": True,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- "rate_limiting.llm_enabled": False,
- }
- if overrides:
- base.update(overrides)
- return base
-
-
-def _mock_get_setting(settings):
- """Return a side_effect for get_setting_from_snapshot."""
- return lambda key, default=None, **kw: settings.get(key, default)
-
-
-# ── LlamaCpp provider ──────────────────────────────────────────────
-
-
-class TestLlamaCppProvider:
- """Tests for the llamacpp provider — now an HTTP wrapper around llama-server."""
-
- def test_uses_chat_openai_with_configured_url(self):
- """Verifies dispatch goes through ChatOpenAI with the URL from settings."""
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp.url": "http://my-server:8080/v1",
- }
- )
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
- ) as mock_chat_openai,
- ):
- mock_chat_openai.return_value = MagicMock()
- get_llm(provider="llamacpp", model_name="my-model")
-
- mock_chat_openai.assert_called_once()
- call_kwargs = mock_chat_openai.call_args[1]
- assert call_kwargs["base_url"] == "http://my-server:8080/v1"
- assert call_kwargs["model"] == "my-model"
-
- def test_uses_default_url_when_unset(self):
- """When llm.llamacpp.url is unset, falls back to localhost:8080/v1."""
- settings = _settings_dict({"llm.provider": "llamacpp"})
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
- ) as mock_chat_openai,
- ):
- mock_chat_openai.return_value = MagicMock()
- get_llm(provider="llamacpp", model_name="my-model")
-
- call_kwargs = mock_chat_openai.call_args[1]
- assert call_kwargs["base_url"] == "http://localhost:8080/v1"
-
-
-# ── Ollama provider ────────────────────────────────────────────────
-
-
-class TestOllamaProvider:
- """Tests for the Ollama provider path in get_llm."""
-
- def _ollama_settings(self, overrides=None):
- s = _settings_dict(
- {
- "llm.provider": "ollama",
- "llm.ollama.url": "http://localhost:11434",
- "llm.ollama.enable_thinking": True,
- }
- )
- if overrides:
- s.update(overrides)
- return s
-
- def test_model_not_found_raises_error(self):
- """Model not in Ollama model list — now handled by ChatOllama itself."""
- settings = self._ollama_settings()
-
- mock_ollama_cls = MagicMock()
- mock_ollama_cls.return_value = MagicMock()
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.config.llm_config.ChatOllama",
- mock_ollama_cls,
- ),
- patch(
- "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
- return_value=MagicMock(),
- ),
- ):
- 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 creates ChatOllama (no pre-flight model check)."""
- settings = self._ollama_settings()
-
- mock_ollama_cls = MagicMock()
- mock_ollama_instance = MagicMock()
- mock_ollama_cls.return_value = mock_ollama_instance
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.config.llm_config.ChatOllama",
- mock_ollama_cls,
- ),
- patch(
- "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
- return_value=mock_ollama_instance,
- ),
- ):
- result = get_llm(provider="ollama", model_name="test-model")
- mock_ollama_cls.assert_called_once()
- assert result is mock_ollama_instance
-
- def test_api_tags_exception_continues(self):
- """No pre-flight check means ChatOllama is always created directly."""
- settings = self._ollama_settings()
-
- mock_ollama_cls = MagicMock()
- mock_ollama_instance = MagicMock()
- mock_ollama_cls.return_value = mock_ollama_instance
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.config.llm_config.ChatOllama",
- mock_ollama_cls,
- ),
- patch(
- "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
- return_value=mock_ollama_instance,
- ),
- ):
- result = get_llm(provider="ollama", model_name="test-model")
- mock_ollama_cls.assert_called_once()
- assert result is mock_ollama_instance
-
-
-# ── OpenAI provider optional params ────────────────────────────────
-
-
-class TestOpenAIOptionalParams:
- """Tests for OpenAI provider optional parameters."""
-
- def _openai_settings(self, overrides=None):
- s = _settings_dict(
- {
- "llm.provider": "openai",
- "llm.openai.api_key": "sk-test",
- "llm.openai.api_base": None,
- "llm.openai.organization": None,
- "llm.streaming": None,
- "llm.max_retries": None,
- "llm.request_timeout": None,
- }
- )
- if overrides:
- s.update(overrides)
- return s
-
- def test_with_api_base(self):
- """api_base is passed through as openai_api_base."""
- from langchain_openai import ChatOpenAI
-
- settings = self._openai_settings(
- {"llm.openai.api_base": "https://custom.endpoint/v1"}
- )
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init,
- ):
- get_llm(provider="openai", settings_snapshot={})
- call_kwargs = mock_init.call_args.kwargs
- assert (
- call_kwargs["openai_api_base"] == "https://custom.endpoint/v1"
- )
-
- def test_with_organization(self):
- """organization is passed through as openai_organization."""
- from langchain_openai import ChatOpenAI
-
- settings = self._openai_settings(
- {"llm.openai.organization": "org-abc123"}
- )
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch.object(
- ChatOpenAI, "__init__", return_value=None
- ) as mock_init,
- ):
- get_llm(provider="openai", settings_snapshot={})
- call_kwargs = mock_init.call_args.kwargs
- assert call_kwargs["openai_organization"] == "org-abc123"
diff --git a/tests/config/test_llm_config_missing_coverage.py b/tests/config/test_llm_config_missing_coverage.py
index 068aaa532e..2a78715655 100644
--- a/tests/config/test_llm_config_missing_coverage.py
+++ b/tests/config/test_llm_config_missing_coverage.py
@@ -63,34 +63,6 @@ class TestGetLlmFallbackEnvVar:
with pytest.raises(ValueError):
get_llm(provider="none", settings_snapshot=settings)
- def test_fallback_env_var_with_openai_config_skips_fallback(self):
- """When provider has config (openai with api_key), fallback is NOT used."""
- settings = _settings_dict(
- {"llm.provider": "openai", "llm.openai.api_key": "sk-real-key"}
- )
- mock_openai_cls = MagicMock()
- mock_openai_instance = MagicMock()
- mock_openai_cls.return_value = mock_openai_instance
- with (
- patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
- patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
- 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}.ChatOpenAI", mock_openai_cls),
- patch(
- f"{MODULE}.wrap_llm_without_think_tags",
- return_value=mock_openai_instance,
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- result = get_llm(provider="openai", settings_snapshot=settings)
- mock_openai_cls.assert_called_once()
- assert result is mock_openai_instance
-
def test_fallback_env_var_no_config_raises_error(self):
"""When provider has NO config, ValueError is raised (fallback model removed)."""
settings = _settings_dict(
@@ -110,67 +82,6 @@ class TestGetLlmFallbackEnvVar:
with pytest.raises(ValueError):
get_llm(provider="openai", settings_snapshot=settings)
- def test_fallback_env_var_lmstudio_available_skips_fallback(self):
- """When provider is lmstudio and available, fallback is skipped."""
- settings = _settings_dict({"llm.provider": "lmstudio"})
- mock_openai_cls = MagicMock()
- mock_lmstudio_instance = MagicMock()
- mock_openai_cls.return_value = mock_lmstudio_instance
- with (
- patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
- patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
- 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_lmstudio_available", return_value=True),
- patch(f"{MODULE}.normalize_url", side_effect=lambda x: x),
- patch(f"{MODULE}.ChatOpenAI", mock_openai_cls),
- patch(
- f"{MODULE}.wrap_llm_without_think_tags",
- return_value=mock_lmstudio_instance,
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- result = get_llm(provider="lmstudio", settings_snapshot=settings)
- mock_openai_cls.assert_called_once()
- assert result is mock_lmstudio_instance
-
- def test_fallback_env_var_llamacpp_available_skips_fallback(self):
- """When provider is llamacpp and available, fallback is skipped."""
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp.url": "http://localhost:8080/v1",
- }
- )
- mock_openai_cls = MagicMock()
- mock_llamacpp_instance = MagicMock()
- mock_openai_cls.return_value = mock_llamacpp_instance
- with (
- patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),
- patch.dict(os.environ, {"LDR_TESTING_WITH_MOCKS": ""}, clear=False),
- 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_llamacpp_available", return_value=True),
- patch(f"{MODULE}.normalize_url", side_effect=lambda x: x),
- patch(f"{MODULE}.ChatOpenAI", mock_openai_cls),
- patch(
- f"{MODULE}.wrap_llm_without_think_tags",
- return_value=mock_llamacpp_instance,
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- result = get_llm(provider="llamacpp", settings_snapshot=settings)
- mock_openai_cls.assert_called_once()
- assert result is mock_llamacpp_instance
-
class TestGetLlmOllamaEdgeCases:
"""Tests for ollama-specific edge cases in get_llm."""
@@ -187,117 +98,6 @@ class TestGetLlmOllamaEdgeCases:
s.update(overrides)
return s
- def test_ollama_model_not_found_raises_error(self):
- """When model is not in the Ollama model list, ChatOllama handles it at invoke time (no pre-flight check)."""
- settings = self._ollama_settings()
- 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}.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
-
- # 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()
- 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}.ChatOllama",
- side_effect=RuntimeError("failed to init"),
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- with pytest.raises(RuntimeError, match="failed to init"):
- get_llm(
- provider="ollama",
- model_name="test-model",
- settings_snapshot=settings,
- )
-
- 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_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}.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
-
- get_llm(
- provider="ollama",
- model_name="test-model",
- settings_snapshot=settings,
- )
- call_kwargs = mock_ollama_cls.call_args[1]
- assert call_kwargs["reasoning"] is True
-
- 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_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}.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
-
- get_llm(
- provider="ollama",
- model_name="test-model",
- settings_snapshot=settings,
- )
- call_kwargs = mock_ollama_cls.call_args[1]
- assert call_kwargs["reasoning"] is False
-
-
-# NOTE: llamacpp now uses an HTTP OpenAI-compatible endpoint (llama-server)
-# instead of in-process llama-cpp-python. The old model-path/extension/
-# directory-listing edge cases that lived here are gone with that code.
-# HTTP-based dispatch is covered in tests/config/test_llm_config_extended.py
-# and tests/config/test_llm_config_providers.py.
-
class TestGetContextWindowForProviderMissing:
"""Additional coverage for _get_context_window_for_provider edge cases."""
diff --git a/tests/config/test_llm_config_providers.py b/tests/config/test_llm_config_providers.py
index de9e0bea47..36bd925bf9 100644
--- a/tests/config/test_llm_config_providers.py
+++ b/tests/config/test_llm_config_providers.py
@@ -108,42 +108,6 @@ class TestProviderInstantiation:
assert params["api_key"] == "lm-studio" # pragma: allowlist secret
assert params["base_url"] == lmstudio_url
- def test_llamacpp_uses_openai_compatible_endpoint(self):
- """llamacpp now talks to llama-server via ChatOpenAI; no in-process load."""
- from unittest.mock import patch, MagicMock
-
- def _settings(key, default=None, *a, **kw):
- return {
- "llm.llamacpp.url": "http://localhost:8080/v1",
- "llm.local_context_window_size": 8192,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- }.get(key, default)
-
- with (
- patch(
- "local_deep_research.config.llm_config.is_llm_registered",
- return_value=False,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=_settings,
- ),
- patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
- ) as mock_chat_openai,
- ):
- mock_chat_openai.return_value = MagicMock()
-
- from local_deep_research.config.llm_config import get_llm
-
- get_llm(provider="llamacpp", model_name="my-loaded-model")
-
- mock_chat_openai.assert_called_once()
- call_kwargs = mock_chat_openai.call_args[1]
- assert call_kwargs["base_url"] == "http://localhost:8080/v1"
- assert call_kwargs["model"] == "my-loaded-model"
-
class TestProviderValidation:
"""Tests for provider validation."""
diff --git a/tests/conftest.py b/tests/conftest.py
index 6c0a543619..dc37f7e6ca 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -132,6 +132,14 @@ def reset_all_singletons():
if hasattr(auto_discovery, "provider_discovery"):
auto_discovery.provider_discovery._discovered = False
auto_discovery.provider_discovery._providers = {}
+
+ # Re-register the built-in providers. get_llm() has no fallback
+ # construction path anymore, so a test that called
+ # clear_llm_registry() would otherwise break every later test
+ # that uses a built-in provider (order-dependent failures).
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
except ImportError:
pass
diff --git a/tests/llm/providers/test_openai_base.py b/tests/llm/providers/test_openai_base.py
index ace7ecb62c..2f157b806f 100644
--- a/tests/llm/providers/test_openai_base.py
+++ b/tests/llm/providers/test_openai_base.py
@@ -53,7 +53,7 @@ class TestOpenAICompatibleProviderCreateLLM:
)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
):
try:
@@ -76,7 +76,7 @@ class TestOpenAICompatibleProviderCreateLLM:
return default
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
side_effect=mock_get_setting,
):
with pytest.raises(ValueError, match="model not configured"):
@@ -96,7 +96,7 @@ class TestOpenAICompatibleProviderCreateLLM:
return default
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
side_effect=mock_get_setting,
):
with patch(
@@ -123,7 +123,7 @@ class TestOpenAICompatibleProviderCreateLLM:
return default
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
side_effect=mock_get_setting,
):
with patch(
@@ -149,7 +149,7 @@ class TestOpenAICompatibleProviderIsAvailable:
)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value="test-api-key",
):
result = OpenAICompatibleProvider.is_available()
@@ -163,7 +163,7 @@ class TestOpenAICompatibleProviderIsAvailable:
)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
):
result = OpenAICompatibleProvider.is_available()
@@ -177,7 +177,7 @@ class TestOpenAICompatibleProviderIsAvailable:
)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
side_effect=Exception("Test error"),
):
result = OpenAICompatibleProvider.is_available()
@@ -212,7 +212,7 @@ class TestOpenAICompatibleProviderListModels:
OpenAICompatibleProvider, "list_models_for_api", return_value=[]
):
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value="test-key",
):
result = OpenAICompatibleProvider.list_models()
@@ -226,7 +226,7 @@ class TestOpenAICompatibleProviderListModels:
)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
side_effect=Exception("Test error"),
):
result = OpenAICompatibleProvider.list_models()
@@ -320,7 +320,7 @@ class TestOpenAICompatibleProviderCreateLLMInstance:
)
call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["api_key"] == "dummy-key"
+ assert call_kwargs["api_key"] == "not-required"
def test_create_llm_instance_uses_provided_key(self):
"""_create_llm_instance uses provided API key."""
diff --git a/tests/llm/providers/test_openai_base_deep_coverage.py b/tests/llm/providers/test_openai_base_deep_coverage.py
index addf28fcba..282dd71924 100644
--- a/tests/llm/providers/test_openai_base_deep_coverage.py
+++ b/tests/llm/providers/test_openai_base_deep_coverage.py
@@ -16,11 +16,12 @@ from local_deep_research.llm.providers.openai_base import (
)
MODULE = "local_deep_research.llm.providers.openai_base"
+SETTINGS_MODULE = "local_deep_research.config.thread_settings"
class TestCreateLlmApiKeyHandling:
@patch(f"{MODULE}.ChatOpenAI")
- @patch(f"{MODULE}.get_setting_from_snapshot")
+ @patch(f"{SETTINGS_MODULE}.get_setting_from_snapshot")
def test_no_api_key_setting_uses_dummy(self, mock_get_setting, mock_chat):
"""Provider without api_key_setting uses dummy key."""
mock_get_setting.return_value = None
@@ -36,10 +37,10 @@ class TestCreateLlmApiKeyHandling:
NoKeyProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["api_key"] == "dummy-key"
+ assert call_kwargs["api_key"] == "not-required"
@patch(f"{MODULE}.ChatOpenAI")
- @patch(f"{MODULE}.get_setting_from_snapshot")
+ @patch(f"{SETTINGS_MODULE}.get_setting_from_snapshot")
def test_missing_api_key_raises(self, mock_get_setting, mock_chat):
"""Raises ValueError when required API key is missing."""
mock_get_setting.return_value = None
@@ -51,7 +52,7 @@ class TestCreateLlmApiKeyHandling:
)
@patch(f"{MODULE}.ChatOpenAI")
- @patch(f"{MODULE}.get_setting_from_snapshot")
+ @patch(f"{SETTINGS_MODULE}.get_setting_from_snapshot")
def test_api_key_from_settings(self, mock_get_setting, mock_chat):
"""API key is read from settings snapshot."""
@@ -82,7 +83,8 @@ def _api_key_side_effect(key, default=None, settings_snapshot=None):
class TestCreateLlmModelAndUrl:
@patch(f"{MODULE}.ChatOpenAI")
@patch(
- f"{MODULE}.get_setting_from_snapshot", side_effect=_api_key_side_effect
+ f"{SETTINGS_MODULE}.get_setting_from_snapshot",
+ side_effect=_api_key_side_effect,
)
def test_default_model_used(self, mock_get_setting, mock_chat):
"""Raises ValueError when no model name is provided (no silent default)."""
@@ -96,7 +98,8 @@ class TestCreateLlmModelAndUrl:
@patch(f"{MODULE}.ChatOpenAI")
@patch(
- f"{MODULE}.get_setting_from_snapshot", side_effect=_api_key_side_effect
+ f"{SETTINGS_MODULE}.get_setting_from_snapshot",
+ side_effect=_api_key_side_effect,
)
def test_custom_base_url(self, mock_get_setting, mock_chat):
"""Custom base_url is normalized and used."""
@@ -114,7 +117,7 @@ class TestCreateLlmModelAndUrl:
class TestCreateLlmOptionalParams:
@patch(f"{MODULE}.ChatOpenAI")
- @patch(f"{MODULE}.get_setting_from_snapshot")
+ @patch(f"{SETTINGS_MODULE}.get_setting_from_snapshot")
def test_max_tokens_from_settings(self, mock_get_setting, mock_chat):
"""max_tokens is read from settings and passed to ChatOpenAI."""
@@ -136,7 +139,7 @@ class TestCreateLlmOptionalParams:
assert call_kwargs["max_tokens"] == 2048
@patch(f"{MODULE}.ChatOpenAI")
- @patch(f"{MODULE}.get_setting_from_snapshot")
+ @patch(f"{SETTINGS_MODULE}.get_setting_from_snapshot")
def test_streaming_from_settings(self, mock_get_setting, mock_chat):
"""streaming is read from settings."""
@@ -175,7 +178,8 @@ class TestCreateLlmOptionalParams:
mock_chat.return_value = Mock()
with patch(
- f"{MODULE}.get_setting_from_snapshot", side_effect=side_effect
+ f"{SETTINGS_MODULE}.get_setting_from_snapshot",
+ side_effect=side_effect,
):
# Should not raise despite NoSettingsContextError for optional params
OpenAICompatibleProvider.create_llm(
diff --git a/tests/llm/test_openai_base.py b/tests/llm/test_openai_base.py
index 8e3c025a54..4b67f95c01 100644
--- a/tests/llm/test_openai_base.py
+++ b/tests/llm/test_openai_base.py
@@ -55,7 +55,7 @@ class TestOpenAICompatibleProviderCreateLLM:
@patch("local_deep_research.llm.providers.openai_base.ChatOpenAI")
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_create_llm_with_api_key(self, mock_get_setting, mock_chat):
"""Test creating LLM with API key from settings."""
@@ -83,7 +83,7 @@ class TestOpenAICompatibleProviderCreateLLM:
assert call_kwargs["temperature"] == 0.5
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_create_llm_raises_without_api_key(self, mock_get_setting):
"""Test that create_llm raises when API key is missing."""
@@ -98,7 +98,7 @@ class TestOpenAICompatibleProviderCreateLLM:
@patch("local_deep_research.llm.providers.openai_base.ChatOpenAI")
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_create_llm_uses_default_model(self, mock_get_setting, mock_chat):
"""Test that create_llm raises ValueError when no model name is provided."""
@@ -119,7 +119,7 @@ class TestOpenAICompatibleProviderCreateLLM:
@patch("local_deep_research.llm.providers.openai_base.ChatOpenAI")
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_create_llm_uses_default_temperature(
self, mock_get_setting, mock_chat
@@ -144,7 +144,7 @@ class TestOpenAICompatibleProviderCreateLLM:
@patch("local_deep_research.llm.providers.openai_base.ChatOpenAI")
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_create_llm_accepts_custom_base_url(
self, mock_get_setting, mock_chat
@@ -174,7 +174,7 @@ class TestOpenAICompatibleProviderIsAvailable:
"""Tests for OpenAICompatibleProvider.is_available method."""
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_is_available_returns_true_with_api_key(self, mock_get_setting):
"""Test that is_available returns True when API key is set."""
@@ -187,7 +187,7 @@ class TestOpenAICompatibleProviderIsAvailable:
assert OpenAICompatibleProvider.is_available() is True
@patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
)
def test_is_available_returns_false_without_api_key(self, mock_get_setting):
"""Test that is_available returns False when API key is not set."""
@@ -233,7 +233,7 @@ class TestOpenAICompatibleProviderCreateLLMInstance:
OpenAICompatibleProvider._create_llm_instance(model_name="test")
call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["api_key"] == "dummy-key"
+ assert call_kwargs["api_key"] == "not-required"
class TestSubclassImplementation:
diff --git a/tests/llm_providers/implementations/test_anthropic_provider.py b/tests/llm_providers/implementations/test_anthropic_provider.py
index 3ad7a708de..249e2a8404 100644
--- a/tests/llm_providers/implementations/test_anthropic_provider.py
+++ b/tests/llm_providers/implementations/test_anthropic_provider.py
@@ -46,7 +46,7 @@ class TestAnthropicCreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -66,7 +66,7 @@ class TestAnthropicCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -92,7 +92,7 @@ class TestAnthropicCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -110,7 +110,7 @@ class TestAnthropicCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -135,7 +135,7 @@ class TestAnthropicCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -160,7 +160,7 @@ class TestAnthropicCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -183,7 +183,7 @@ class TestAnthropicCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.anthropic.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -202,7 +202,7 @@ class TestAnthropicIsAvailable:
def test_is_available_true_when_key_exists(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-key"
@@ -212,7 +212,7 @@ class TestAnthropicIsAvailable:
def test_is_available_false_when_no_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -222,7 +222,7 @@ class TestAnthropicIsAvailable:
def test_is_available_false_when_empty_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
@@ -232,7 +232,7 @@ class TestAnthropicIsAvailable:
def test_is_available_false_on_exception(self):
"""Returns False when exception occurs."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = Exception("Settings error")
diff --git a/tests/llm_providers/implementations/test_google_provider.py b/tests/llm_providers/implementations/test_google_provider.py
index c198263866..c4b1439c93 100644
--- a/tests/llm_providers/implementations/test_google_provider.py
+++ b/tests/llm_providers/implementations/test_google_provider.py
@@ -423,7 +423,7 @@ class TestGoogleCreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -446,7 +446,7 @@ class TestGoogleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -475,7 +475,7 @@ class TestGoogleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -496,7 +496,7 @@ class TestGoogleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -522,7 +522,7 @@ class TestGoogleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -555,7 +555,7 @@ class TestGoogleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -576,7 +576,7 @@ class TestGoogleIsAvailable:
def test_is_available_true_when_key_exists(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-google-key"
@@ -586,7 +586,7 @@ class TestGoogleIsAvailable:
def test_is_available_false_when_no_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -596,7 +596,7 @@ class TestGoogleIsAvailable:
def test_is_available_false_when_empty_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
@@ -606,7 +606,7 @@ class TestGoogleIsAvailable:
def test_is_available_false_on_exception(self):
"""Returns False when exception occurs."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = Exception("Settings error")
diff --git a/tests/llm_providers/implementations/test_ionos_provider.py b/tests/llm_providers/implementations/test_ionos_provider.py
index a26f78be4e..e91d0fdd81 100644
--- a/tests/llm_providers/implementations/test_ionos_provider.py
+++ b/tests/llm_providers/implementations/test_ionos_provider.py
@@ -46,7 +46,7 @@ class TestIONOSCreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -69,7 +69,7 @@ class TestIONOSCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -98,7 +98,7 @@ class TestIONOSCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -119,7 +119,7 @@ class TestIONOSCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -149,7 +149,7 @@ class TestIONOSCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -177,7 +177,7 @@ class TestIONOSCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -196,7 +196,7 @@ class TestIONOSIsAvailable:
def test_is_available_true_when_key_exists(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-key"
@@ -206,7 +206,7 @@ class TestIONOSIsAvailable:
def test_is_available_false_when_no_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -216,7 +216,7 @@ class TestIONOSIsAvailable:
def test_is_available_false_when_empty_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
diff --git a/tests/llm_providers/implementations/test_llamacpp_provider.py b/tests/llm_providers/implementations/test_llamacpp_provider.py
index 5bb7d89c23..64c616b752 100644
--- a/tests/llm_providers/implementations/test_llamacpp_provider.py
+++ b/tests/llm_providers/implementations/test_llamacpp_provider.py
@@ -47,9 +47,10 @@ class TestLlamaCppProviderMetadata:
"""llama.cpp is a local provider."""
assert LlamaCppProvider.is_cloud is False
- def test_api_key_setting_is_none(self):
- """llama.cpp doesn't require an API key."""
- assert LlamaCppProvider.api_key_setting is None
+ def test_api_key_setting_is_optional(self):
+ """llama.cpp declares its setting key but treats it as optional."""
+ assert LlamaCppProvider.api_key_setting == "llm.llamacpp.api_key"
+ assert LlamaCppProvider.api_key_optional is True
def test_url_setting(self):
"""URL setting is defined."""
@@ -138,7 +139,7 @@ class TestLlamaCppCreateLLM:
LlamaCppProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["api_key"] == "lm-studio"
+ assert call_kwargs["api_key"] == "not-required"
def test_create_llm_uses_real_api_key(self):
"""Uses configured API key when llm.llamacpp.api_key is set."""
@@ -246,6 +247,33 @@ class TestLlamaCppIsAvailable:
result = LlamaCppProvider.is_available()
assert result is False
+ def test_sends_bearer_header_when_api_key_configured(self):
+ """Authenticated llama-server (proxy) instances are detected as available.
+
+ Regression: previously is_available() probed without Authorization,
+ so a 401 from an auth proxy made the provider report unavailable
+ even though create_llm() was perfectly capable of using the key.
+ """
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_setting_side_effect(
+ "http://localhost:8080/v1", api_key_value="my-secret-key"
+ )
+
+ with patch("local_deep_research.security.safe_get") as mock_get:
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_get.return_value = mock_response
+
+ LlamaCppProvider.is_available()
+
+ # Assert headers were forwarded
+ call_kwargs = mock_get.call_args[1]
+ assert call_kwargs.get("headers") == {
+ "Authorization": "Bearer my-secret-key"
+ }
+
class TestLlamaCppRequiresAuth:
"""Tests for requires_auth_for_models method."""
diff --git a/tests/llm_providers/implementations/test_lmstudio_provider.py b/tests/llm_providers/implementations/test_lmstudio_provider.py
index 755eb48c26..bf7f726d8c 100644
--- a/tests/llm_providers/implementations/test_lmstudio_provider.py
+++ b/tests/llm_providers/implementations/test_lmstudio_provider.py
@@ -46,9 +46,10 @@ class TestLMStudioProviderMetadata:
"""Company name is LM Studio."""
assert LMStudioProvider.company_name == "LM Studio"
- def test_api_key_setting_is_none(self):
- """LM Studio doesn't require API key."""
- assert LMStudioProvider.api_key_setting is None
+ def test_api_key_setting_is_optional(self):
+ """LM Studio declares its setting key but treats it as optional."""
+ assert LMStudioProvider.api_key_setting == "llm.lmstudio.api_key"
+ assert LMStudioProvider.api_key_optional is True
def test_url_setting(self):
"""URL setting is defined."""
diff --git a/tests/llm_providers/implementations/test_openai_provider.py b/tests/llm_providers/implementations/test_openai_provider.py
index 62f622a5ca..9030317f9c 100644
--- a/tests/llm_providers/implementations/test_openai_provider.py
+++ b/tests/llm_providers/implementations/test_openai_provider.py
@@ -46,7 +46,7 @@ class TestOpenAICreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -72,7 +72,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -103,7 +103,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -126,7 +126,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -154,7 +154,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -184,7 +184,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -212,7 +212,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -240,7 +240,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -268,7 +268,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -296,7 +296,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -327,7 +327,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -355,7 +355,7 @@ class TestOpenAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -385,7 +385,7 @@ class TestOpenAICreateLLM:
raise NoSettingsContextError("No settings context")
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -400,7 +400,7 @@ class TestOpenAICreateLLM:
def test_create_llm_with_empty_api_key_raises(self):
"""Raises ValueError when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.implementations.openai.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
@@ -416,7 +416,7 @@ class TestOpenAIIsAvailable:
def test_is_available_true_when_key_exists(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-key"
@@ -426,7 +426,7 @@ class TestOpenAIIsAvailable:
def test_is_available_false_when_no_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -436,7 +436,7 @@ class TestOpenAIIsAvailable:
def test_is_available_false_when_empty_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
@@ -446,7 +446,7 @@ class TestOpenAIIsAvailable:
def test_is_available_false_on_exception(self):
"""Returns False when exception occurs."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = Exception("Settings error")
@@ -456,7 +456,7 @@ class TestOpenAIIsAvailable:
def test_is_available_with_settings_snapshot(self):
"""Uses provided settings snapshot."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-key"
snapshot = {"llm.openai.api_key": "test-key"}
@@ -517,7 +517,7 @@ class TestOpenAIListModels:
def test_list_models_uses_settings_for_api_key(self):
"""list_models() gets API key from settings."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
with patch.object(
OpenAIProvider, "list_models_for_api"
diff --git a/tests/llm_providers/implementations/test_openrouter_provider.py b/tests/llm_providers/implementations/test_openrouter_provider.py
index 1344eeead8..953d5d79a6 100644
--- a/tests/llm_providers/implementations/test_openrouter_provider.py
+++ b/tests/llm_providers/implementations/test_openrouter_provider.py
@@ -46,7 +46,7 @@ class TestOpenRouterCreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -69,7 +69,7 @@ class TestOpenRouterCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -98,7 +98,7 @@ class TestOpenRouterCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -119,7 +119,7 @@ class TestOpenRouterCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -145,7 +145,7 @@ class TestOpenRouterCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -173,7 +173,7 @@ class TestOpenRouterCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -192,7 +192,7 @@ class TestOpenRouterIsAvailable:
def test_is_available_true_when_key_exists(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-key"
@@ -202,7 +202,7 @@ class TestOpenRouterIsAvailable:
def test_is_available_false_when_no_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -212,7 +212,7 @@ class TestOpenRouterIsAvailable:
def test_is_available_false_when_empty_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
diff --git a/tests/llm_providers/implementations/test_xai_provider.py b/tests/llm_providers/implementations/test_xai_provider.py
index 46e5f3737f..785aa5871e 100644
--- a/tests/llm_providers/implementations/test_xai_provider.py
+++ b/tests/llm_providers/implementations/test_xai_provider.py
@@ -46,7 +46,7 @@ class TestXAICreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -69,7 +69,7 @@ class TestXAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -98,7 +98,7 @@ class TestXAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -119,7 +119,7 @@ class TestXAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -145,7 +145,7 @@ class TestXAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -171,7 +171,7 @@ class TestXAICreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -190,7 +190,7 @@ class TestXAIIsAvailable:
def test_is_available_true_when_key_exists(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-key"
@@ -200,7 +200,7 @@ class TestXAIIsAvailable:
def test_is_available_false_when_no_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -210,7 +210,7 @@ class TestXAIIsAvailable:
def test_is_available_false_when_empty_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
diff --git a/tests/llm_providers/test_anthropic_high_value.py b/tests/llm_providers/test_anthropic_high_value.py
index 2399b07d62..bda3496953 100644
--- a/tests/llm_providers/test_anthropic_high_value.py
+++ b/tests/llm_providers/test_anthropic_high_value.py
@@ -13,15 +13,20 @@ from local_deep_research.llm.providers.implementations.anthropic import (
)
-# Module-level patch path for the anthropic implementation
+# Module-level patch paths.
+# get_setting_from_snapshot is patched at its source module so that calls
+# from BaseLLMProvider.resolve_api_key (which lives in providers/base.py)
+# are intercepted alongside calls from anthropic.py itself.
ANTHROPIC_MOD = "local_deep_research.llm.providers.implementations.anthropic"
-GET_SETTING = f"{ANTHROPIC_MOD}.get_setting_from_snapshot"
+GET_SETTING = (
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+)
CHAT_ANTHROPIC = f"{ANTHROPIC_MOD}.ChatAnthropic"
-# Patch path for is_available(), which is inherited from OpenAICompatibleProvider
-BASE_GET_SETTING = (
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
-)
+# Patch path for is_available(), which is inherited from
+# OpenAICompatibleProvider and resolves the key via
+# BaseLLMProvider.resolve_api_key — same source-module patch point.
+BASE_GET_SETTING = GET_SETTING
def _make_setting_side_effect(overrides=None):
@@ -53,19 +58,16 @@ class TestAnthropicAPIKeyValidation:
with pytest.raises(ValueError, match="API key not configured"):
AnthropicProvider.create_llm()
- def test_whitespace_only_api_key_passes_through(self):
- """A whitespace-only API key passes the truthiness check and reaches ChatAnthropic."""
+ def test_whitespace_only_api_key_treated_as_missing(self):
+ """A whitespace-only API key is normalized as missing and raises (required provider)."""
with patch(
GET_SETTING,
side_effect=_make_setting_side_effect(
{"llm.anthropic.api_key": " "}
),
):
- with patch(CHAT_ANTHROPIC) as mock_chat:
- mock_chat.return_value = Mock()
+ with pytest.raises(ValueError, match="API key not configured"):
AnthropicProvider.create_llm(model_name="test-model")
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["anthropic_api_key"] == " "
def test_none_api_key_raises_value_error(self):
"""A None API key should raise ValueError."""
diff --git a/tests/llm_providers/test_base_provider_keys.py b/tests/llm_providers/test_base_provider_keys.py
new file mode 100644
index 0000000000..9031a0cc51
--- /dev/null
+++ b/tests/llm_providers/test_base_provider_keys.py
@@ -0,0 +1,163 @@
+"""Tests for the API-key helpers on BaseLLMProvider.
+
+Covers ``resolve_api_key`` (None vs raise vs string), the
+``resolve_api_key_or_placeholder`` companion that always returns a string,
+``build_bearer_header``, and the ``has_api_key`` predicate.
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.llm.providers.base import (
+ BaseLLMProvider,
+ OPTIONAL_API_KEY_PLACEHOLDER,
+)
+
+
+class _RequiredProvider(BaseLLMProvider):
+ """Test fixture: a provider that requires an API key."""
+
+ provider_name = "RequiredProvider"
+ api_key_setting = "test.required.api_key"
+ api_key_optional = False
+
+
+class _OptionalProvider(BaseLLMProvider):
+ """Test fixture: a provider that allows missing API key."""
+
+ provider_name = "OptionalProvider"
+ api_key_setting = "test.optional.api_key"
+ api_key_optional = True
+
+
+class _NoSettingProvider(BaseLLMProvider):
+ """Test fixture: a provider with no api_key_setting at all."""
+
+ provider_name = "NoSettingProvider"
+ api_key_setting = None
+
+
+SETTINGS = (
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+)
+
+
+def _set(value):
+ """Patch get_setting_from_snapshot to return ``value`` for any key."""
+
+ def side_effect(key, default=None, *args, **kwargs):
+ if key == _RequiredProvider.api_key_setting:
+ return value
+ if key == _OptionalProvider.api_key_setting:
+ return value
+ return default
+
+ return side_effect
+
+
+class TestResolveApiKey:
+ def test_required_with_real_key_returns_stripped(self):
+ with patch(SETTINGS, side_effect=_set(" sk-key ")):
+ assert _RequiredProvider.resolve_api_key() == "sk-key"
+
+ def test_required_with_missing_key_raises(self):
+ with patch(SETTINGS, side_effect=_set(None)):
+ with pytest.raises(ValueError, match="API key not configured"):
+ _RequiredProvider.resolve_api_key()
+
+ def test_required_with_empty_string_raises(self):
+ with patch(SETTINGS, side_effect=_set("")):
+ with pytest.raises(ValueError):
+ _RequiredProvider.resolve_api_key()
+
+ def test_required_with_whitespace_only_raises(self):
+ with patch(SETTINGS, side_effect=_set(" ")):
+ with pytest.raises(ValueError):
+ _RequiredProvider.resolve_api_key()
+
+ def test_optional_with_real_key_returns_stripped(self):
+ with patch(SETTINGS, side_effect=_set(" sk-opt ")):
+ assert _OptionalProvider.resolve_api_key() == "sk-opt"
+
+ def test_optional_with_missing_key_returns_none(self):
+ with patch(SETTINGS, side_effect=_set(None)):
+ assert _OptionalProvider.resolve_api_key() is None
+
+ def test_optional_with_whitespace_only_returns_none(self):
+ with patch(SETTINGS, side_effect=_set("\t \n")):
+ assert _OptionalProvider.resolve_api_key() is None
+
+ def test_no_setting_returns_none(self):
+ # Patching is unnecessary — api_key_setting is None so no read happens
+ assert _NoSettingProvider.resolve_api_key() is None
+
+
+class TestResolveApiKeyOrPlaceholder:
+ def test_returns_real_key_when_set(self):
+ with patch(SETTINGS, side_effect=_set("real")):
+ assert _OptionalProvider.resolve_api_key_or_placeholder() == "real"
+
+ def test_returns_placeholder_when_optional_and_missing(self):
+ with patch(SETTINGS, side_effect=_set("")):
+ assert (
+ _OptionalProvider.resolve_api_key_or_placeholder()
+ == OPTIONAL_API_KEY_PLACEHOLDER
+ )
+
+ def test_required_missing_still_raises(self):
+ # The "_or_placeholder" variant only swallows missing for OPTIONAL
+ # providers; required providers must still raise so cloud-API
+ # callers get a clear error instead of silently sending a fake key.
+ with patch(SETTINGS, side_effect=_set("")):
+ with pytest.raises(ValueError):
+ _RequiredProvider.resolve_api_key_or_placeholder()
+
+
+class TestBuildBearerHeader:
+ def test_returns_empty_when_no_key(self):
+ with patch(SETTINGS, side_effect=_set(None)):
+ assert _OptionalProvider.build_bearer_header() == {}
+
+ def test_returns_empty_for_whitespace_only(self):
+ with patch(SETTINGS, side_effect=_set(" ")):
+ assert _OptionalProvider.build_bearer_header() == {}
+
+ def test_returns_bearer_when_key_set(self):
+ with patch(SETTINGS, side_effect=_set("abc")):
+ assert _OptionalProvider.build_bearer_header() == {
+ "Authorization": "Bearer abc"
+ }
+
+ def test_strips_whitespace_in_header_value(self):
+ with patch(SETTINGS, side_effect=_set(" abc ")):
+ assert _OptionalProvider.build_bearer_header() == {
+ "Authorization": "Bearer abc"
+ }
+
+ def test_required_provider_with_no_key_returns_empty(self):
+ # ValueError from resolve_api_key is swallowed — caller can decide
+ # what to do (e.g., is_available returns False elsewhere).
+ with patch(SETTINGS, side_effect=_set(None)):
+ assert _RequiredProvider.build_bearer_header() == {}
+
+
+class TestHasApiKey:
+ def test_true_when_real_key_set(self):
+ with patch(SETTINGS, side_effect=_set("real")):
+ assert _RequiredProvider.has_api_key() is True
+
+ def test_false_when_required_and_missing(self):
+ with patch(SETTINGS, side_effect=_set(None)):
+ assert _RequiredProvider.has_api_key() is False
+
+ def test_false_when_optional_and_missing(self):
+ with patch(SETTINGS, side_effect=_set("")):
+ assert _OptionalProvider.has_api_key() is False
+
+ def test_false_when_settings_raise_unexpectedly(self):
+ # Defense-in-depth: settings infrastructure failures should not
+ # propagate from is_available()-style callers.
+ with patch(SETTINGS, side_effect=RuntimeError("settings down")):
+ assert _RequiredProvider.has_api_key() is False
+ assert _OptionalProvider.has_api_key() is False
diff --git a/tests/llm_providers/test_compute_max_tokens.py b/tests/llm_providers/test_compute_max_tokens.py
new file mode 100644
index 0000000000..b201102cd4
--- /dev/null
+++ b/tests/llm_providers/test_compute_max_tokens.py
@@ -0,0 +1,83 @@
+"""Tests for the shared max_tokens helper.
+
+Documents the 80%-of-context-window cap, the omit-the-kwarg behavior for
+unset ``llm.max_tokens`` (matches the pre-refactor live-class path), and
+the ``llm.supports_max_tokens=False`` opt-out.
+"""
+
+from unittest.mock import patch
+
+from local_deep_research.llm.providers._helpers import compute_max_tokens
+
+
+SETTINGS = (
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+)
+
+
+def _set(values):
+ """Build a side_effect that returns mapped values for known keys."""
+
+ def side_effect(key, default=None, *args, **kwargs):
+ return values.get(key, default)
+
+ return side_effect
+
+
+class TestComputeMaxTokens:
+ def test_returns_none_when_supports_max_tokens_false(self):
+ with patch(
+ SETTINGS, side_effect=_set({"llm.supports_max_tokens": False})
+ ):
+ assert compute_max_tokens() is None
+
+ def test_returns_none_when_setting_unset(self):
+ # Absent llm.max_tokens → None → caller omits the kwarg and the
+ # provider SDK default applies. This matches the pre-refactor
+ # live-class behavior; the dead chain's 100000 default exceeded
+ # the output limit of most cloud models.
+ with patch(
+ SETTINGS,
+ side_effect=_set({"llm.supports_max_tokens": True}),
+ ):
+ assert compute_max_tokens() is None
+
+ def test_caps_at_80_percent_of_context_window(self):
+ # 1000 * 0.8 == 800; min(2000, 800) == 800
+ with patch(
+ SETTINGS,
+ side_effect=_set(
+ {
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 2000,
+ }
+ ),
+ ):
+ assert compute_max_tokens(context_window_size=1000) == 800
+
+ def test_uses_setting_when_below_80_percent_cap(self):
+ with patch(
+ SETTINGS,
+ side_effect=_set(
+ {
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 500,
+ }
+ ),
+ ):
+ # 500 < 1000*0.8=800, so the setting wins
+ assert compute_max_tokens(context_window_size=1000) == 500
+
+ def test_returns_none_when_max_tokens_explicitly_none(self):
+ # Distinct from "setting unset" — explicit None means caller should
+ # omit the kwarg rather than pass the legacy default.
+ with patch(
+ SETTINGS,
+ side_effect=_set(
+ {
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": None,
+ }
+ ),
+ ):
+ assert compute_max_tokens(context_window_size=1000) is None
diff --git a/tests/llm_providers/test_custom_openai_endpoint.py b/tests/llm_providers/test_custom_openai_endpoint.py
index 1ad2d455c6..77f17b09e5 100644
--- a/tests/llm_providers/test_custom_openai_endpoint.py
+++ b/tests/llm_providers/test_custom_openai_endpoint.py
@@ -183,7 +183,7 @@ class TestCustomOpenAIEndpointCreateLLM:
mock_get_setting.side_effect = mock_get_setting_side_effect
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_base_get_setting:
mock_base_get_setting.side_effect = mock_get_setting_side_effect
diff --git a/tests/llm_providers/test_ollama_deep_coverage.py b/tests/llm_providers/test_ollama_deep_coverage.py
index 77428a211e..eac24640d8 100644
--- a/tests/llm_providers/test_ollama_deep_coverage.py
+++ b/tests/llm_providers/test_ollama_deep_coverage.py
@@ -7,7 +7,7 @@ Targets paths not exercised by test_ollama_provider.py:
- is_available: URL configured but safe_get raises unexpected exception
- is_available: safe_get returns non-200 response
- create_llm: model not found in older API format (no "models" key)
-- create_llm: context_window_size is None (no num_ctx / max_tokens added)
+- create_llm: explicit None context window resolves to the helper default
- list_models_for_api: label ":latest" stripped correctly
- requires_auth_for_models: always returns False
"""
@@ -147,24 +147,38 @@ class TestCreateLlmRequiresModelName:
class TestCreateLlmContextWindowNone:
- def test_no_num_ctx_when_context_window_none(self):
- def _get_setting(key, default=None, *args, **kwargs):
- mapping = {
- "llm.ollama.url": "http://localhost:11434",
- "llm.local_context_window_size": None,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 100000,
- }
- return mapping.get(key, default)
+ def test_explicit_none_window_resolves_to_helper_default(self):
+ """Explicit None resolves through the shared helper to its default,
+ matching what context_limit bookkeeping reports for overflow
+ detection. Previously num_ctx was omitted here (Ollama server
+ default ~2048) while context_limit claimed 8192 — overflows
+ between the two went undetected. No max_tokens kwarg: ChatOllama
+ ignores it.
+
+ Uses a real settings_snapshot (no get_setting patch) so the
+ explicit-None value actually reaches the shared helper's
+ function-local thread_settings lookup.
+ """
+ from local_deep_research.llm.providers._helpers import (
+ DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE,
+ )
- with patch(GET_SETTING, side_effect=_get_setting):
- with patch(f"{MODULE}.ChatOllama") as mock_chat:
- mock_chat.return_value = Mock()
- OllamaProvider.create_llm(model_name="gemma3:12b")
+ snapshot = {
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.local_context_window_size": None,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 100000,
+ }
+
+ with patch(f"{MODULE}.ChatOllama") as mock_chat:
+ mock_chat.return_value = Mock()
+ OllamaProvider.create_llm(
+ model_name="gemma3:12b", settings_snapshot=snapshot
+ )
- call_kwargs = mock_chat.call_args[1]
- assert "num_ctx" not in call_kwargs
- assert "max_tokens" not in call_kwargs
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["num_ctx"] == DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE
+ assert "max_tokens" not in call_kwargs
# ---------------------------------------------------------------------------
diff --git a/tests/llm_providers/test_ollama_provider.py b/tests/llm_providers/test_ollama_provider.py
index 9cfab4e3cf..e80e141855 100644
--- a/tests/llm_providers/test_ollama_provider.py
+++ b/tests/llm_providers/test_ollama_provider.py
@@ -260,3 +260,91 @@ class TestOllamaCreateLLM:
call_kwargs = mock_chat_ollama.call_args[1]
assert call_kwargs["temperature"] == 0.5
+
+
+class TestOllamaEnableThinking:
+ """Tests for the enable_thinking → reasoning kwarg port.
+
+ Previously this setting was only honored in the dead procedural
+ code in llm_config.get_llm("ollama"). After the collapse it lives
+ in OllamaProvider.create_llm so the live registered-LLM path
+ actually respects llm.ollama.enable_thinking.
+ """
+
+ @staticmethod
+ def _settings(enable_thinking_value):
+ def side_effect(key, default=None, *args, **kwargs):
+ return {
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.local_context_window_size": 8192,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "llm.ollama.enable_thinking": enable_thinking_value,
+ }.get(key, default)
+
+ return side_effect
+
+ def test_enable_thinking_true_sets_reasoning_true(self):
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot",
+ side_effect=self._settings(True),
+ ):
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+ ) as mock_chat:
+ OllamaProvider.create_llm(model_name="deepseek-r1:14b")
+ assert mock_chat.call_args[1]["reasoning"] is True
+
+ def test_enable_thinking_false_sets_reasoning_false(self):
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot",
+ side_effect=self._settings(False),
+ ):
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+ ) as mock_chat:
+ OllamaProvider.create_llm(model_name="deepseek-r1:14b")
+ assert mock_chat.call_args[1]["reasoning"] is False
+
+ def test_non_bool_enable_thinking_omits_reasoning_kwarg(self):
+ """Non-bool values (None, strings, etc.) are ignored — defensive."""
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot",
+ side_effect=self._settings("not-a-bool"),
+ ):
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+ ) as mock_chat:
+ OllamaProvider.create_llm(model_name="llama3.1:8b")
+ assert "reasoning" not in mock_chat.call_args[1]
+
+ def test_default_when_setting_absent_resolves_to_true(self):
+ """Setting is absent from snapshot → uses get_setting_from_snapshot's
+ ``True`` default → reasoning=True is passed.
+
+ This exercises the most common production path: a fresh install
+ where the user hasn't touched ``llm.ollama.enable_thinking`` and
+ the setting comes from default_settings.json (which ships True).
+ """
+
+ def side_effect(key, default=None, *args, **kwargs):
+ base = {
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.local_context_window_size": 8192,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ }
+ # Note: llm.ollama.enable_thinking deliberately absent — the
+ # caller's `default=True` should win.
+ return base.get(key, default)
+
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot",
+ side_effect=side_effect,
+ ):
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+ ) as mock_chat:
+ OllamaProvider.create_llm(model_name="deepseek-r1:14b")
+ # default=True is the fallback; isinstance(True, bool) → kwarg set
+ assert mock_chat.call_args[1].get("reasoning") is True
diff --git a/tests/llm_providers/test_openai_base.py b/tests/llm_providers/test_openai_base.py
index ced9d61847..6451cd6472 100644
--- a/tests/llm_providers/test_openai_base.py
+++ b/tests/llm_providers/test_openai_base.py
@@ -39,7 +39,7 @@ class TestOpenAICompatibleCreateLLM:
def test_create_llm_raises_without_api_key(self):
"""Raises ValueError when API key not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -62,7 +62,7 @@ class TestOpenAICompatibleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -93,7 +93,7 @@ class TestOpenAICompatibleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -114,7 +114,7 @@ class TestOpenAICompatibleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -140,7 +140,7 @@ class TestOpenAICompatibleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -168,7 +168,7 @@ class TestOpenAICompatibleCreateLLM:
return settings_map.get(key, default)
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
@@ -190,7 +190,7 @@ class TestOpenAICompatibleIsAvailable:
def test_available_with_api_key(self):
"""Returns True when API key is configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "test-api-key"
@@ -200,7 +200,7 @@ class TestOpenAICompatibleIsAvailable:
def test_not_available_without_api_key(self):
"""Returns False when API key is not configured."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
@@ -210,7 +210,7 @@ class TestOpenAICompatibleIsAvailable:
def test_not_available_with_empty_api_key(self):
"""Returns False when API key is empty string."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = ""
@@ -263,7 +263,7 @@ class TestOpenAICompatibleListModels:
def test_list_models_uses_settings(self):
"""list_models() gets API key from settings."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = "settings-key"
@@ -377,7 +377,7 @@ class TestOpenAICompatibleCreateLLMInstance:
)
call_kwargs = mock_chat_openai.call_args[1]
- assert call_kwargs["api_key"] == "dummy-key"
+ assert call_kwargs["api_key"] == "not-required"
class TestOpenAICompatibleSubclass:
diff --git a/tests/llm_providers/test_openai_base_coverage.py b/tests/llm_providers/test_openai_base_coverage.py
index fa072c69fb..90d24f4f20 100644
--- a/tests/llm_providers/test_openai_base_coverage.py
+++ b/tests/llm_providers/test_openai_base_coverage.py
@@ -67,7 +67,7 @@ class TestCreateLlm:
def test_raises_when_api_key_missing(self):
"""If api_key_setting is set but key not found, ValueError is raised."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
):
with pytest.raises(ValueError, match="not configured"):
@@ -78,7 +78,7 @@ class TestCreateLlm:
mock_llm = MagicMock()
with (
patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
),
patch(
@@ -89,12 +89,12 @@ class TestCreateLlm:
_NoKeyProvider.create_llm(model_name="test-model")
# dummy-key was passed
call_kwargs = MockChat.call_args[1]
- assert call_kwargs["api_key"] == "dummy-key"
+ assert call_kwargs["api_key"] == "not-required"
def test_uses_default_model_when_none_given(self):
"""model_name=None → raises ValueError (no silent default)."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
):
with pytest.raises(ValueError, match="model not configured"):
@@ -105,7 +105,7 @@ class TestCreateLlm:
mock_llm = MagicMock()
with (
patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
),
patch(
@@ -134,7 +134,7 @@ class TestCreateLlmInstance:
mock_llm = MagicMock()
with (
patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
),
patch(
@@ -144,7 +144,7 @@ class TestCreateLlmInstance:
):
_NoKeyProvider._create_llm_instance(model_name="test-model")
call_kwargs = MockChat.call_args[1]
- assert call_kwargs["api_key"] == "dummy-key"
+ assert call_kwargs["api_key"] == "not-required"
# ---------------------------------------------------------------------------
@@ -158,28 +158,28 @@ class TestIsAvailable:
def test_keyed_provider_available_when_key_present(self):
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value="sk-real-key",
):
assert _KeyedProvider.is_available() is True
def test_keyed_provider_not_available_when_key_missing(self):
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=None,
):
assert _KeyedProvider.is_available() is False
def test_keyed_provider_not_available_when_key_blank(self):
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value=" ",
):
assert _KeyedProvider.is_available() is False
def test_exception_during_check_returns_false(self):
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
side_effect=Exception("boom"),
):
assert _KeyedProvider.is_available() is False
@@ -207,7 +207,7 @@ class TestGetBaseUrlForModels:
def test_returns_configured_url_when_url_setting_present(self):
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
return_value="http://configured.local/v1",
):
url = _UrlSettingProvider._get_base_url_for_models()
diff --git a/tests/llm_providers/test_providers_high_value.py b/tests/llm_providers/test_providers_high_value.py
index 2f1ffd131d..166ca1f271 100644
--- a/tests/llm_providers/test_providers_high_value.py
+++ b/tests/llm_providers/test_providers_high_value.py
@@ -109,25 +109,20 @@ class TestOpenRouterEdgeCases:
"""Edge cases unique to the OpenRouter provider."""
def test_create_llm_with_whitespace_only_api_key(self):
- """Whitespace-only API key passes truthiness check (not stripped in create_llm)."""
+ """Whitespace-only API key is normalized as missing and raises (required cloud provider)."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings(
"llm.openrouter.api_key", " "
)
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat:
- mock_chat.return_value = Mock()
+ with pytest.raises(ValueError, match="API key not configured"):
OpenRouterProvider.create_llm(model_name="test-model")
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["api_key"] == " "
def test_create_llm_error_message_contains_setting_name(self):
"""Error message tells user which setting to configure."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings(
"llm.openrouter.api_key", None
@@ -151,7 +146,7 @@ class TestOpenRouterEdgeCases:
def test_create_llm_passes_max_tokens_when_configured(self):
"""max_tokens from settings is forwarded to ChatOpenAI."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings(
"llm.openrouter.api_key",
@@ -178,7 +173,7 @@ class TestXAIEdgeCases:
def test_create_llm_with_empty_string_api_key(self):
"""Empty string API key raises ValueError."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings("llm.xai.api_key", "")
with pytest.raises(ValueError, match="(?i)api key"):
@@ -187,7 +182,7 @@ class TestXAIEdgeCases:
def test_create_llm_error_message_contains_xai_setting(self):
"""Error message references the correct xAI setting key."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings("llm.xai.api_key", None)
with pytest.raises(ValueError) as exc_info:
@@ -202,7 +197,7 @@ class TestXAIEdgeCases:
def test_is_available_with_exception_in_settings(self):
"""Exception during settings retrieval returns False."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = RuntimeError("settings DB corrupted")
assert XAIProvider.is_available() is False
@@ -224,7 +219,7 @@ class TestIONOSEdgeCases:
def test_create_llm_with_none_api_key_raises(self):
"""Explicitly None API key raises ValueError."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings("llm.ionos.api_key", None)
with pytest.raises(ValueError, match="(?i)api key"):
@@ -233,7 +228,7 @@ class TestIONOSEdgeCases:
def test_create_llm_error_message_references_ionos_setting(self):
"""Error message tells the user exactly which setting is missing."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.side_effect = _cloud_settings("llm.ionos.api_key", None)
with pytest.raises(ValueError) as exc_info:
@@ -248,7 +243,7 @@ class TestIONOSEdgeCases:
def test_is_available_with_whitespace_only_key(self):
"""Whitespace-only API key is treated as unavailable."""
with patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
) as mock_gs:
mock_gs.return_value = " "
assert IONOSProvider.is_available() is False
@@ -322,8 +317,9 @@ class TestCrossProviderConsistency:
assert provider_cls.api_key_setting.startswith("llm.")
def test_local_provider_does_not_require_api_key(self):
- """LM Studio (local) should not require an API key."""
- assert LMStudioProvider.api_key_setting is None
+ """LM Studio (local) declares its setting key but treats it as optional."""
+ assert LMStudioProvider.api_key_setting == "llm.lmstudio.api_key"
+ assert LMStudioProvider.api_key_optional is True
@pytest.mark.parametrize(
"provider_cls",
diff --git a/tests/security/test_api_key_leakage.py b/tests/security/test_api_key_leakage.py
index c3853adf10..e7f779d208 100644
--- a/tests/security/test_api_key_leakage.py
+++ b/tests/security/test_api_key_leakage.py
@@ -344,7 +344,7 @@ class TestOpenAIBaseProviderKeyLeakage:
return_value=False,
):
with patch(
- "local_deep_research.llm.providers.openai_base."
+ "local_deep_research.config.thread_settings."
"get_setting_from_snapshot",
return_value=_LEAKED_KEY,
):
@@ -390,7 +390,7 @@ class TestOpenAIBaseProviderKeyLeakage:
side_effect=exc,
):
with patch(
- "local_deep_research.llm.providers.openai_base."
+ "local_deep_research.config.thread_settings."
"get_setting_from_snapshot",
return_value=_LEAKED_KEY,
):
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index 809bd47275..c565418408 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -190,6 +190,10 @@ def collect_consumed_setting_keys() -> set:
r'"([a-z][a-z0-9_.]+)"\s+in\s+settings_snapshot',
# Web route key comparison: setting.key == "key"
r'setting\.key\s*==\s*"([^"]+)"',
+ # Provider-class api_key_setting declarations (consumed indirectly
+ # via cls.resolve_api_key / cls.has_api_key on BaseLLMProvider
+ # rather than a literal get_setting_from_snapshot call).
+ r'api_key_setting\s*=\s*"([^"]+)"',
]
compiled = [re.compile(p) for p in patterns]
keys = set()
diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.py
index 3135e90f9f..efa1b09fdf 100644
--- a/tests/test_api_key_configuration.py
+++ b/tests/test_api_key_configuration.py
@@ -6,23 +6,46 @@ Tests that API keys can be set and used properly for different LLM providers.
import pytest
from unittest.mock import Mock, patch
+from langchain_core.language_models import BaseChatModel
+
from local_deep_research.config.llm_config import (
get_llm,
is_openai_available,
is_anthropic_available,
is_openai_endpoint_available,
)
-from local_deep_research.llm import clear_llm_registry
from local_deep_research.settings import SettingsManager
+def _llm_mock(**kwargs):
+ """Build a Mock that satisfies the BaseChatModel isinstance check.
+
+ The registered-LLM branch in get_llm() validates that create_llm()
+ returned a real BaseChatModel; with spec=BaseChatModel the Mock
+ passes isinstance() while still capturing call args.
+ """
+ return Mock(spec=BaseChatModel, **kwargs)
+
+
@pytest.fixture(autouse=True)
-def _clear_provider_registry():
- """Clear the LLM registry so tests use the direct-instantiation code path
- in get_llm() instead of being intercepted by auto-discovered providers."""
- clear_llm_registry()
+def _restore_auto_discovered_providers():
+ """Make sure auto-discovered providers are registered before each test.
+
+ The previous version of this fixture cleared the registry to force the
+ procedural ``if/elif`` chain in ``get_llm`` — that chain has been
+ deleted, so tests now go through the live registered-LLM path. ChatXxx
+ patches in each test target the provider class module (e.g.
+ ``...implementations.openai.ChatOpenAI``) which is where the LLM is
+ actually constructed.
+
+ ``force_refresh=True`` is required because the discovery singleton
+ short-circuits subsequent calls otherwise — and other test modules in
+ the suite may have called ``clear_llm_registry()`` between tests.
+ """
+ from local_deep_research.llm.providers import discover_providers
+
+ discover_providers(force_refresh=True)
yield
- clear_llm_registry()
class TestAPIKeyConfiguration:
@@ -123,10 +146,10 @@ class TestAPIKeyConfiguration:
def test_openai_api_key_configuration(self, settings_snapshot_with_openai):
"""Test that OpenAI API key can be configured and used."""
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Create a mock LLM instance
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_openai.return_value = mock_llm_instance
# Get LLM with OpenAI settings
@@ -146,10 +169,10 @@ class TestAPIKeyConfiguration:
):
"""Test that Anthropic API key can be configured and used."""
with patch(
- "local_deep_research.config.llm_config.ChatAnthropic"
+ "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
) as mock_anthropic:
# Create a mock LLM instance
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_anthropic.return_value = mock_llm_instance
# Get LLM with Anthropic settings
@@ -172,10 +195,10 @@ class TestAPIKeyConfiguration:
):
"""Test that OpenAI endpoint (OpenRouter) API key can be configured and used."""
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_openai:
# Create a mock LLM instance
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_openai.return_value = mock_llm_instance
# Get LLM with OpenAI endpoint settings
@@ -188,18 +211,17 @@ class TestAPIKeyConfiguration:
assert call_args.kwargs["model"] == "claude-3-opus"
assert call_args.kwargs["api_key"] == "test-openrouter-api-key"
assert (
- call_args.kwargs["openai_api_base"]
- == "https://openrouter.ai/api/v1"
+ call_args.kwargs["base_url"] == "https://openrouter.ai/api/v1"
)
assert call_args.kwargs["temperature"] == 0.5
def test_llm_execution_with_api_key(self, settings_snapshot_with_openai):
"""Test that LLM can actually be invoked with API key."""
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Create a mock LLM instance with invoke method
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_response = Mock()
mock_response.content = "Test response from OpenAI"
mock_llm_instance.invoke.return_value = mock_response
@@ -222,9 +244,9 @@ class TestAPIKeyConfiguration:
"""Test switching between different providers with their API keys."""
# Test OpenAI
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
- mock_openai.return_value = Mock()
+ mock_openai.return_value = _llm_mock()
get_llm(settings_snapshot=settings_snapshot_with_openai)
assert mock_openai.called
assert (
@@ -233,9 +255,9 @@ class TestAPIKeyConfiguration:
# Test Anthropic
with patch(
- "local_deep_research.config.llm_config.ChatAnthropic"
+ "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
) as mock_anthropic:
- mock_anthropic.return_value = Mock()
+ mock_anthropic.return_value = _llm_mock()
get_llm(settings_snapshot=settings_snapshot_with_anthropic)
assert mock_anthropic.called
assert (
@@ -245,9 +267,9 @@ class TestAPIKeyConfiguration:
# Test OpenAI Endpoint
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_openai_endpoint:
- mock_openai_endpoint.return_value = Mock()
+ mock_openai_endpoint.return_value = _llm_mock()
get_llm(settings_snapshot=settings_snapshot_with_openai_endpoint)
assert mock_openai_endpoint.called
assert (
@@ -255,7 +277,7 @@ class TestAPIKeyConfiguration:
== "test-openrouter-api-key"
)
assert (
- mock_openai_endpoint.call_args.kwargs["openai_api_base"]
+ mock_openai_endpoint.call_args.kwargs["base_url"]
== "https://openrouter.ai/api/v1"
)
@@ -266,10 +288,10 @@ class TestAPIKeyConfiguration:
from local_deep_research.api.research_functions import quick_summary
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_openai:
# Setup mock LLM
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_response = Mock()
mock_response.content = "Research summary about test topic"
mock_llm_instance.invoke.return_value = mock_response
@@ -390,10 +412,10 @@ class TestLLMIntegration:
)
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Setup mock LLM with callbacks
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_llm_instance.callbacks = []
mock_response = Mock()
mock_response.content = "Test response"
@@ -423,10 +445,10 @@ class TestLLMIntegration:
)
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Setup mock LLM that raises error
- mock_llm_instance = Mock()
+ mock_llm_instance = _llm_mock()
mock_llm_instance.invoke.side_effect = Exception(
"API rate limit exceeded"
)
@@ -455,15 +477,15 @@ class TestLLMIntegration:
)
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_openai:
- mock_openai.return_value = Mock()
+ mock_openai.return_value = _llm_mock()
get_llm(settings_snapshot=settings_snapshot)
# Verify custom URL was used
assert (
- mock_openai.call_args.kwargs["openai_api_base"]
+ mock_openai.call_args.kwargs["base_url"]
== "https://custom-llm-provider.com/v1"
)
assert mock_openai.call_args.kwargs["api_key"] == "test-key"
diff --git a/tests/test_api_key_frontend_settings.py b/tests/test_api_key_frontend_settings.py
index 7d1af21ad1..f7d8bbc419 100644
--- a/tests/test_api_key_frontend_settings.py
+++ b/tests/test_api_key_frontend_settings.py
@@ -26,11 +26,19 @@ CLOUD_PROVIDERS = [
"IONOS",
]
-# Providers with optional API keys
-OPTIONAL_API_KEY_PROVIDERS = ["OLLAMA", "OPENAI_ENDPOINT"]
+# Providers with optional API keys (key is read from settings but missing
+# is OK; falls back to a placeholder ChatOpenAI accepts).
+OPTIONAL_API_KEY_PROVIDERS = [
+ "OLLAMA",
+ "OPENAI_ENDPOINT",
+ "LMSTUDIO",
+ "LLAMACPP",
+]
-# Local providers that don't need API keys
-LOCAL_PROVIDERS_NO_KEY = ["LMSTUDIO", "LLAMACPP"]
+# Providers that have no API key concept at all (api_key_setting=None).
+# Currently empty after the LLM construction collapse — every built-in
+# provider declares a real api_key_setting now.
+LOCAL_PROVIDERS_NO_KEY: list[str] = []
class TestAPIKeyProviderMapping:
@@ -103,13 +111,29 @@ class TestAPIKeyProviderMapping:
assert OllamaProvider.api_key_setting == "llm.ollama.api_key"
- def test_lmstudio_provider_no_api_key(self):
- """Test LM Studio provider doesn't require API key."""
+ def test_lmstudio_provider_optional_api_key(self):
+ """LM Studio declares its API key setting as optional.
+
+ Older versions of LDR set ``api_key_setting = None`` on LMStudio to
+ signal "no auth needed". Now we model it as a real setting + the
+ ``api_key_optional`` flag so ``has_api_key``/``is_available``
+ semantics are uniform across providers.
+ """
from local_deep_research.llm.providers.implementations.lmstudio import (
LMStudioProvider,
)
- assert LMStudioProvider.api_key_setting is None
+ assert LMStudioProvider.api_key_setting == "llm.lmstudio.api_key"
+ assert LMStudioProvider.api_key_optional is True
+
+ def test_llamacpp_provider_optional_api_key(self):
+ """llama.cpp declares its API key setting as optional (proxy auth)."""
+ from local_deep_research.llm.providers.implementations.llamacpp import (
+ LlamaCppProvider,
+ )
+
+ assert LlamaCppProvider.api_key_setting == "llm.llamacpp.api_key"
+ assert LlamaCppProvider.api_key_optional is True
class TestAPIKeySettingsInMemory:
diff --git a/tests/test_llm_provider_integration.py b/tests/test_llm_provider_integration.py
index cc855d59df..67242e7a50 100644
--- a/tests/test_llm_provider_integration.py
+++ b/tests/test_llm_provider_integration.py
@@ -149,7 +149,7 @@ class TestLLMProviderIntegration:
) as mock_openai:
with (
patch(
- "local_deep_research.config.llm_config.ChatOpenAI",
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI",
mock_openai,
),
patch(
@@ -240,7 +240,7 @@ class TestLLMProviderIntegration:
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_openai:
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI",
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI",
mock_openai,
):
mock_openai.return_value = Mock(spec=BaseChatModel)
@@ -261,7 +261,7 @@ class TestLLMProviderIntegration:
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI",
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI",
mock_openai,
):
mock_openai.return_value = Mock(spec=BaseChatModel)
@@ -282,7 +282,7 @@ class TestLLMProviderIntegration:
"local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
) as mock_anthropic:
with patch(
- "local_deep_research.config.llm_config.ChatAnthropic",
+ "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic",
mock_anthropic,
):
mock_anthropic.return_value = Mock(
@@ -377,7 +377,7 @@ class TestLLMProviderIntegration:
settings_snapshot = settings_manager.get_all_settings()
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_openai.return_value = Mock(spec=BaseChatModel)
diff --git a/tests/test_openai_api_key_usage.py b/tests/test_openai_api_key_usage.py
index 66becf86c0..088432c23d 100644
--- a/tests/test_openai_api_key_usage.py
+++ b/tests/test_openai_api_key_usage.py
@@ -51,7 +51,7 @@ class TestOpenAIAPIKeyUsage:
def test_openai_api_key_in_llm_config(self, openai_settings_snapshot):
"""Test that OpenAI API key is properly passed to ChatOpenAI."""
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Mock the LLM instance
mock_llm_instance = Mock()
@@ -87,7 +87,7 @@ class TestOpenAIAPIKeyUsage:
os.environ, {"LDR_LLM_OPENAI_API_KEY": "sk-env-test-key"}
):
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_llm_instance = Mock()
mock_openai.return_value = mock_llm_instance
@@ -104,7 +104,7 @@ class TestOpenAIAPIKeyUsage:
"""Test that API key is properly passed through research flow to OpenAI."""
# Mock the ChatOpenAI class to verify API key is passed
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Create a mock LLM instance
mock_llm = Mock()
@@ -134,7 +134,7 @@ class TestOpenAIAPIKeyUsage:
custom_settings["llm.openai.api_key"] = "custom-azure-key"
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_llm_instance = Mock()
mock_openai.return_value = mock_llm_instance
@@ -154,7 +154,7 @@ class TestOpenAIAPIKeyUsage:
def test_openai_error_handling_invalid_key(self, openai_settings_snapshot):
"""Test error handling when OpenAI API key is invalid."""
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Simulate OpenAI authentication error
mock_openai.side_effect = Exception("Invalid API key provided")
@@ -177,7 +177,7 @@ class TestOpenAIAPIKeyUsage:
settings["llm.model"] = model
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_llm_instance = Mock()
mock_openai.return_value = mock_llm_instance
@@ -194,7 +194,7 @@ class TestOpenAIAPIKeyUsage:
streaming_settings["llm.streaming"] = True
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_llm_instance = Mock()
mock_openai.return_value = mock_llm_instance
@@ -212,7 +212,7 @@ class TestOpenAIAPIKeyUsage:
retry_settings["llm.request_timeout"] = 60
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_llm_instance = Mock()
mock_openai.return_value = mock_llm_instance
@@ -231,7 +231,7 @@ class TestOpenAIAPIKeyUsage:
org_settings["llm.openai.organization"] = "org-test123"
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
mock_llm_instance = Mock()
mock_openai.return_value = mock_llm_instance
@@ -254,7 +254,7 @@ class TestOpenAIAPIKeyUsage:
full_settings["llm.openai.organization"] = "org-123"
with patch(
- "local_deep_research.config.llm_config.ChatOpenAI"
+ "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_openai:
# Create mock LLM
mock_llm = Mock()
diff --git a/tests/web_search_engines/test_search_engine_factory_branch_coverage.py b/tests/web_search_engines/test_search_engine_factory_branch_coverage.py
index 6bb9fa09f3..b516af3988 100644
--- a/tests/web_search_engines/test_search_engine_factory_branch_coverage.py
+++ b/tests/web_search_engines/test_search_engine_factory_branch_coverage.py
@@ -460,8 +460,15 @@ class TestWrapLlmContextLimitRegisteredProvider:
class TestGetLlmAnthropicMissingKey:
- """Covers the ValueError branch when Anthropic API key is missing
- (lines 418-421 in llm_config.py)."""
+ """Covers the ValueError raised by AnthropicProvider.resolve_api_key
+ when the user hasn't configured llm.anthropic.api_key.
+
+ Pre-collapse this test exercised the procedural ``if/elif`` chain in
+ ``llm_config.get_llm`` by mocking ``is_llm_registered=False``. After
+ the dead-code deletion the chain is gone; the same error now comes
+ from ``AnthropicProvider.create_llm`` via the registered-LLM branch
+ in ``get_llm``. Test goes through the real registered path now.
+ """
def test_anthropic_no_api_key_raises(self):
settings = {
@@ -474,13 +481,15 @@ class TestGetLlmAnthropicMissingKey:
"rate_limiting.llm_enabled": False,
}
- with (
- patch(f"{_LLM_MOD}.is_llm_registered", return_value=False),
- patch(
- f"{_LLM_MOD}.get_setting_from_snapshot",
- side_effect=lambda key, default=None, settings_snapshot=None: (
- settings.get(key, default)
- ),
+ from local_deep_research.llm.providers import discover_providers
+
+ # Re-prime the registry in case a sibling test cleared it.
+ discover_providers(force_refresh=True)
+
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot",
+ side_effect=lambda key, default=None, settings_snapshot=None: (
+ settings.get(key, default)
),
):
from local_deep_research.config.llm_config import get_llm