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.

fix(llm): remove silent gemma3:12b fallback for Ollama model (#3670)

LearningCircuited8f382219c0
diff --git a/README.md b/README.md
index a4498d436e..ab32ae0a3b 100644
--- a/README.md
+++ b/README.md
@@ -442,10 +442,12 @@ Track costs, performance, and usage with detailed metrics. [Learn more →](docs
## 🤖 Supported LLMs
-### Local Models (via Ollama)
-- Llama 3, Mistral, Gemma, DeepSeek
-- LLM processing stays local (search queries still go to web)
-- No API costs
+### Local Models
+- **Ollama** — connect to its native API (default `http://localhost:11434`)
+- **LM Studio** — connect to its OpenAI-compatible server (default `http://localhost:1234/v1`)
+- **llama.cpp** — connect to `llama-server`'s OpenAI-compatible endpoint (default `http://localhost:8080/v1`); start with `llama-server -m <model.gguf>`
+- Common models: Llama 3, Mistral, Gemma, DeepSeek, Qwen
+- LLM processing stays local (search queries still go to web). No API costs.
### Cloud Models
- OpenAI (GPT-4, GPT-3.5)
@@ -455,6 +457,11 @@ Track costs, performance, and usage with detailed metrics. [Learn more →](docs
[Model Setup →](docs/env_configuration.md)
+### Upgrading from earlier versions
+
+- **`llm.model` no longer has a default.** Pre-1.7 installs auto-filled `gemma3:12b` (Ollama) when no model was configured, which silently downloaded a multi-GB binary. The field is now empty by default — pick a model in Settings → LLM, or research will fail loudly with a clear error.
+- **The `llamacpp` provider now uses HTTP instead of in-process loading.** If you previously set `llm.llamacpp_model_path` to a local `.gguf` file, that setting is no longer read. Instead, run `llama-server -m <your-model.gguf>` (it ships with every modern llama.cpp build) and the default `llm.llamacpp.url` of `http://localhost:8080/v1` will pick it up. Optional API key support is available via `llm.llamacpp.api_key` if you put `llama-server` behind an auth proxy.
+
## 📚 Documentation
### Getting Started
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 34fc96e5b9..f306bbbabd 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -113,14 +113,13 @@ They are not available in the Web UI because they are needed to start the applic
| `llm.context_window_unrestricted` | `LDR_LLM_CONTEXT_WINDOW_UNRESTRICTED` | `true` | Let cloud provider APIs manage their own token limits without a hard cap (recommended). Uncheck to enforce a specific limit via the Context Window Size setting. | LLM |
| `llm.google.api_key` | `LDR_LLM_GOOGLE_API_KEY` | `null` | API key to use for the Google Gemini provider. | SEARCH |
| `llm.ionos.api_key` | `LDR_LLM_IONOS_API_KEY` | `null` | API key to use for the IONOS AI Model Hub provider. | SEARCH |
-| `llm.llamacpp_f16_kv` | `LDR_LLM_LLAMACPP_F16_KV` | `true` | Use 16-bit floating point for LlamaCpp's key-value cache. Reduces memory usage compared to 32-bit; disable only if you need higher precision and have enough VRAM. | LLM |
-| `llm.llamacpp_model_path` | `LDR_LLM_LLAMACPP_MODEL_PATH` | `` | Path to GGUF model file relative to models directory (~/.local/share/llm_models/). For llama.cpp server connections, use 'openai_endpoint' provider instead with the server's /v1 URL. | LLM |
-| `llm.llamacpp_n_batch` | `LDR_LLM_LLAMACPP_N_BATCH` | `512` | Batch size for LlamaCpp token processing. Higher values improve inference speed but increase memory usage. Reduce if experiencing out-of-memory errors. | LLM |
-| `llm.llamacpp_n_gpu_layers` | `LDR_LLM_LLAMACPP_N_GPU_LAYERS` | `1` | Number of model layers to offload to GPU for acceleration in LlamaCpp. 0 = CPU only, higher values = more GPU usage and faster inference. Set based on your available VRAM. | LLM |
+| `llm.llamacpp.api_key` | `LDR_LLM_LLAMACPP_API_KEY` | `` | Optional API key for `llama-server` if it's behind an auth proxy. Leave empty if your llama-server has no authentication. | LLM |
+| `llm.llamacpp.url` | `LDR_LLM_LLAMACPP_URL` | `http://localhost:8080/v1` | HTTP endpoint URL where llama.cpp's `llama-server` is running. Include the full path with /v1 (default: http://localhost:8080/v1). Run `llama-server -m <model.gguf>` to start it. | LLM |
+| `llm.lmstudio.api_key` | `LDR_LLM_LMSTUDIO_API_KEY` | `` | Optional API key for LM Studio if you've enabled authentication. Leave empty for the default no-auth setup. | LLM |
| `llm.lmstudio.url` | `LDR_LLM_LMSTUDIO_URL` | `http://localhost:1234/v1` | HTTP endpoint URL where LM Studio is running locally. Include the full path (e.g., http://localhost:1234/v1 for OpenAI-compatible API format). | LLM |
| `llm.local_context_window_size` | `LDR_LLM_LOCAL_CONTEXT_WINDOW_SIZE` | `30208` | Context window size in tokens for local LLMs (Ollama, LlamaCpp, LM Studio). The default of 30208 tokens leaves more headroom for the synthesis prompt (sources + previous knowledge + instructions) so it is less likely to be truncated by the model. If you have limited VRAM, reduce this and switch to the source-based strategy instead. | LLM |
| `llm.max_tokens` | `LDR_LLM_MAX_TOKENS` | `30000` | Maximum tokens in model responses. Automatically capped at 80% of the context window size to leave room for prompt tokens. | LLM |
-| `llm.model` | `LDR_LLM_MODEL` | `gemma3:12b` | The language model to use. Available models depend on the selected provider (e.g., 'gpt-4o' for OpenAI, 'gemma:7b' for Ollama). You can type any model name supported by your provider. | LLM |
+| `llm.model` | `LDR_LLM_MODEL` | `` | The language model to use. Available models depend on the selected provider (e.g., 'gpt-4o' for OpenAI, 'gemma:7b' for Ollama). You can type any model name supported by your provider. | LLM |
| `llm.ollama.enable_thinking` | `LDR_LLM_OLLAMA_ENABLE_THINKING` | `true` | Enable thinking/reasoning mode for models like deepseek-r1 and qwen2.5. When enabled (recommended), the model performs internal reasoning for more accurate answers, but the reasoning content is automatically separated and excluded from the final response. When disabled, the model gives faster but potentially less accurate direct answers without reasoning. | LLM |
| `llm.ollama.url` | `LDR_LLM_OLLAMA_URL` | `http://localhost:11434` | HTTP endpoint URL where Ollama is running. Used to connect to local or remote Ollama instances for model inference. | LLM |
| `llm.openai.api_key` | `LDR_LLM_OPENAI_API_KEY` | `` | Your OpenAI API key for GPT models. Get one at platform.openai.com. Required when using the OpenAI provider. | LLM |
diff --git a/docs/release_notes/1.7.0.md b/docs/release_notes/1.7.0.md
new file mode 100644
index 0000000000..8f831c67fb
--- /dev/null
+++ b/docs/release_notes/1.7.0.md
@@ -0,0 +1,33 @@
+# Remove silent model defaults + migrate llamacpp to HTTP — release notes (pending)
+
+Staging notes for the silent-default removal shipped by [#3670](https://github.com/LearningCircuit/local-deep-research/pull/3670). Fold into the next tagged version's release-notes file when cutting the release.
+
+## BREAKING — `llm.model` no longer has a default
+
+Pre-1.7 installs auto-filled `gemma3:12b` (Ollama) when no model was configured, which silently downloaded a multi-GB binary on first use. The field is now empty by default — pick a model in **Settings → LLM**, or research will fail loudly with a clear `ValueError`.
+
+### Impact
+
+- Existing users with a saved `llm.model` setting are unaffected.
+- Fresh installs will see an inline warning in Settings and a clear error on research start.
+- All built-in providers (`openai`, `anthropic`, `ollama`, `lmstudio`, `llamacpp`, `google`, `openrouter`, `ionos`, `xai`) now require explicit model selection.
+
+## BREAKING — llama.cpp provider migrated from in-process to HTTP
+
+The `llamacpp` provider no longer loads `.gguf` files in-process via `llama-cpp-python`. Instead, it connects to `llama-server`'s OpenAI-compatible HTTP endpoint.
+
+- **Removed settings**: `llm.llamacpp_model_path`, `llm.llamacpp_n_batch`, `llm.llamacpp_n_gpu_layers`, `llm.llamacpp_f16_kv`
+- **New settings**: `llm.llamacpp.url` (default `http://localhost:8080/v1`), `llm.llamacpp.api_key` (optional, for auth proxies)
+- **Migration**: Run `llama-server -m <your-model.gguf>` and the default URL will pick it up. Alternatively, use the `openai_endpoint` provider pointed at the same URL.
+
+## New Features
+
+- **LM Studio optional API key**: New `llm.lmstudio.api_key` setting for LM Studio instances with authentication enabled.
+- **UI model-empty warning**: Settings page shows an inline warning (`aria-live="polite"`) when no model is selected.
+
+## Settings
+
+- `llm.model` (default `""`, was `"gemma3:12b"`) — no longer auto-fills; must be set explicitly.
+- `llm.llamacpp.url` (default `http://localhost:8080/v1`) — HTTP endpoint for `llama-server`.
+- `llm.llamacpp.api_key` (default `""`) — optional API key for llama-server behind an auth proxy.
+- `llm.lmstudio.api_key` (default `""`) — optional API key for LM Studio with auth enabled.
diff --git a/src/local_deep_research/config/constants.py b/src/local_deep_research/config/constants.py
index 4aca1bfde7..aeddad77dc 100644
--- a/src/local_deep_research/config/constants.py
+++ b/src/local_deep_research/config/constants.py
@@ -2,6 +2,7 @@
DEFAULT_OLLAMA_URL = "http://localhost:11434"
DEFAULT_LMSTUDIO_URL = "http://localhost:1234/v1"
+DEFAULT_LLAMACPP_URL = "http://localhost:8080/v1"
# Cap on how many results the LLM relevance filter keeps per search-engine
# call. Must match the ``search.max_filtered_results`` entry in
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index fbf52100c5..3725e70beb 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -9,7 +9,11 @@ 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_OLLAMA_URL, DEFAULT_LMSTUDIO_URL
+from .constants import (
+ DEFAULT_LLAMACPP_URL,
+ DEFAULT_LMSTUDIO_URL,
+ DEFAULT_OLLAMA_URL,
+)
# Import providers module to trigger auto-discovery
try:
@@ -107,36 +111,19 @@ def is_lmstudio_available(settings_snapshot=None):
def is_llamacpp_available(settings_snapshot=None):
- """Check if LlamaCpp is available and properly configured.
+ """Check if llama.cpp's HTTP server is reachable.
- Checks that the library is installed and a model path is configured.
- For llama.cpp server connections, use 'openai_endpoint' provider instead.
+ Talks to `llama-server`'s OpenAI-compatible endpoint (no in-process
+ `llama-cpp-python` binding required).
"""
try:
- # Import check
- from langchain_community.llms import LlamaCpp # noqa: F401
-
- # Check if model path is configured and looks valid
- # Note: For llama.cpp server connections, use 'openai_endpoint' provider instead
- model_path_str = get_setting_from_snapshot(
- "llm.llamacpp_model_path",
- default=None,
- settings_snapshot=settings_snapshot,
- )
-
- # If no path configured, LlamaCpp is not available
- if not model_path_str:
- return False
-
- # Path is configured, actual validation happens when model loads
- return True
+ from ..llm.providers.implementations.llamacpp import LlamaCppProvider
+ return LlamaCppProvider.is_available(settings_snapshot)
except ImportError:
- # LlamaCpp library not installed
return False
-
except Exception:
- logger.debug("Error checking LlamaCpp availability", exc_info=True)
+ logger.debug("Error checking llama.cpp availability", exc_info=True)
return False
@@ -276,7 +263,7 @@ def get_llm(
# Use database values for parameters if not provided
if model_name is None:
model_name = get_setting_from_snapshot(
- "llm.model", "gemma3:12b", settings_snapshot=settings_snapshot
+ "llm.model", "", settings_snapshot=settings_snapshot
)
if temperature is None:
temperature = get_setting_from_snapshot(
@@ -349,6 +336,19 @@ def get_llm(
raise ValueError(
f"Invalid provider: {provider}. Must be one of: {VALID_PROVIDERS}"
)
+
+ # Require an explicit model for built-in providers. Mirrors the
+ # API-key-not-configured pattern in openai_base.py and the URL-not-
+ # configured pattern in providers/implementations/ollama.py: no silent
+ # substitution to a hardcoded default model.
+ if not model_name or not model_name.strip():
+ logger.error("llm.model is not configured (empty/None after lookup)")
+ raise ValueError(
+ "LLM model not configured. Please open Settings, choose an LLM "
+ "provider, and select a model name (e.g. 'gpt-4o-mini' for "
+ "OpenAI, 'claude-3-5-sonnet-20241022' for Anthropic, "
+ "'llama3.1:8b' for Ollama). The 'llm.model' setting is required."
+ )
logger.info(
f"Getting LLM with model: {model_name}, temperature: {temperature}, provider: {provider}"
)
@@ -641,10 +641,18 @@ def get_llm(
)
# Use URL as-is (default already includes /v1)
base_url = normalize_url(lmstudio_url)
+ # Optional API key for LM Studio with auth enabled. Empty falls back
+ # to a placeholder ChatOpenAI accepts; a no-auth LM Studio ignores it.
+ lmstudio_auth = ( # gitleaks:allow
+ get_setting_from_snapshot(
+ "llm.lmstudio.api_key", "", settings_snapshot=settings_snapshot
+ )
+ or "lm-studio" # gitleaks:allow
+ )
llm = ChatOpenAI( # type: ignore[assignment, call-arg, arg-type]
model=model_name,
- api_key="lm-studio", # LM Studio doesn't require a real API key # pragma: allowlist secret
+ api_key=lmstudio_auth, # gitleaks:allow
base_url=base_url,
temperature=temperature,
max_tokens=max_tokens, # Use calculated max_tokens based on context size
@@ -657,108 +665,31 @@ def get_llm(
settings_snapshot=settings_snapshot,
)
- # Update the llamacpp section in get_llm function
elif provider == "llamacpp":
- # Import LlamaCpp
- from langchain_community.llms import LlamaCpp
-
- # Note: For llama.cpp server connections, use 'openai_endpoint' provider
- # with the server's /v1 URL (e.g., 'http://localhost:8000/v1')
-
- # Get LlamaCpp model path from settings
- model_path = get_setting_from_snapshot(
- "llm.llamacpp_model_path", settings_snapshot=settings_snapshot
- )
- if not model_path:
- logger.error("llamacpp_model_path not set in settings")
- raise ValueError(
- "LlamaCpp model path not configured. Either:\n"
- "1. Set 'llm.llamacpp_model_path' to your .gguf file path, or\n"
- "2. For llama.cpp server connections, use 'openai_endpoint' provider "
- "with the server's /v1 endpoint (e.g., 'http://localhost:8000/v1')"
- )
-
- # Validate model path for security FIRST using centralized validator
- # This MUST happen before any filesystem operations on user input
- from ..security.path_validator import PathValidator
- from .paths import get_models_directory
-
- try:
- validated_path = PathValidator.validate_model_path(model_path)
- except ValueError as e:
- error_msg = str(e)
- # If the path is not a file, try to provide helpful directory listing
- # Only do this after path has passed security validation (safe_join check)
- if "not a file" in error_msg:
- helpful_message = None
- try:
- model_root = str(get_models_directory())
- safe_path = PathValidator.validate_safe_path(
- model_path, model_root, allow_absolute=False
- )
- if safe_path and safe_path.is_dir():
- gguf_files = list(safe_path.glob("*.gguf"))
- if gguf_files:
- files_list = ", ".join(
- f.name for f in gguf_files[:5]
- )
- if len(gguf_files) > 5:
- files_list += (
- f" (and {len(gguf_files) - 5} more)"
- )
- suggestion = f"Found .gguf files: {files_list}"
- else:
- suggestion = (
- "No .gguf files found in this directory"
- )
- helpful_message = (
- f"Model path is a directory, not a file: {model_path}\n"
- f"Please specify the full path to a .gguf model file.\n"
- f"{suggestion}"
- )
- except ValueError:
- pass # Secondary validation failed, use original error
- if helpful_message:
- raise ValueError(helpful_message) from e
- logger.exception("Model path validation failed")
- raise
-
- model_path = str(validated_path)
-
- # Validate file extension - LlamaCpp requires .gguf or .bin files
- # Safe to use validated_path here since it passed security validation
- if validated_path.suffix.lower() not in (".gguf", ".bin"):
- raise ValueError(
- f"Invalid model file extension: {validated_path.suffix}\n"
- f"LlamaCpp requires .gguf or .bin model files.\n"
- f"File: {validated_path.name}"
- )
-
- # Get additional LlamaCpp parameters
- n_gpu_layers = get_setting_from_snapshot(
- "llm.llamacpp_n_gpu_layers",
- 1,
+ # 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,
)
- n_batch = get_setting_from_snapshot(
- "llm.llamacpp_n_batch", 512, settings_snapshot=settings_snapshot
- )
- f16_kv = get_setting_from_snapshot(
- "llm.llamacpp_f16_kv", True, 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
)
- # Create LlamaCpp instance
- llm = LlamaCpp(
- model_path=model_path,
+ 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, # Use calculated max_tokens
- n_gpu_layers=n_gpu_layers,
- n_batch=n_batch,
- f16_kv=f16_kv,
- n_ctx=context_window_size, # Set context window size directly (None = use default)
- verbose=True,
+ max_tokens=max_tokens,
)
-
return wrap_llm_without_think_tags(
llm,
research_id=research_id,
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 65cb762d5e..e47cfff989 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -338,60 +338,46 @@
"value": true,
"visible": false
},
- "llm.llamacpp_f16_kv": {
+ "llm.llamacpp.api_key": {
"category": null,
- "description": "Use 16-bit floating point for LlamaCpp's key-value cache. Reduces memory usage compared to 32-bit; disable only if you need higher precision and have enough VRAM.",
+ "description": "Optional API key for `llama-server` if it's behind an auth proxy. Leave empty if your llama-server has no authentication.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Llamacpp F16 Kv",
+ "name": "Llamacpp API Key",
"options": null,
"step": null,
"type": "LLM",
- "ui_element": "checkbox",
- "value": true,
+ "ui_element": "password",
+ "value": "",
"visible": true
},
- "llm.llamacpp_model_path": {
+ "llm.llamacpp.url": {
"category": null,
- "description": "Path to GGUF model file relative to models directory (~/.local/share/llm_models/). For llama.cpp server connections, use 'openai_endpoint' provider instead with the server's /v1 URL.",
+ "description": "HTTP endpoint URL where llama.cpp's `llama-server` is running. Include the full path with /v1 (default: http://localhost:8080/v1). Run `llama-server -m <model.gguf>` to start it.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Llamacpp Model Path",
+ "name": "Llamacpp Url",
"options": null,
"step": null,
"type": "LLM",
"ui_element": "text",
- "value": "",
- "visible": true
- },
- "llm.llamacpp_n_batch": {
- "category": null,
- "description": "Batch size for LlamaCpp token processing. Higher values improve inference speed but increase memory usage. Reduce if experiencing out-of-memory errors.",
- "editable": true,
- "max_value": null,
- "min_value": 1,
- "name": "Llamacpp N Batch",
- "options": null,
- "step": null,
- "type": "LLM",
- "ui_element": "number",
- "value": 512,
+ "value": "http://localhost:8080/v1",
"visible": true
},
- "llm.llamacpp_n_gpu_layers": {
+ "llm.lmstudio.api_key": {
"category": null,
- "description": "Number of model layers to offload to GPU for acceleration in LlamaCpp. 0 = CPU only, higher values = more GPU usage and faster inference. Set based on your available VRAM.",
+ "description": "Optional API key for LM Studio if you've enabled authentication. Leave empty for the default no-auth setup.",
"editable": true,
"max_value": null,
- "min_value": 0,
- "name": "Llamacpp N Gpu Layers",
+ "min_value": null,
+ "name": "Lmstudio API Key",
"options": null,
"step": null,
"type": "LLM",
- "ui_element": "number",
- "value": 1,
+ "ui_element": "password",
+ "value": "",
"visible": true
},
"llm.lmstudio.url": {
@@ -518,7 +504,7 @@
"step": null,
"type": "LLM",
"ui_element": "select",
- "value": "gemma3:12b",
+ "value": "",
"visible": true
},
"llm.openai_endpoint.url": {
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index 739ee3fc1d..8ff8c95344 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -272,9 +272,7 @@ def start_followup():
)
# Normalize provider to lowercase canonical form
model_provider = normalize_provider(model_provider)
- model = settings_snapshot.get("llm.model", {}).get(
- "value", "gemma3:12b"
- )
+ model = settings_snapshot.get("llm.model", {}).get("value", "")
search_engine = settings_snapshot.get("search.tool", {}).get(
"value", "searxng"
)
diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.py
index 1c0310c924..f3f4e6a21f 100644
--- a/src/local_deep_research/llm/providers/implementations/anthropic.py
+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py
@@ -18,7 +18,7 @@ class AnthropicProvider(OpenAICompatibleProvider):
provider_name = "Anthropic"
api_key_setting = "llm.anthropic.api_key"
- default_model = "claude-3-sonnet-20240229"
+ default_model = "" # User must explicitly pick a model — no silent fallback
default_base_url = "https://api.anthropic.com/v1"
# Metadata for auto-discovery
@@ -57,9 +57,14 @@ class AnthropicProvider(OpenAICompatibleProvider):
f"Please set {cls.api_key_setting} in settings."
)
- # Use default model if none specified
- if not model_name:
- model_name = cls.default_model
+ # Require an explicit model — no silent fallback to a hardcoded default.
+ if not model_name or not model_name.strip():
+ logger.error(f"{cls.provider_name} model name not provided")
+ raise ValueError(
+ f"{cls.provider_name} model not configured. "
+ f"Please set llm.model in settings "
+ f"(e.g. 'claude-3-5-sonnet-20241022')."
+ )
# Build Anthropic-specific parameters
anthropic_params = {
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 dd55412286..da6ab0db9d 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
@@ -18,7 +18,7 @@ class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
api_key_setting = "llm.openai_endpoint.api_key"
url_setting = "llm.openai_endpoint.url" # type: ignore[assignment] # Settings key for URL
default_base_url = "https://api.openai.com/v1"
- default_model = "gpt-3.5-turbo"
+ default_model = "" # User must explicitly pick a model — no silent fallback
# Metadata for auto-discovery
provider_key = "OPENAI_ENDPOINT"
diff --git a/src/local_deep_research/llm/providers/implementations/google.py b/src/local_deep_research/llm/providers/implementations/google.py
index 99d335623b..f50371940b 100644
--- a/src/local_deep_research/llm/providers/implementations/google.py
+++ b/src/local_deep_research/llm/providers/implementations/google.py
@@ -16,7 +16,7 @@ class GoogleProvider(OpenAICompatibleProvider):
provider_name = "Google Gemini"
api_key_setting = "llm.google.api_key"
default_base_url = "https://generativelanguage.googleapis.com/v1beta/openai"
- default_model = "gemini-1.5-flash"
+ default_model = "" # User must explicitly pick a model — no silent fallback
# Metadata for auto-discovery
provider_key = "GOOGLE"
diff --git a/src/local_deep_research/llm/providers/implementations/ionos.py b/src/local_deep_research/llm/providers/implementations/ionos.py
index 643017a94c..c9237925a3 100644
--- a/src/local_deep_research/llm/providers/implementations/ionos.py
+++ b/src/local_deep_research/llm/providers/implementations/ionos.py
@@ -9,7 +9,7 @@ class IONOSProvider(OpenAICompatibleProvider):
provider_name = "IONOS AI Model Hub"
api_key_setting = "llm.ionos.api_key"
default_base_url = "https://openai.inference.de-txl.ionos.com/v1"
- default_model = "meta-llama/llama-3.2-3b-instruct" # Default open model
+ default_model = "" # User must explicitly pick a model — no silent fallback
# Metadata for auto-discovery
provider_key = "IONOS"
diff --git a/src/local_deep_research/llm/providers/implementations/llamacpp.py b/src/local_deep_research/llm/providers/implementations/llamacpp.py
new file mode 100644
index 0000000000..aa9a193c2f
--- /dev/null
+++ b/src/local_deep_research/llm/providers/implementations/llamacpp.py
@@ -0,0 +1,87 @@
+"""llama.cpp LLM provider for Local Deep Research.
+
+Talks to llama.cpp's OpenAI-compatible HTTP server (`llama-server`) instead
+of loading models in-process via `llama-cpp-python`. Modeled after
+`LMStudioProvider`. For setups that need API key auth or non-default URLs
+beyond a single endpoint, use the `openai_endpoint` provider directly.
+"""
+
+from ....config.constants import DEFAULT_LLAMACPP_URL
+from ....utilities.url_utils import normalize_url
+from ..openai_base import OpenAICompatibleProvider
+
+
+class LlamaCppProvider(OpenAICompatibleProvider):
+ """llama.cpp provider using its OpenAI-compatible HTTP endpoint.
+
+ Run `llama-server -m <model.gguf>` (port 8080 by default) and point
+ `llm.llamacpp.url` at the server's `/v1` endpoint.
+ """
+
+ 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]
+ 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
+
+ # Metadata for auto-discovery
+ provider_key = "LLAMACPP"
+ company_name = "llama.cpp"
+ is_cloud = False # Local provider
+
+ @classmethod
+ def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
+ """Create a ChatOpenAI client pointed at llama-server."""
+ from ....config.thread_settings import get_setting_from_snapshot
+
+ settings_snapshot = kwargs.get("settings_snapshot")
+
+ url = get_setting_from_snapshot(
+ "llm.llamacpp.url",
+ 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
+
+ return super()._create_llm_instance(model_name, temperature, **kwargs)
+
+ @classmethod
+ def is_available(cls, settings_snapshot=None):
+ """Check whether llama-server is reachable."""
+ try:
+ from ....config.thread_settings import get_setting_from_snapshot
+ from ....security import safe_get
+
+ url = get_setting_from_snapshot(
+ "llm.llamacpp.url",
+ cls.default_base_url,
+ settings_snapshot=settings_snapshot,
+ )
+ base_url = normalize_url(url)
+ response = safe_get(
+ f"{base_url}/models",
+ timeout=1,
+ allow_localhost=True,
+ allow_private_ips=True,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+ @classmethod
+ def requires_auth_for_models(cls):
+ """llama-server doesn't require authentication for listing models."""
+ return False
diff --git a/src/local_deep_research/llm/providers/implementations/lmstudio.py b/src/local_deep_research/llm/providers/implementations/lmstudio.py
index b614384217..9187705f88 100644
--- a/src/local_deep_research/llm/providers/implementations/lmstudio.py
+++ b/src/local_deep_research/llm/providers/implementations/lmstudio.py
@@ -12,10 +12,15 @@ class LMStudioProvider(OpenAICompatibleProvider):
"""
provider_name = "LM Studio"
- api_key_setting = None # type: ignore[assignment] # LM Studio doesn't need a real API key
+ # 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]
url_setting = "llm.lmstudio.url" # type: ignore[assignment] # Settings key for URL
default_base_url = DEFAULT_LMSTUDIO_URL
- default_model = "local-model" # User should specify their loaded model
+ default_model = (
+ "" # User must specify the model they loaded — no silent fallback
+ )
# Metadata for auto-discovery
provider_key = "LMSTUDIO"
@@ -35,12 +40,19 @@ class LMStudioProvider(OpenAICompatibleProvider):
cls.default_base_url,
settings_snapshot=settings_snapshot,
)
+ api_key = get_setting_from_snapshot(
+ "llm.lmstudio.api_key",
+ "",
+ settings_snapshot=settings_snapshot,
+ )
# Use URL as-is (user should provide complete URL including /v1 if needed)
kwargs["base_url"] = normalize_url(lmstudio_url)
- # LM Studio doesn't require a real API key, just use a clearly fake placeholder
- kwargs["api_key"] = "not-required" # pragma: allowlist secret
+ # 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
# Use parent's create_llm but bypass API key check
return super()._create_llm_instance(model_name, temperature, **kwargs)
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index 49a7edb9a9..1af14fe7a2 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -17,7 +17,7 @@ class OllamaProvider(BaseLLMProvider):
"""
provider_name = "Ollama"
- default_model = "gemma3:12b"
+ default_model = ""
api_key_setting = "llm.ollama.api_key" # Optional API key for authenticated Ollama instances
url_setting = "llm.ollama.url" # URL setting for model listing
@@ -108,9 +108,17 @@ class OllamaProvider(BaseLLMProvider):
"""
settings_snapshot = kwargs.get("settings_snapshot")
- # Use default model if none specified
- if not model_name:
- model_name = cls.default_model
+ # Defense-in-depth: callers using the central get_llm() already get a
+ # clear ValueError when llm.model is unset. This second check covers
+ # direct callers of OllamaProvider.create_llm() (programmatic API,
+ # custom registrations) so they don't get a confusing langchain
+ # error about a model that wasn't actually requested.
+ if not model_name or not model_name.strip():
+ logger.error("Ollama model name not provided to create_llm()")
+ raise ValueError(
+ "Ollama model not configured. Please set llm.model in "
+ "settings (e.g. 'llama3.1:8b', 'qwen2.5:14b')."
+ )
# Use the configurable Ollama base URL
raw_base_url = get_setting_from_snapshot(
diff --git a/src/local_deep_research/llm/providers/implementations/openai.py b/src/local_deep_research/llm/providers/implementations/openai.py
index beb27a1025..7a786aea1c 100644
--- a/src/local_deep_research/llm/providers/implementations/openai.py
+++ b/src/local_deep_research/llm/providers/implementations/openai.py
@@ -18,7 +18,7 @@ class OpenAIProvider(OpenAICompatibleProvider):
provider_name = "OpenAI"
api_key_setting = "llm.openai.api_key"
- default_model = "gpt-3.5-turbo"
+ default_model = "" # User must explicitly pick a model — no silent fallback
default_base_url = "https://api.openai.com/v1"
# Metadata for auto-discovery
@@ -57,9 +57,13 @@ class OpenAIProvider(OpenAICompatibleProvider):
f"Please set {cls.api_key_setting} in settings."
)
- # Use default model if none specified
- if not model_name:
- model_name = cls.default_model
+ # Require an explicit model — no silent fallback to a hardcoded default.
+ if not model_name or not model_name.strip():
+ logger.error(f"{cls.provider_name} model name not provided")
+ raise ValueError(
+ f"{cls.provider_name} model not configured. "
+ f"Please set llm.model in settings (e.g. 'gpt-4o-mini')."
+ )
# Build OpenAI-specific parameters
openai_params = {
diff --git a/src/local_deep_research/llm/providers/implementations/openrouter.py b/src/local_deep_research/llm/providers/implementations/openrouter.py
index df38ab8a87..0b82332a08 100644
--- a/src/local_deep_research/llm/providers/implementations/openrouter.py
+++ b/src/local_deep_research/llm/providers/implementations/openrouter.py
@@ -14,9 +14,7 @@ class OpenRouterProvider(OpenAICompatibleProvider):
provider_name = "OpenRouter"
api_key_setting = "llm.openrouter.api_key"
default_base_url = "https://openrouter.ai/api/v1"
- default_model = (
- "meta-llama/llama-3.2-3b-instruct:free" # A free model as default
- )
+ default_model = "" # User must explicitly pick a model — no silent fallback
# Metadata for auto-discovery
provider_key = "OPENROUTER"
diff --git a/src/local_deep_research/llm/providers/implementations/xai.py b/src/local_deep_research/llm/providers/implementations/xai.py
index 741202deba..5a451d2b73 100644
--- a/src/local_deep_research/llm/providers/implementations/xai.py
+++ b/src/local_deep_research/llm/providers/implementations/xai.py
@@ -12,7 +12,7 @@ class XAIProvider(OpenAICompatibleProvider):
provider_name = "xAI Grok"
api_key_setting = "llm.xai.api_key"
default_base_url = "https://api.x.ai/v1"
- default_model = "grok-beta"
+ default_model = "" # User must explicitly pick a model — no silent fallback
# Metadata for auto-discovery
provider_key = "XAI"
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 2ce4a73c98..9a45d0c1b6 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -23,7 +23,9 @@ class OpenAICompatibleProvider(BaseLLMProvider):
api_key_setting = "llm.openai_endpoint.api_key" # Settings key for API key
url_setting = None # Settings key for URL (e.g., "llm.lmstudio.url")
default_base_url = "https://api.openai.com/v1" # Default endpoint URL
- default_model = "gpt-3.5-turbo" # Default model if none specified
+ default_model = (
+ "" # User must explicitly configure llm.model — no silent fallback
+ )
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
@@ -62,9 +64,13 @@ class OpenAICompatibleProvider(BaseLLMProvider):
# Provider doesn't require API key (e.g., LM Studio)
api_key = kwargs.get("api_key", "dummy-key")
- # Use default model if none specified
- if not model_name:
- model_name = cls.default_model
+ # Require an explicit model — no silent fallback to a hardcoded default.
+ if not model_name or not model_name.strip():
+ logger.error(f"{cls.provider_name} model name not provided")
+ raise ValueError(
+ f"{cls.provider_name} model not configured. "
+ f"Please set llm.model in settings."
+ )
# Get endpoint URL (can be overridden in kwargs for flexibility)
base_url = kwargs.get("base_url", cls.default_base_url)
@@ -141,9 +147,13 @@ class OpenAICompatibleProvider(BaseLLMProvider):
"""
settings_snapshot = kwargs.get("settings_snapshot")
- # Use default model if none specified
- if not model_name:
- model_name = cls.default_model
+ # Require an explicit model — no silent fallback to a hardcoded default.
+ if not model_name or not model_name.strip():
+ logger.error(f"{cls.provider_name} model name not provided")
+ raise ValueError(
+ f"{cls.provider_name} model not configured. "
+ f"Please set llm.model in settings."
+ )
# Get endpoint URL (can be overridden in kwargs for flexibility)
base_url = kwargs.get("base_url", cls.default_base_url)
diff --git a/src/local_deep_research/news/recommender/topic_based.py b/src/local_deep_research/news/recommender/topic_based.py
index 674aa683c8..ddc80338aa 100644
--- a/src/local_deep_research/news/recommender/topic_based.py
+++ b/src/local_deep_research/news/recommender/topic_based.py
@@ -225,7 +225,18 @@ class TopicBasedRecommender(BaseRecommender):
from ...config.llm_config import get_llm
from ...config.search_config import get_search
- llm = get_llm()
+ try:
+ llm = get_llm()
+ except ValueError:
+ # Configuration not set (e.g. llm.model empty). User issue,
+ # not a runtime fault. Log a single concise warning per
+ # scheduled topic — no stack trace, since this scheduler
+ # runs repeatedly and we don't want to spam the log.
+ logger.warning(
+ f"Skipping news recommendation for topic '{topic}': "
+ "LLM not configured. Set llm.model in Settings."
+ )
+ return None
search = get_search(llm_instance=llm)
search_system = AdvancedSearchSystem(
llm=llm, search=search, strategy_name="news"
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 1c27be562f..c1d93156f6 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -440,7 +440,24 @@ def check_ollama_model():
# Get model name from request or use config default
model_name = request.args.get("model")
if not model_name:
- model_name = llm_config.get("model", "gemma3:12b")
+ model_name = llm_config.get("model", "")
+
+ if not model_name:
+ logger.warning(
+ "/api/check/ollama_model called with no model name and "
+ "llm.model is not configured"
+ )
+ return jsonify(
+ {
+ "available": False,
+ "model": "",
+ "message": (
+ "Model is required. Pass ?model=<name> in the "
+ "query string, or configure llm.model in Settings."
+ ),
+ "error_type": "model_not_configured",
+ }
+ ), 400
# Log which model we're checking for debugging
logger.info(f"Checking availability of Ollama model: {model_name}")
@@ -599,7 +616,7 @@ def check_ollama_model():
"model": (
model_name
if "model_name" in locals()
- else llm_config.get("model", "gemma3:12b")
+ else llm_config.get("model", "")
),
"message": "An internal error occurred while checking the model.",
"error_type": "exception",
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 4ec6f11965..d2bd18f962 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -371,7 +371,7 @@ def save_all_settings(db_session=None, settings_manager=None):
else:
# Use default or null for other types
if key == "llm.model":
- value = "gemma3:12b"
+ value = ""
elif key == "llm.provider":
value = "ollama"
elif key == "search.tool":
@@ -1979,7 +1979,7 @@ def fix_corrupted_settings(db_session=None):
# Try to find a matching default setting based on key
if setting.key.startswith("llm."):
if setting.key == "llm.model":
- default_value = "gemma3:12b"
+ default_value = ""
elif setting.key == "llm.provider":
default_value = "ollama"
elif setting.key == "llm.temperature":
diff --git a/src/local_deep_research/web/static/css/settings.css b/src/local_deep_research/web/static/css/settings.css
index 487d78e3da..e459ce6f9a 100644
--- a/src/local_deep_research/web/static/css/settings.css
+++ b/src/local_deep_research/web/static/css/settings.css
@@ -618,6 +618,18 @@
text-decoration: underline;
}
+.ldr-input-warning {
+ display: block;
+ font-size: 0.85rem;
+ color: var(--warning-color);
+ margin-top: 0.3rem;
+ line-height: 1.3;
+}
+
+.ldr-input-warning i {
+ margin-right: 0.4rem;
+}
+
.ldr-checkbox-group {
display: flex;
align-items: center;
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 60d6eaf168..809d86d9aa 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -562,6 +562,19 @@
}
}
+ /**
+ * Toggle the inline "no model selected" warning shown under the
+ * Language Model dropdown. The element itself lives in the settings
+ * template; this just flips its visibility.
+ * @param {boolean} isEmpty - true when the model field is empty
+ */
+ function updateModelEmptyWarning(isEmpty) {
+ const warningEl = document.getElementById('llm.model-empty-warning');
+ if (!warningEl) return;
+ warningEl.style.display = isEmpty ? '' : 'none';
+ warningEl.setAttribute('aria-hidden', isEmpty ? 'false' : 'true');
+ }
+
/**
* Schedule a debounced save operation
* @param {Object} formData - The form data to save
@@ -1031,16 +1044,13 @@
// Define settings that should only appear in specific tabs
const tabSpecificSettings = {
'llm': [
- 'llamacpp_f16_kv',
'provider',
'model',
'temperature',
'max_tokens',
'openai_endpoint_url',
'lmstudio_url',
- 'llamacpp_model_path',
- 'llamacpp_n_batch',
- 'llamacpp_n_gpu_layers',
+ 'llamacpp_url',
'api_key'
],
'search': [
@@ -1081,7 +1091,7 @@
// Priority settings that should appear at the top of each tab
const prioritySettings = {
'app': ['enable_web', 'enable_notifications', 'web_interface', 'theme', 'default_theme', 'dark_mode', 'debug', 'host', 'port', 'warnings'],
- 'llm': ['provider', 'model', 'temperature', 'max_tokens', 'api_key', 'openai_endpoint_url', 'lmstudio_url', 'llamacpp_model_path'],
+ 'llm': ['provider', 'model', 'temperature', 'max_tokens', 'api_key', 'openai_endpoint_url', 'lmstudio_url', 'llamacpp_url'],
'search': ['tool', 'iterations', 'questions_per_iteration', 'max_results', 'region', 'search_engine'],
'report': ['knowledge_accumulation']
};
@@ -3413,7 +3423,7 @@
// Get current settings from hidden inputs
const currentProvider = providerHiddenInput.value || 'ollama'
- const currentModel = modelHiddenInput.value || 'gemma3:12b';
+ const currentModel = modelHiddenInput.value || '';
SafeLogger.log('Current settings:', { provider: currentProvider, model: currentModel });
@@ -3524,6 +3534,19 @@
modelHiddenInput.addEventListener('change', handleInputChange);
SafeLogger.log('Added change listener to hidden model input:', modelHiddenInput.id);
// --- END OF ADDED LISTENER ---
+
+ // Inline "no model selected" warning — toggled live by
+ // both the hidden input (dropdown selection) and the
+ // visible input (free-text typing).
+ updateModelEmptyWarning(!modelHiddenInput.value || !modelHiddenInput.value.trim());
+ modelHiddenInput.addEventListener('change', () => {
+ updateModelEmptyWarning(!modelHiddenInput.value || !modelHiddenInput.value.trim());
+ });
+ if (settingsModelInput) {
+ settingsModelInput.addEventListener('input', () => {
+ updateModelEmptyWarning(!settingsModelInput.value || !settingsModelInput.value.trim());
+ });
+ }
}
// Set up refresh button
@@ -4268,8 +4291,19 @@
SafeLogger.log(`Current model ${currentModel} invalid for provider ${providerUpper}. Setting to first available: ${firstModel}`);
modelHiddenInput.value = firstModel;
modelInput.value = filteredModels[0].label || firstModel;
+ // Direct value-set bypasses change listener, so update
+ // the empty-warning explicitly to keep UI in sync.
+ updateModelEmptyWarning(!firstModel || !firstModel.trim());
}
}
+ // Mirror the backup path: if no models are available for this
+ // provider, clear the hidden input and surface the warning so
+ // the UI doesn't keep showing a now-invalid stored value.
+ if (filteredModels.length === 0 && modelHiddenInput) {
+ modelHiddenInput.value = '';
+ if (modelInput) modelInput.value = '';
+ updateModelEmptyWarning(true);
+ }
// If dropdown was open, ensure it stays open
if (isDropdownOpen) {
@@ -4323,10 +4357,12 @@
const firstModel = filteredModels[0].value;
SafeLogger.log(`Current model ${currentModel} invalid for provider ${providerUpper}. Setting to first available: ${firstModel}`);
modelDropdownControl.setValue(firstModel, false); // DON'T fire event, avoid loop
+ updateModelEmptyWarning(!firstModel || !firstModel.trim());
} else {
// No models available, clear the input
SafeLogger.log(`No models found for provider ${providerUpper}. Clearing model selection.`);
modelDropdownControl.setValue("", false);
+ updateModelEmptyWarning(true);
}
}
diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.html
index 7e0469bd78..aebbc61dcc 100644
--- a/src/local_deep_research/web/templates/components/settings_form.html
+++ b/src/local_deep_research/web/templates/components/settings_form.html
@@ -217,6 +217,16 @@
refresh_aria_label="Refresh model list" if setting.key == "llm.model" else "Refresh search engine list",
data_setting_key=setting.key
) }}
+ {% if setting.key == "llm.model" %}
+ <span class="ldr-input-warning"
+ id="llm.model-empty-warning"
+ role="status"
+ aria-live="polite"
+ style="display: none;">
+ <i class="fas fa-exclamation-triangle" aria-hidden="true"></i>
+ No model selected. Choose a model from the list, or type one supported by your provider.
+ </span>
+ {% endif %}
{% else %}
{% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}
diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.py
index 4836287b60..c5ffba8f47 100644
--- a/tests/config/test_llm_config.py
+++ b/tests/config/test_llm_config.py
@@ -161,25 +161,21 @@ class TestIsLmstudioAvailable:
class TestIsLlamacppAvailable:
- """Tests for is_llamacpp_available function."""
+ """Tests for is_llamacpp_available function (delegates to LlamaCppProvider)."""
- def test_returns_true_when_model_path_configured(self):
- """Should return True when model path is configured."""
+ def test_returns_true_when_llama_server_responds(self):
+ """Should return True when LlamaCppProvider reports available."""
with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- return_value="/path/to/model.gguf",
+ "local_deep_research.llm.providers.implementations.llamacpp.LlamaCppProvider.is_available",
+ return_value=True,
):
- # Need to also mock the import
- with patch.dict(
- "sys.modules", {"langchain_community.llms": MagicMock()}
- ):
- assert is_llamacpp_available() is True
+ assert is_llamacpp_available() is True
- def test_returns_false_when_no_model_path(self):
- """Should return False when no model path configured."""
+ def test_returns_false_when_not_running(self):
+ """Should return False when LlamaCppProvider reports unavailable."""
with patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- return_value=None,
+ "local_deep_research.llm.providers.implementations.llamacpp.LlamaCppProvider.is_available",
+ return_value=False,
):
assert is_llamacpp_available() is False
@@ -494,6 +490,73 @@ class TestGetLlm:
with pytest.raises(ValueError, match="Invalid provider"):
get_llm()
+ def test_raises_when_model_setting_empty(self):
+ """get_llm() must raise ValueError when llm.model is empty string."""
+ 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": "",
+ "llm.temperature": 0.7,
+ "llm.provider": "ollama",
+ }.get(key, default)
+
+ with pytest.raises(
+ ValueError, match="LLM model not configured"
+ ):
+ get_llm()
+
+ def test_raises_when_model_setting_whitespace_only(self):
+ """get_llm() must raise ValueError when llm.model is whitespace."""
+ 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": " ",
+ "llm.temperature": 0.7,
+ "llm.provider": "ollama",
+ }.get(key, default)
+
+ with pytest.raises(
+ ValueError, match="LLM model not configured"
+ ):
+ get_llm()
+
+ def test_raises_when_model_setting_missing_returns_empty_default(self):
+ """get_llm() must raise when snapshot returns empty default."""
+ 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:
+ # Snapshot has neither llm.model nor a custom default;
+ # function falls back to its own "" default.
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.temperature": 0.7,
+ "llm.provider": "ollama",
+ }.get(key, default)
+
+ with pytest.raises(
+ ValueError, match="LLM model not configured"
+ ):
+ get_llm()
+
def test_anthropic_provider_creates_chat_anthropic(self):
"""Should create ChatAnthropic when provider is anthropic."""
from langchain_anthropic import ChatAnthropic
diff --git a/tests/config/test_llm_config_behavior.py b/tests/config/test_llm_config_behavior.py
index d53c80e87f..7c93d4dca8 100644
--- a/tests/config/test_llm_config_behavior.py
+++ b/tests/config/test_llm_config_behavior.py
@@ -106,7 +106,7 @@ class TestModelAndProviderNameCleaning:
# 'none' is valid but has no implementation, so it raises ValueError
# The point is the quotes are stripped before validation
with pytest.raises(ValueError, match="No LLM provider configured"):
- get_llm(provider="'none'", settings_snapshot={})
+ get_llm(model_name="x", provider="'none'", settings_snapshot={})
def test_whitespace_provider_name_cleaned(self):
"""Surrounding whitespace is stripped: ' none ' → 'none'."""
@@ -114,7 +114,7 @@ class TestModelAndProviderNameCleaning:
from local_deep_research.config.llm_config import get_llm
with pytest.raises(ValueError, match="No LLM provider configured"):
- get_llm(provider=" none ", settings_snapshot={})
+ get_llm(model_name="x", provider=" none ", settings_snapshot={})
def test_uppercase_provider_lowercased(self):
"""Provider name is lowercased: 'NONE' → 'none'."""
@@ -122,7 +122,7 @@ class TestModelAndProviderNameCleaning:
from local_deep_research.config.llm_config import get_llm
with pytest.raises(ValueError, match="No LLM provider configured"):
- get_llm(provider="NONE", settings_snapshot={})
+ get_llm(model_name="x", provider="NONE", settings_snapshot={})
def test_combined_quotes_whitespace_case_cleaning(self):
"""Combined cleaning: \" 'None' \" → 'none'."""
@@ -130,7 +130,7 @@ class TestModelAndProviderNameCleaning:
from local_deep_research.config.llm_config import get_llm
with pytest.raises(ValueError, match="No LLM provider configured"):
- get_llm(provider=" 'None' ", settings_snapshot={})
+ get_llm(model_name="x", provider=" 'None' ", settings_snapshot={})
class TestGetSelectedLlmProvider:
diff --git a/tests/config/test_llm_config_coverage.py b/tests/config/test_llm_config_coverage.py
index fc4a59df61..4085905ad9 100644
--- a/tests/config/test_llm_config_coverage.py
+++ b/tests/config/test_llm_config_coverage.py
@@ -228,23 +228,23 @@ class TestIsLMStudioAvailable:
class TestIsLlamaCppAvailable:
- """Edge-case coverage for is_llamacpp_available()."""
+ """Edge-case coverage for is_llamacpp_available() — now HTTP-based."""
- def test_import_error_returns_false(self):
- """LlamaCpp library not installed returns False."""
- with patch.dict(sys.modules, {"langchain_community.llms": None}):
+ LLAMACPP_PROVIDER = "local_deep_research.llm.providers.implementations.llamacpp.LlamaCppProvider"
+
+ def test_returns_true_when_provider_available(self):
+ """Returns True when LlamaCppProvider.is_available() returns True."""
+ with patch(f"{self.LLAMACPP_PROVIDER}.is_available", return_value=True):
from local_deep_research.config.llm_config import (
is_llamacpp_available,
)
- result = is_llamacpp_available()
- assert result is False
+ assert is_llamacpp_available() is True
- def test_empty_string_path_returns_false(self):
- """Empty-string model path is treated as not configured."""
+ def test_returns_false_when_provider_unavailable(self):
+ """Returns False when llama-server isn't reachable."""
with patch(
- f"{MODULE}.get_setting_from_snapshot",
- return_value="",
+ f"{self.LLAMACPP_PROVIDER}.is_available", return_value=False
):
from local_deep_research.config.llm_config import (
is_llamacpp_available,
@@ -252,25 +252,10 @@ class TestIsLlamaCppAvailable:
assert is_llamacpp_available() is False
- def test_non_empty_path_returns_true(self):
- """Non-empty model path returns True (path validation is deferred)."""
- with (
- patch(
- f"{MODULE}.get_setting_from_snapshot",
- return_value="/some/model.gguf",
- ),
- patch.dict(sys.modules, {"langchain_community.llms": MagicMock()}),
- ):
- from local_deep_research.config.llm_config import (
- is_llamacpp_available,
- )
-
- assert is_llamacpp_available() is True
-
def test_generic_exception_returns_false(self):
"""Unexpected exception in is_llamacpp_available returns False."""
with patch(
- f"{MODULE}.get_setting_from_snapshot",
+ f"{self.LLAMACPP_PROVIDER}.is_available",
side_effect=RuntimeError("unexpected"),
):
from local_deep_research.config.llm_config import (
diff --git a/tests/config/test_llm_config_extended.py b/tests/config/test_llm_config_extended.py
index ff8328ffb9..50bd0897be 100644
--- a/tests/config/test_llm_config_extended.py
+++ b/tests/config/test_llm_config_extended.py
@@ -2,7 +2,6 @@
from unittest.mock import MagicMock, patch
-import pytest
from local_deep_research.config.llm_config import get_llm
@@ -33,126 +32,14 @@ def _mock_get_setting(settings):
class TestLlamaCppProvider:
- """Tests for the LlamaCpp provider path in get_llm."""
+ """Tests for the llamacpp provider — now an HTTP wrapper around llama-server."""
- def test_no_path_raises(self):
- """Missing model path raises ValueError."""
+ 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_model_path": None,
- }
- )
-
- 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),
- ),
- ):
- with pytest.raises(ValueError, match="model path not configured"):
- get_llm(provider="llamacpp")
-
- def test_invalid_extension_raises(self, tmp_path):
- """Invalid file extension raises ValueError."""
- bad_file = tmp_path / "model.txt"
- bad_file.write_text("not a model")
-
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(bad_file),
- }
- )
-
- 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.security.path_validator.PathValidator.validate_model_path"
- ) as mock_validate,
- ):
- # PathValidator.validate_model_path returns the path as-is
- mock_validate.return_value = bad_file
- with pytest.raises(
- ValueError, match="Invalid model file extension"
- ):
- get_llm(provider="llamacpp")
-
- def test_creates_with_gpu_params(self, tmp_path):
- """LlamaCpp is created with GPU params from settings."""
- model_file = tmp_path / "model.gguf"
- model_file.write_text("fake model data")
-
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(model_file),
- "llm.llamacpp_n_gpu_layers": 8,
- "llm.llamacpp_n_batch": 256,
- "llm.llamacpp_f16_kv": False,
- }
- )
-
- mock_llamacpp_cls = MagicMock()
- mock_llamacpp_instance = MagicMock()
- mock_llamacpp_cls.return_value = mock_llamacpp_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.security.path_validator.PathValidator.validate_model_path"
- ) as mock_pv_validate,
- patch(
- "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
- return_value=mock_llamacpp_instance,
- ),
- patch.dict(
- "sys.modules",
- {
- "langchain_community.llms": MagicMock(
- LlamaCpp=mock_llamacpp_cls
- )
- },
- ),
- ):
- mock_pv_validate.return_value = model_file
-
- result = get_llm(provider="llamacpp")
-
- mock_llamacpp_cls.assert_called_once()
- call_kwargs = mock_llamacpp_cls.call_args[1]
- assert call_kwargs["n_gpu_layers"] == 8
- assert call_kwargs["n_batch"] == 256
- assert call_kwargs["f16_kv"] is False
- assert result is mock_llamacpp_instance
-
- def test_path_validation_called(self, tmp_path):
- """PathValidator.validate_model_path is called for security."""
- model_file = tmp_path / "model.gguf"
- model_file.write_text("fake model")
-
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(model_file),
+ "llm.llamacpp.url": "http://my-server:8080/v1",
}
)
@@ -166,32 +53,20 @@ class TestLlamaCppProvider:
side_effect=_mock_get_setting(settings),
),
patch(
- "local_deep_research.security.path_validator.PathValidator.validate_model_path"
- ) as mock_pv_validate,
- patch(
- "local_deep_research.config.llm_config.wrap_llm_without_think_tags",
- return_value=MagicMock(),
- ),
- patch.dict(
- "sys.modules",
- {"langchain_community.llms": MagicMock()},
- ),
+ "local_deep_research.config.llm_config.ChatOpenAI"
+ ) as mock_chat_openai,
):
- mock_pv_validate.return_value = model_file
- get_llm(provider="llamacpp")
- mock_pv_validate.assert_called_once_with(str(model_file))
+ mock_chat_openai.return_value = MagicMock()
+ get_llm(provider="llamacpp", model_name="my-model")
- def test_directory_path_lists_gguf_files(self, tmp_path):
- """Directory with .gguf files produces helpful error listing them."""
- (tmp_path / "alpha.gguf").write_text("fake")
- (tmp_path / "beta.gguf").write_text("fake")
+ 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"
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(tmp_path),
- }
- )
+ 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(
@@ -203,59 +78,14 @@ class TestLlamaCppProvider:
side_effect=_mock_get_setting(settings),
),
patch(
- "local_deep_research.security.path_validator.PathValidator.validate_model_path",
- side_effect=ValueError(f"Model path is not a file: {tmp_path}"),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_safe_path",
- return_value=tmp_path,
- ),
- patch(
- "local_deep_research.config.paths.get_models_directory",
- return_value=tmp_path,
- ),
+ "local_deep_research.config.llm_config.ChatOpenAI"
+ ) as mock_chat_openai,
):
- with pytest.raises(
- ValueError, match="Found .gguf files:"
- ) as exc_info:
- get_llm(provider="llamacpp")
- msg = str(exc_info.value)
- assert "alpha.gguf" in msg
- assert "beta.gguf" in msg
-
- def test_directory_path_no_gguf_files(self, tmp_path):
- """Empty directory produces helpful error about no .gguf files."""
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(tmp_path),
- }
- )
+ mock_chat_openai.return_value = MagicMock()
+ get_llm(provider="llamacpp", model_name="my-model")
- 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.security.path_validator.PathValidator.validate_model_path",
- side_effect=ValueError(f"Model path is not a file: {tmp_path}"),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_safe_path",
- return_value=tmp_path,
- ),
- patch(
- "local_deep_research.config.paths.get_models_directory",
- return_value=tmp_path,
- ),
- ):
- with pytest.raises(ValueError, match="No .gguf files found"):
- get_llm(provider="llamacpp")
+ call_kwargs = mock_chat_openai.call_args[1]
+ assert call_kwargs["base_url"] == "http://localhost:8080/v1"
# ── Ollama provider ────────────────────────────────────────────────
diff --git a/tests/config/test_llm_config_extra_coverage.py b/tests/config/test_llm_config_extra_coverage.py
index d42b22db01..6e67befd0b 100644
--- a/tests/config/test_llm_config_extra_coverage.py
+++ b/tests/config/test_llm_config_extra_coverage.py
@@ -143,43 +143,30 @@ class TestProviderAvailabilityExceptionPaths:
class TestIsLlamacppAvailable:
- def test_import_error_returns_false(self):
- from local_deep_research.config.llm_config import is_llamacpp_available
-
- with patch.dict("sys.modules", {"langchain_community.llms": None}):
- assert is_llamacpp_available() is False
-
- def test_no_model_path_returns_false(self):
- from local_deep_research.config.llm_config import is_llamacpp_available
-
- with patch(f"{MODULE}.get_setting_from_snapshot", return_value=None):
- result = is_llamacpp_available(settings_snapshot={})
+ """is_llamacpp_available now probes llama-server's HTTP endpoint."""
- assert result is False
+ LLAMACPP_PROVIDER = "local_deep_research.llm.providers.implementations.llamacpp.LlamaCppProvider"
- def test_empty_model_path_returns_false(self):
+ def test_returns_true_when_provider_available(self):
from local_deep_research.config.llm_config import is_llamacpp_available
- with patch(f"{MODULE}.get_setting_from_snapshot", return_value=""):
- assert is_llamacpp_available(settings_snapshot={}) is False
+ with patch(f"{self.LLAMACPP_PROVIDER}.is_available", return_value=True):
+ assert is_llamacpp_available(settings_snapshot={}) is True
- def test_valid_model_path_returns_true(self):
+ def test_returns_false_when_provider_unavailable(self):
from local_deep_research.config.llm_config import is_llamacpp_available
with patch(
- f"{MODULE}.get_setting_from_snapshot",
- return_value="/models/llama.gguf",
+ f"{self.LLAMACPP_PROVIDER}.is_available", return_value=False
):
- result = is_llamacpp_available(settings_snapshot={})
-
- assert result is True
+ assert is_llamacpp_available(settings_snapshot={}) is False
- def test_setting_exception_returns_false(self):
+ def test_returns_false_on_unexpected_exception(self):
from local_deep_research.config.llm_config import is_llamacpp_available
with patch(
- f"{MODULE}.get_setting_from_snapshot",
- side_effect=RuntimeError("settings error"),
+ f"{self.LLAMACPP_PROVIDER}.is_available",
+ side_effect=RuntimeError("boom"),
):
assert is_llamacpp_available(settings_snapshot={}) is False
diff --git a/tests/config/test_llm_config_missing_coverage.py b/tests/config/test_llm_config_missing_coverage.py
index 96400f1ea2..068aaa532e 100644
--- a/tests/config/test_llm_config_missing_coverage.py
+++ b/tests/config/test_llm_config_missing_coverage.py
@@ -141,8 +141,14 @@ class TestGetLlmFallbackEnvVar:
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_model_path": None}
+ {
+ "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),
@@ -152,11 +158,18 @@ class TestGetLlmFallbackEnvVar:
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
- with pytest.raises(ValueError, match="model path not configured"):
- get_llm(provider="llamacpp", settings_snapshot=settings)
+ result = get_llm(provider="llamacpp", settings_snapshot=settings)
+ mock_openai_cls.assert_called_once()
+ assert result is mock_llamacpp_instance
class TestGetLlmOllamaEdgeCases:
@@ -279,124 +292,11 @@ class TestGetLlmOllamaEdgeCases:
assert call_kwargs["reasoning"] is False
-class TestGetLlmLlamaCppEdgeCases:
- """Tests for llamacpp-specific edge cases in get_llm."""
-
- def test_llamacpp_no_model_path_raises(self):
- """When llamacpp_model_path is not set, ValueError is raised."""
- settings = _settings_dict(
- {"llm.provider": "llamacpp", "llm.llamacpp_model_path": None}
- )
- with (
- patch(f"{MODULE}.is_llm_registered", return_value=False),
- patch(
- f"{MODULE}.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- with pytest.raises(ValueError, match="model path not configured"):
- get_llm(provider="llamacpp", settings_snapshot=settings)
-
- def test_llamacpp_invalid_extension_raises(self, tmp_path):
- """A file with a non-.gguf/.bin extension raises ValueError."""
- bad_file = tmp_path / "model.safetensors"
- bad_file.write_text("not a gguf model")
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(bad_file),
- }
- )
- with (
- patch(f"{MODULE}.is_llm_registered", return_value=False),
- patch(
- f"{MODULE}.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_model_path",
- return_value=bad_file,
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- with pytest.raises(
- ValueError, match="Invalid model file extension"
- ):
- get_llm(provider="llamacpp", settings_snapshot=settings)
-
- def test_llamacpp_directory_with_gguf_suggestion(self, tmp_path):
- """When path is a directory with .gguf files, the error lists them."""
- (tmp_path / "model_a.gguf").write_text("fake")
- (tmp_path / "model_b.gguf").write_text("fake")
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(tmp_path),
- }
- )
- with (
- patch(f"{MODULE}.is_llm_registered", return_value=False),
- patch(
- f"{MODULE}.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_model_path",
- side_effect=ValueError(f"Model path is not a file: {tmp_path}"),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_safe_path",
- return_value=tmp_path,
- ),
- patch(
- "local_deep_research.config.paths.get_models_directory",
- return_value=tmp_path,
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- with pytest.raises(
- ValueError, match="Found .gguf files:"
- ) as exc_info:
- get_llm(provider="llamacpp", settings_snapshot=settings)
- msg = str(exc_info.value)
- assert "model_a.gguf" in msg
- assert "model_b.gguf" in msg
-
- def test_llamacpp_directory_no_gguf_files(self, tmp_path):
- """When path is a directory with no .gguf files, error says so."""
- settings = _settings_dict(
- {
- "llm.provider": "llamacpp",
- "llm.llamacpp_model_path": str(tmp_path),
- }
- )
- with (
- patch(f"{MODULE}.is_llm_registered", return_value=False),
- patch(
- f"{MODULE}.get_setting_from_snapshot",
- side_effect=_mock_get_setting(settings),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_model_path",
- side_effect=ValueError(f"Model path is not a file: {tmp_path}"),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_safe_path",
- return_value=tmp_path,
- ),
- patch(
- "local_deep_research.config.paths.get_models_directory",
- return_value=tmp_path,
- ),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- with pytest.raises(ValueError, match="No .gguf files found"):
- get_llm(provider="llamacpp", settings_snapshot=settings)
+# 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:
diff --git a/tests/config/test_llm_config_providers.py b/tests/config/test_llm_config_providers.py
index c3572d3abb..de9e0bea47 100644
--- a/tests/config/test_llm_config_providers.py
+++ b/tests/config/test_llm_config_providers.py
@@ -108,69 +108,41 @@ class TestProviderInstantiation:
assert params["api_key"] == "lm-studio" # pragma: allowlist secret
assert params["base_url"] == lmstudio_url
- def test_llamacpp_local_mode_path_validation(self):
- """LlamaCpp local mode validates model path."""
- model_path = "/models/llama-2-7b.gguf"
-
- # Path validation
- is_valid = model_path.endswith(".gguf") or model_path.endswith(".bin")
-
- assert is_valid
-
- def test_llamacpp_rejects_invalid_extension(self):
- """LlamaCpp rejects model files without .gguf or .bin extension."""
- import sys
- import tempfile
- from pathlib import Path
+ 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
- with tempfile.TemporaryDirectory() as tmpdir:
- # Create a file with invalid extension
- bad_model = Path(tmpdir) / "model.txt"
- bad_model.write_text("not a real model")
-
- # Mock the LlamaCpp import (llama-cpp-python may not be installed)
- mock_llamacpp_module = MagicMock()
- with (
- patch.dict(
- sys.modules,
- {"langchain_community.llms.llamacpp": mock_llamacpp_module},
- ),
- patch(
- "langchain_community.llms.LlamaCpp",
- mock_llamacpp_module.LlamaCpp,
- create=True,
- ),
- patch(
- "local_deep_research.config.llm_config.get_setting_from_snapshot",
- side_effect=lambda key, *a, **kw: (
- str(bad_model) if "model_path" in key else None
- ),
- ),
- patch(
- "local_deep_research.security.path_validator.PathValidator.validate_model_path",
- return_value=bad_model,
- ),
- pytest.raises(ValueError, match="Invalid model file extension"),
- ):
- from local_deep_research.config.llm_config import get_llm
-
- get_llm(provider="llamacpp")
-
- def test_llamacpp_gpu_layers_config(self):
- """LlamaCpp GPU layers configuration."""
- n_gpu_layers = 35 # Number of layers to offload to GPU
-
- params = {
- "model_path": "/models/model.gguf",
- "n_gpu_layers": n_gpu_layers,
- "n_batch": 512,
- "f16_kv": True,
- }
-
- assert params["n_gpu_layers"] == 35
- assert params["n_batch"] == 512
- assert params["f16_kv"] is True
+ 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:
diff --git a/tests/llm/providers/test_openai_base.py b/tests/llm/providers/test_openai_base.py
index b44763758f..ace7ecb62c 100644
--- a/tests/llm/providers/test_openai_base.py
+++ b/tests/llm/providers/test_openai_base.py
@@ -10,6 +10,8 @@ Tests cover:
from unittest.mock import Mock, patch
+import pytest
+
class TestOpenAICompatibleProviderAttributes:
"""Tests for OpenAICompatibleProvider class attributes."""
@@ -61,7 +63,7 @@ class TestOpenAICompatibleProviderCreateLLM:
assert "API key not configured" in str(e)
def test_create_llm_uses_default_model(self):
- """create_llm uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
from local_deep_research.llm.providers.openai_base import (
OpenAICompatibleProvider,
)
@@ -77,20 +79,9 @@ class TestOpenAICompatibleProviderCreateLLM:
"local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
side_effect=mock_get_setting,
):
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat:
- mock_chat.return_value = Mock()
-
+ with pytest.raises(ValueError, match="model not configured"):
OpenAICompatibleProvider.create_llm()
- # Check that default model was used
- call_kwargs = mock_chat.call_args[1]
- assert (
- call_kwargs["model"]
- == OpenAICompatibleProvider.default_model
- )
-
def test_create_llm_uses_specified_model(self):
"""create_llm uses specified model."""
from local_deep_research.llm.providers.openai_base import (
@@ -140,7 +131,9 @@ class TestOpenAICompatibleProviderCreateLLM:
) as mock_chat:
mock_chat.return_value = Mock()
- OpenAICompatibleProvider.create_llm(temperature=0.5)
+ OpenAICompatibleProvider.create_llm(
+ model_name="test-model", temperature=0.5
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.5
@@ -322,7 +315,9 @@ class TestOpenAICompatibleProviderCreateLLMInstance:
) as mock_chat:
mock_chat.return_value = Mock()
- OpenAICompatibleProvider._create_llm_instance()
+ OpenAICompatibleProvider._create_llm_instance(
+ model_name="test-model"
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["api_key"] == "dummy-key"
@@ -338,7 +333,9 @@ class TestOpenAICompatibleProviderCreateLLMInstance:
) as mock_chat:
mock_chat.return_value = Mock()
- OpenAICompatibleProvider._create_llm_instance(api_key="custom-key")
+ OpenAICompatibleProvider._create_llm_instance(
+ model_name="test-model", api_key="custom-key"
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["api_key"] == "custom-key"
diff --git a/tests/llm/providers/test_openai_base_deep_coverage.py b/tests/llm/providers/test_openai_base_deep_coverage.py
index c82ca5f91f..addf28fcba 100644
--- a/tests/llm/providers/test_openai_base_deep_coverage.py
+++ b/tests/llm/providers/test_openai_base_deep_coverage.py
@@ -46,7 +46,8 @@ class TestCreateLlmApiKeyHandling:
with pytest.raises(ValueError, match="API key not configured"):
OpenAICompatibleProvider.create_llm(
- settings_snapshot={"some": "settings"}
+ model_name="test-model",
+ settings_snapshot={"some": "settings"},
)
@patch(f"{MODULE}.ChatOpenAI")
@@ -63,7 +64,8 @@ class TestCreateLlmApiKeyHandling:
mock_chat.return_value = Mock()
OpenAICompatibleProvider.create_llm(
- settings_snapshot={"llm.openai_endpoint.api_key": "sk-test-key"}
+ model_name="test-model",
+ settings_snapshot={"llm.openai_endpoint.api_key": "sk-test-key"},
)
call_kwargs = mock_chat.call_args[1]
@@ -83,16 +85,14 @@ class TestCreateLlmModelAndUrl:
f"{MODULE}.get_setting_from_snapshot", side_effect=_api_key_side_effect
)
def test_default_model_used(self, mock_get_setting, mock_chat):
- """Uses default_model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
mock_chat.return_value = Mock()
- OpenAICompatibleProvider.create_llm(
- model_name=None,
- settings_snapshot={},
- )
-
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == "gpt-3.5-turbo"
+ with pytest.raises(ValueError, match="model not configured"):
+ OpenAICompatibleProvider.create_llm(
+ model_name=None,
+ settings_snapshot={},
+ )
@patch(f"{MODULE}.ChatOpenAI")
@patch(
@@ -128,7 +128,9 @@ class TestCreateLlmOptionalParams:
mock_get_setting.side_effect = side_effect
mock_chat.return_value = Mock()
- OpenAICompatibleProvider.create_llm(settings_snapshot={})
+ OpenAICompatibleProvider.create_llm(
+ model_name="test-model", settings_snapshot={}
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 2048
@@ -148,7 +150,9 @@ class TestCreateLlmOptionalParams:
mock_get_setting.side_effect = side_effect
mock_chat.return_value = Mock()
- OpenAICompatibleProvider.create_llm(settings_snapshot={})
+ OpenAICompatibleProvider.create_llm(
+ model_name="test-model", settings_snapshot={}
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["streaming"] is True
@@ -174,6 +178,8 @@ class TestCreateLlmOptionalParams:
f"{MODULE}.get_setting_from_snapshot", side_effect=side_effect
):
# Should not raise despite NoSettingsContextError for optional params
- OpenAICompatibleProvider.create_llm(settings_snapshot={})
+ OpenAICompatibleProvider.create_llm(
+ model_name="test-model", settings_snapshot={}
+ )
mock_chat.assert_called_once()
diff --git a/tests/llm/test_openai_base.py b/tests/llm/test_openai_base.py
index a0263bbc60..8e3c025a54 100644
--- a/tests/llm/test_openai_base.py
+++ b/tests/llm/test_openai_base.py
@@ -101,7 +101,7 @@ class TestOpenAICompatibleProviderCreateLLM:
"local_deep_research.llm.providers.openai_base.get_setting_from_snapshot"
)
def test_create_llm_uses_default_model(self, mock_get_setting, mock_chat):
- """Test that create_llm uses default model when none specified."""
+ """Test that create_llm raises ValueError when no model name is provided."""
from local_deep_research.llm.providers.openai_base import (
OpenAICompatibleProvider,
)
@@ -114,10 +114,8 @@ class TestOpenAICompatibleProviderCreateLLM:
mock_get_setting.side_effect = setting_side_effect
mock_chat.return_value = Mock()
- OpenAICompatibleProvider.create_llm()
-
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == OpenAICompatibleProvider.default_model
+ with pytest.raises(ValueError, match="model not configured"):
+ OpenAICompatibleProvider.create_llm()
@patch("local_deep_research.llm.providers.openai_base.ChatOpenAI")
@patch(
diff --git a/tests/llm_providers/implementations/test_anthropic_provider.py b/tests/llm_providers/implementations/test_anthropic_provider.py
index 749c4badb3..a9fc1af085 100644
--- a/tests/llm_providers/implementations/test_anthropic_provider.py
+++ b/tests/llm_providers/implementations/test_anthropic_provider.py
@@ -32,9 +32,8 @@ class TestAnthropicProviderMetadata:
assert AnthropicProvider.api_key_setting == "llm.anthropic.api_key"
def test_default_model(self):
- """Default model is set."""
- assert AnthropicProvider.default_model is not None
- assert "claude" in AnthropicProvider.default_model.lower()
+ """Default model is empty by design — users must explicitly pick one."""
+ assert AnthropicProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is correct."""
@@ -77,13 +76,13 @@ class TestAnthropicCreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = AnthropicProvider.create_llm()
+ result = AnthropicProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
def test_create_llm_uses_default_model_when_none(self):
- """Uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -97,14 +96,9 @@ class TestAnthropicCreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
- ) as mock_chat:
+ with pytest.raises(ValueError, match="model not configured"):
AnthropicProvider.create_llm()
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == AnthropicProvider.default_model
-
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
@@ -148,7 +142,9 @@ class TestAnthropicCreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
) as mock_chat:
- AnthropicProvider.create_llm(temperature=0.5)
+ AnthropicProvider.create_llm(
+ model_name="test-model", temperature=0.5
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.5
@@ -171,7 +167,7 @@ class TestAnthropicCreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
) as mock_chat:
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 4096
@@ -194,7 +190,7 @@ class TestAnthropicCreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.anthropic.ChatAnthropic"
) as mock_chat:
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["anthropic_api_key"] == "my-anthropic-key"
diff --git a/tests/llm_providers/implementations/test_google_provider.py b/tests/llm_providers/implementations/test_google_provider.py
index c4c55c565d..4cea3066e7 100644
--- a/tests/llm_providers/implementations/test_google_provider.py
+++ b/tests/llm_providers/implementations/test_google_provider.py
@@ -32,8 +32,8 @@ class TestGoogleProviderMetadata:
assert GoogleProvider.api_key_setting == "llm.google.api_key"
def test_default_model(self):
- """Default model is gemini-1.5-flash."""
- assert GoogleProvider.default_model == "gemini-1.5-flash"
+ """Default model is empty by design — users must explicitly pick one."""
+ assert GoogleProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is Google's OpenAI-compatible endpoint."""
@@ -443,13 +443,13 @@ class TestGoogleCreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = GoogleProvider.create_llm()
+ result = GoogleProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
def test_create_llm_uses_default_model(self):
- """Uses gemini-1.5-flash as default model."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -466,14 +466,9 @@ class TestGoogleCreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat:
+ with pytest.raises(ValueError, match="model not configured"):
GoogleProvider.create_llm()
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == "gemini-1.5-flash"
-
def test_create_llm_with_custom_model(self):
"""Uses custom Gemini model when specified."""
@@ -525,7 +520,7 @@ class TestGoogleCreateLLM:
"local_deep_research.llm.providers.openai_base.normalize_url",
side_effect=lambda x: x,
):
- GoogleProvider.create_llm()
+ GoogleProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert (
@@ -554,7 +549,9 @@ class TestGoogleCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- GoogleProvider.create_llm(temperature=0.3)
+ GoogleProvider.create_llm(
+ model_name="test-model", temperature=0.3
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.3
diff --git a/tests/llm_providers/implementations/test_ionos_provider.py b/tests/llm_providers/implementations/test_ionos_provider.py
index 6ef4b4b7e9..a26f78be4e 100644
--- a/tests/llm_providers/implementations/test_ionos_provider.py
+++ b/tests/llm_providers/implementations/test_ionos_provider.py
@@ -32,9 +32,8 @@ class TestIONOSProviderMetadata:
assert IONOSProvider.api_key_setting == "llm.ionos.api_key"
def test_default_model(self):
- """Default model is set to open model."""
- assert IONOSProvider.default_model is not None
- assert "llama" in IONOSProvider.default_model.lower()
+ """Default model is empty by design — users must explicitly pick one."""
+ assert IONOSProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is correct."""
@@ -80,13 +79,13 @@ class TestIONOSCreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = IONOSProvider.create_llm()
+ result = IONOSProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
def test_create_llm_uses_default_model_when_none(self):
- """Uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -103,14 +102,9 @@ class TestIONOSCreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat:
+ with pytest.raises(ValueError, match="model not configured"):
IONOSProvider.create_llm()
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == IONOSProvider.default_model
-
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
@@ -162,7 +156,9 @@ class TestIONOSCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- IONOSProvider.create_llm(temperature=0.3)
+ IONOSProvider.create_llm(
+ model_name="test-model", temperature=0.3
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.3
@@ -188,7 +184,7 @@ class TestIONOSCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- IONOSProvider.create_llm()
+ IONOSProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "ionos.com" in call_kwargs["base_url"]
diff --git a/tests/llm_providers/implementations/test_llamacpp_provider.py b/tests/llm_providers/implementations/test_llamacpp_provider.py
new file mode 100644
index 0000000000..5bb7d89c23
--- /dev/null
+++ b/tests/llm_providers/implementations/test_llamacpp_provider.py
@@ -0,0 +1,255 @@
+"""Tests for llama.cpp LLM provider."""
+
+from unittest.mock import Mock, patch
+
+from local_deep_research.llm.providers.implementations.llamacpp import (
+ LlamaCppProvider,
+)
+
+
+def _make_setting_side_effect(url_value, api_key_value=""):
+ """Create a side_effect function that returns url_value for
+ llm.llamacpp.url, api_key_value for llm.llamacpp.api_key, and
+ default for everything else.
+
+ Uses *args, **kwargs to handle variable call patterns from
+ get_setting_from_snapshot.
+ """
+
+ def _setting_side_effect(*args, **kwargs):
+ key = args[0] if args else kwargs.get("key", "")
+ default = args[1] if len(args) > 1 else kwargs.get("default", None)
+ if key == "llm.llamacpp.url":
+ return url_value
+ if key == "llm.llamacpp.api_key":
+ return api_key_value
+ return default
+
+ return _setting_side_effect
+
+
+class TestLlamaCppProviderMetadata:
+ """Tests for LlamaCppProvider class metadata."""
+
+ def test_provider_name(self):
+ """Provider name is correct."""
+ assert LlamaCppProvider.provider_name == "llama.cpp"
+
+ def test_provider_key(self):
+ """Provider key is correct."""
+ assert LlamaCppProvider.provider_key == "LLAMACPP"
+
+ def test_company_name(self):
+ """Company name is llama.cpp."""
+ assert LlamaCppProvider.company_name == "llama.cpp"
+
+ def test_is_not_cloud(self):
+ """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_url_setting(self):
+ """URL setting is defined."""
+ assert LlamaCppProvider.url_setting == "llm.llamacpp.url"
+
+ def test_default_model(self):
+ """Default model is empty — user must specify."""
+ assert LlamaCppProvider.default_model == ""
+
+ def test_default_base_url(self):
+ """Default base URL is localhost on port 8080."""
+ assert "8080" in LlamaCppProvider.default_base_url
+
+
+class TestLlamaCppCreateLLM:
+ """Tests for create_llm method."""
+
+ def test_create_llm_success(self):
+ """Successfully creates ChatOpenAI instance."""
+ 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"
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ mock_llm = Mock()
+ mock_chat.return_value = mock_llm
+
+ result = LlamaCppProvider.create_llm(model_name="test-model")
+
+ assert result is mock_llm
+ mock_chat.assert_called_once()
+
+ def test_create_llm_uses_default_url(self):
+ """Uses default URL when not configured."""
+ 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(
+ LlamaCppProvider.default_base_url
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LlamaCppProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert "localhost" in call_kwargs["base_url"]
+ assert "8080" in call_kwargs["base_url"]
+
+ def test_create_llm_uses_custom_url(self):
+ """Uses custom URL from settings."""
+ 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://custom:5000/v1"
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LlamaCppProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert "custom" in call_kwargs["base_url"]
+ assert "5000" in call_kwargs["base_url"]
+
+ def test_create_llm_placeholder_api_key_when_unset(self):
+ """Falls back to placeholder API key when none configured."""
+ 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=""
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LlamaCppProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["api_key"] == "lm-studio"
+
+ def test_create_llm_uses_real_api_key(self):
+ """Uses configured API key when llm.llamacpp.api_key is set."""
+ 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.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LlamaCppProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["api_key"] == "my-secret-key"
+
+ def test_create_llm_with_custom_model(self):
+ """Uses custom model when specified."""
+ 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"
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LlamaCppProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["model"] == "test-model"
+
+ def test_create_llm_with_custom_temperature(self):
+ """Uses custom temperature."""
+ 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"
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LlamaCppProvider.create_llm(
+ model_name="test-model", temperature=0.3
+ )
+
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["temperature"] == 0.3
+
+
+class TestLlamaCppIsAvailable:
+ """Tests for is_available method."""
+
+ def test_true_when_server_responds_200(self):
+ """Returns True when llama-server responds with 200."""
+ 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"
+ )
+
+ 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
+
+ result = LlamaCppProvider.is_available()
+ assert result is True
+
+ def test_false_when_server_returns_500(self):
+ """Returns False when server returns 500."""
+ 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"
+ )
+
+ with patch("local_deep_research.security.safe_get") as mock_get:
+ mock_response = Mock()
+ mock_response.status_code = 500
+ mock_get.return_value = mock_response
+
+ result = LlamaCppProvider.is_available()
+ assert result is False
+
+ def test_false_on_connection_error(self):
+ """Returns False when connection fails."""
+ 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"
+ )
+
+ with patch("local_deep_research.security.safe_get") as mock_get:
+ mock_get.side_effect = Exception("Connection refused")
+
+ result = LlamaCppProvider.is_available()
+ assert result is False
+
+
+class TestLlamaCppRequiresAuth:
+ """Tests for requires_auth_for_models method."""
+
+ def test_does_not_require_auth(self):
+ """llama.cpp doesn't require authentication for listing models."""
+ assert LlamaCppProvider.requires_auth_for_models() is False
diff --git a/tests/llm_providers/implementations/test_lmstudio_provider.py b/tests/llm_providers/implementations/test_lmstudio_provider.py
index 6ca918a031..a5b30a0146 100644
--- a/tests/llm_providers/implementations/test_lmstudio_provider.py
+++ b/tests/llm_providers/implementations/test_lmstudio_provider.py
@@ -7,9 +7,9 @@ from local_deep_research.llm.providers.implementations.lmstudio import (
)
-def _make_setting_side_effect(url_value):
- """Create a side_effect function that returns url_value for llm.lmstudio.url
- and default for everything else.
+def _make_setting_side_effect(url_value, api_key_value=""):
+ """Create a side_effect function that returns url_value for llm.lmstudio.url,
+ api_key_value for llm.lmstudio.api_key, and default for everything else.
Uses *args, **kwargs to handle variable call patterns from
get_setting_from_snapshot.
@@ -20,6 +20,8 @@ def _make_setting_side_effect(url_value):
default = args[1] if len(args) > 1 else kwargs.get("default", None)
if key == "llm.lmstudio.url":
return url_value
+ if key == "llm.lmstudio.api_key":
+ return api_key_value
return default
return _setting_side_effect
@@ -53,9 +55,8 @@ class TestLMStudioProviderMetadata:
assert LMStudioProvider.url_setting == "llm.lmstudio.url"
def test_default_model(self):
- """Default model is set."""
- assert LMStudioProvider.default_model is not None
- assert LMStudioProvider.default_model == "local-model"
+ """Default model is empty by design — users must explicitly pick one."""
+ assert LMStudioProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is localhost."""
@@ -81,7 +82,7 @@ class TestLMStudioCreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = LMStudioProvider.create_llm()
+ result = LMStudioProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
@@ -98,7 +99,7 @@ class TestLMStudioCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- LMStudioProvider.create_llm()
+ LMStudioProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "localhost" in call_kwargs["base_url"]
@@ -116,7 +117,7 @@ class TestLMStudioCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- LMStudioProvider.create_llm()
+ LMStudioProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "custom" in call_kwargs["base_url"]
@@ -134,12 +135,29 @@ class TestLMStudioCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- LMStudioProvider.create_llm()
+ LMStudioProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
# Should use a placeholder key like "not-required"
assert call_kwargs["api_key"] == "not-required"
+ def test_create_llm_uses_configured_api_key(self):
+ """Uses real API key when llm.lmstudio.api_key is configured."""
+ 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:1234/v1", api_key_value="my-real-api-key"
+ )
+
+ with patch(
+ "local_deep_research.llm.providers.openai_base.ChatOpenAI"
+ ) as mock_chat:
+ LMStudioProvider.create_llm(model_name="test-model")
+
+ call_kwargs = mock_chat.call_args[1]
+ assert call_kwargs["api_key"] == "my-real-api-key"
+
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
with patch(
@@ -169,7 +187,9 @@ class TestLMStudioCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- LMStudioProvider.create_llm(temperature=0.3)
+ LMStudioProvider.create_llm(
+ model_name="test-model", temperature=0.3
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.3
diff --git a/tests/llm_providers/implementations/test_openai_provider.py b/tests/llm_providers/implementations/test_openai_provider.py
index f92493fff2..47f40d082c 100644
--- a/tests/llm_providers/implementations/test_openai_provider.py
+++ b/tests/llm_providers/implementations/test_openai_provider.py
@@ -32,8 +32,8 @@ class TestOpenAIProviderMetadata:
assert OpenAIProvider.api_key_setting == "llm.openai.api_key"
def test_default_model(self):
- """Default model is gpt-3.5-turbo."""
- assert OpenAIProvider.default_model == "gpt-3.5-turbo"
+ """Default model is empty by design — users must explicitly pick one."""
+ assert OpenAIProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is OpenAI API."""
@@ -82,13 +82,13 @@ class TestOpenAICreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = OpenAIProvider.create_llm()
+ result = OpenAIProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
def test_create_llm_uses_default_model_when_none(self):
- """Uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -107,14 +107,9 @@ class TestOpenAICreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
- ) as mock_chat:
+ with pytest.raises(ValueError, match="model not configured"):
OpenAIProvider.create_llm()
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == "gpt-3.5-turbo"
-
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
@@ -166,7 +161,9 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm(temperature=0.5)
+ OpenAIProvider.create_llm(
+ model_name="test-model", temperature=0.5
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.5
@@ -194,7 +191,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 4096
@@ -222,7 +219,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["streaming"] is True
@@ -250,7 +247,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_retries"] == 5
@@ -278,7 +275,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["request_timeout"] == 120
@@ -306,7 +303,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert (
@@ -337,7 +334,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["openai_organization"] == "org-12345"
@@ -365,7 +362,7 @@ class TestOpenAICreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 2048
@@ -396,7 +393,7 @@ class TestOpenAICreateLLM:
"local_deep_research.llm.providers.implementations.openai.ChatOpenAI"
) as mock_chat:
# Should not raise - NoSettingsContextError is caught for optional params
- OpenAIProvider.create_llm()
+ OpenAIProvider.create_llm(model_name="test-model")
mock_chat.assert_called_once()
diff --git a/tests/llm_providers/implementations/test_openrouter_provider.py b/tests/llm_providers/implementations/test_openrouter_provider.py
index 35fe5c387e..1344eeead8 100644
--- a/tests/llm_providers/implementations/test_openrouter_provider.py
+++ b/tests/llm_providers/implementations/test_openrouter_provider.py
@@ -32,9 +32,8 @@ class TestOpenRouterProviderMetadata:
assert OpenRouterProvider.api_key_setting == "llm.openrouter.api_key"
def test_default_model(self):
- """Default model is a free model."""
- assert OpenRouterProvider.default_model is not None
- assert "free" in OpenRouterProvider.default_model.lower()
+ """Default model is empty by design — users must explicitly pick one."""
+ assert OpenRouterProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is correct."""
@@ -80,13 +79,13 @@ class TestOpenRouterCreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = OpenRouterProvider.create_llm()
+ result = OpenRouterProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
def test_create_llm_uses_default_model_when_none(self):
- """Uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -103,14 +102,9 @@ class TestOpenRouterCreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat:
+ with pytest.raises(ValueError, match="model not configured"):
OpenRouterProvider.create_llm()
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == OpenRouterProvider.default_model
-
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
@@ -158,7 +152,9 @@ class TestOpenRouterCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- OpenRouterProvider.create_llm(temperature=0.5)
+ OpenRouterProvider.create_llm(
+ model_name="test-model", temperature=0.5
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.5
@@ -184,7 +180,7 @@ class TestOpenRouterCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- OpenRouterProvider.create_llm()
+ OpenRouterProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "openrouter.ai" in call_kwargs["base_url"]
diff --git a/tests/llm_providers/implementations/test_xai_provider.py b/tests/llm_providers/implementations/test_xai_provider.py
index 235ee49970..46e5f3737f 100644
--- a/tests/llm_providers/implementations/test_xai_provider.py
+++ b/tests/llm_providers/implementations/test_xai_provider.py
@@ -32,9 +32,8 @@ class TestXAIProviderMetadata:
assert XAIProvider.api_key_setting == "llm.xai.api_key"
def test_default_model(self):
- """Default model is grok-beta."""
- assert XAIProvider.default_model is not None
- assert "grok" in XAIProvider.default_model.lower()
+ """Default model is empty by design — users must explicitly pick one."""
+ assert XAIProvider.default_model == ""
def test_default_base_url(self):
"""Default base URL is correct."""
@@ -80,13 +79,13 @@ class TestXAICreateLLM:
mock_llm = Mock()
mock_chat.return_value = mock_llm
- result = XAIProvider.create_llm()
+ result = XAIProvider.create_llm(model_name="test-model")
assert result is mock_llm
mock_chat.assert_called_once()
def test_create_llm_uses_default_model_when_none(self):
- """Uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -103,14 +102,9 @@ class TestXAICreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat:
+ with pytest.raises(ValueError, match="model not configured"):
XAIProvider.create_llm()
- call_kwargs = mock_chat.call_args[1]
- assert call_kwargs["model"] == XAIProvider.default_model
-
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
@@ -158,7 +152,7 @@ class TestXAICreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- XAIProvider.create_llm(temperature=0.8)
+ XAIProvider.create_llm(model_name="test-model", temperature=0.8)
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.8
@@ -184,7 +178,7 @@ class TestXAICreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
- XAIProvider.create_llm()
+ XAIProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "x.ai" in call_kwargs["base_url"]
diff --git a/tests/llm_providers/test_anthropic_high_value.py b/tests/llm_providers/test_anthropic_high_value.py
index 9fed58af95..51d168d6e8 100644
--- a/tests/llm_providers/test_anthropic_high_value.py
+++ b/tests/llm_providers/test_anthropic_high_value.py
@@ -58,7 +58,7 @@ class TestAnthropicAPIKeyValidation:
):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["anthropic_api_key"] == " "
@@ -113,7 +113,7 @@ class TestAnthropicAPIKeyValidation:
with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "anthropic_api_key" in call_kwargs
assert "api_key" not in call_kwargs
@@ -130,7 +130,7 @@ class TestAnthropicMaxTokensHandling:
):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "max_tokens" not in call_kwargs
@@ -142,7 +142,7 @@ class TestAnthropicMaxTokensHandling:
):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert "max_tokens" not in call_kwargs
@@ -154,7 +154,7 @@ class TestAnthropicMaxTokensHandling:
):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 8192
assert isinstance(call_kwargs["max_tokens"], int)
@@ -167,7 +167,7 @@ class TestAnthropicMaxTokensHandling:
):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 4096
assert isinstance(call_kwargs["max_tokens"], int)
@@ -188,7 +188,9 @@ class TestAnthropicSettingsSnapshot:
) as mock_get:
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm(settings_snapshot=snapshot)
+ AnthropicProvider.create_llm(
+ model_name="test-model", settings_snapshot=snapshot
+ )
for call in mock_get.call_args_list:
assert call.kwargs.get("settings_snapshot") == snapshot
@@ -198,7 +200,7 @@ class TestAnthropicSettingsSnapshot:
with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- result = AnthropicProvider.create_llm()
+ result = AnthropicProvider.create_llm(model_name="test-model")
assert result is mock_chat.return_value
@@ -246,7 +248,7 @@ class TestAnthropicChatConstruction:
with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.7
@@ -255,7 +257,9 @@ class TestAnthropicChatConstruction:
with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm(temperature=0.0)
+ AnthropicProvider.create_llm(
+ model_name="test-model", temperature=0.0
+ )
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["temperature"] == 0.0
@@ -265,14 +269,14 @@ class TestAnthropicChatConstruction:
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.side_effect = Exception("Connection refused")
with pytest.raises(Exception, match="Connection refused"):
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
def test_only_expected_params_passed_without_max_tokens(self):
"""Without max_tokens, only model, anthropic_api_key, temperature should be passed."""
with patch(GET_SETTING, side_effect=_make_setting_side_effect()):
with patch(CHAT_ANTHROPIC) as mock_chat:
mock_chat.return_value = Mock()
- AnthropicProvider.create_llm()
+ AnthropicProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
expected_keys = {"model", "anthropic_api_key", "temperature"}
assert set(call_kwargs.keys()) == expected_keys
diff --git a/tests/llm_providers/test_custom_openai_endpoint.py b/tests/llm_providers/test_custom_openai_endpoint.py
index 8a97c392f3..1ad2d455c6 100644
--- a/tests/llm_providers/test_custom_openai_endpoint.py
+++ b/tests/llm_providers/test_custom_openai_endpoint.py
@@ -193,7 +193,9 @@ class TestCustomOpenAIEndpointCreateLLM:
mock_llm = Mock()
mock_chat_openai.return_value = mock_llm
- result = CustomOpenAIEndpointProvider.create_llm()
+ result = CustomOpenAIEndpointProvider.create_llm(
+ model_name="test-model"
+ )
assert result is mock_llm
call_kwargs = mock_chat_openai.call_args[1]
diff --git a/tests/llm_providers/test_ollama_deep_coverage.py b/tests/llm_providers/test_ollama_deep_coverage.py
index d910b1bfcc..77428a211e 100644
--- a/tests/llm_providers/test_ollama_deep_coverage.py
+++ b/tests/llm_providers/test_ollama_deep_coverage.py
@@ -118,6 +118,34 @@ class TestCreateLlmOlderApiFormat:
# ---------------------------------------------------------------------------
+class TestCreateLlmRequiresModelName:
+ """Direct callers of OllamaProvider.create_llm() must specify a model."""
+
+ def test_raises_when_no_model_name(self):
+ import pytest
+
+ def _get_setting(key, default=None, *args, **kwargs):
+ return {"llm.ollama.url": "http://localhost:11434"}.get(
+ key, default
+ )
+
+ with patch(GET_SETTING, side_effect=_get_setting):
+ with pytest.raises(ValueError, match="Ollama model not configured"):
+ OllamaProvider.create_llm()
+
+ def test_raises_when_model_name_empty_string(self):
+ import pytest
+
+ def _get_setting(key, default=None, *args, **kwargs):
+ return {"llm.ollama.url": "http://localhost:11434"}.get(
+ key, default
+ )
+
+ with patch(GET_SETTING, side_effect=_get_setting):
+ with pytest.raises(ValueError, match="Ollama model not configured"):
+ OllamaProvider.create_llm(model_name="")
+
+
class TestCreateLlmContextWindowNone:
def test_no_num_ctx_when_context_window_none(self):
def _get_setting(key, default=None, *args, **kwargs):
diff --git a/tests/llm_providers/test_ollama_provider.py b/tests/llm_providers/test_ollama_provider.py
index 07c09f2a8f..9cfab4e3cf 100644
--- a/tests/llm_providers/test_ollama_provider.py
+++ b/tests/llm_providers/test_ollama_provider.py
@@ -26,10 +26,11 @@ class TestOllamaProviderMetadata:
"""Ollama is a local provider."""
assert OllamaProvider.is_cloud is False
- def test_default_model(self):
- """Default model is set."""
- assert OllamaProvider.default_model is not None
- assert len(OllamaProvider.default_model) > 0
+ def test_default_model_is_empty(self):
+ """Default model is empty by design — users must explicitly pick
+ one. Mirrors the API-key-not-configured pattern; we don't silently
+ download a multi-GB binary the user never asked for."""
+ assert OllamaProvider.default_model == ""
class TestOllamaGetAuthHeaders:
@@ -181,15 +182,27 @@ class TestOllamaListModels:
class TestOllamaCreateLLM:
"""Tests for create_llm method."""
+ def test_create_llm_raises_without_model(self):
+ """Raises ValueError when no model name is provided."""
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.return_value = "http://localhost:11434"
+
+ with pytest.raises(ValueError) as exc_info:
+ OllamaProvider.create_llm()
+
+ assert "model not configured" in str(exc_info.value).lower()
+
def test_create_llm_raises_without_url(self):
- """Raises ValueError when URL not configured."""
+ """Raises ValueError when URL not configured (model is provided)."""
with patch(
"local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot"
) as mock_get_setting:
mock_get_setting.return_value = None
with pytest.raises(ValueError) as exc_info:
- OllamaProvider.create_llm()
+ OllamaProvider.create_llm(model_name="llama3.1:8b")
assert "url not configured" in str(exc_info.value).lower()
@@ -216,36 +229,11 @@ class TestOllamaCreateLLM:
mock_llm = Mock()
mock_chat_ollama.return_value = mock_llm
- result = OllamaProvider.create_llm()
+ result = OllamaProvider.create_llm(model_name="llama3.1:8b")
assert result is mock_llm
mock_chat_ollama.assert_called_once()
- def test_create_llm_uses_default_model(self):
- """Uses default model when none specified."""
-
- def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
- settings_map = {
- "llm.ollama.url": "http://localhost:11434",
- "llm.local_context_window_size": 8192,
- "llm.supports_max_tokens": True,
- "llm.max_tokens": 4096,
- }
- return settings_map.get(key, default)
-
- with patch(
- "local_deep_research.llm.providers.implementations.ollama.get_setting_from_snapshot"
- ) as mock_get_setting:
- mock_get_setting.side_effect = mock_get_setting_side_effect
-
- with patch(
- "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
- ) as mock_chat_ollama:
- OllamaProvider.create_llm()
-
- call_kwargs = mock_chat_ollama.call_args[1]
- assert call_kwargs["model"] == OllamaProvider.default_model
-
def test_create_llm_with_custom_temperature(self):
"""Uses custom temperature."""
@@ -266,7 +254,9 @@ class TestOllamaCreateLLM:
with patch(
"local_deep_research.llm.providers.implementations.ollama.ChatOllama"
) as mock_chat_ollama:
- OllamaProvider.create_llm(temperature=0.5)
+ OllamaProvider.create_llm(
+ model_name="llama3.1:8b", temperature=0.5
+ )
call_kwargs = mock_chat_ollama.call_args[1]
assert call_kwargs["temperature"] == 0.5
diff --git a/tests/llm_providers/test_openai_base.py b/tests/llm_providers/test_openai_base.py
index 4f2178d884..ced9d61847 100644
--- a/tests/llm_providers/test_openai_base.py
+++ b/tests/llm_providers/test_openai_base.py
@@ -25,8 +25,8 @@ class TestOpenAICompatibleProviderMetadata:
)
def test_default_model(self):
- """Default model is set."""
- assert OpenAICompatibleProvider.default_model == "gpt-3.5-turbo"
+ """Default model is empty by design — users must explicitly pick one."""
+ assert OpenAICompatibleProvider.default_model == ""
def test_api_key_setting(self):
"""API key setting is defined."""
@@ -72,13 +72,15 @@ class TestOpenAICompatibleCreateLLM:
mock_llm = Mock()
mock_chat_openai.return_value = mock_llm
- result = OpenAICompatibleProvider.create_llm()
+ result = OpenAICompatibleProvider.create_llm(
+ model_name="test-model"
+ )
assert result is mock_llm
mock_chat_openai.assert_called_once()
def test_create_llm_uses_default_model(self):
- """Uses default model when none specified."""
+ """Raises ValueError when no model name is provided (no silent default)."""
def mock_get_setting_side_effect(key, default=None, *args, **kwargs):
settings_map = {
@@ -95,14 +97,9 @@ class TestOpenAICompatibleCreateLLM:
) as mock_get_setting:
mock_get_setting.side_effect = mock_get_setting_side_effect
- with patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI"
- ) as mock_chat_openai:
+ with pytest.raises(ValueError, match="model not configured"):
OpenAICompatibleProvider.create_llm()
- call_kwargs = mock_chat_openai.call_args[1]
- assert call_kwargs["model"] == "gpt-3.5-turbo"
-
def test_create_llm_with_custom_model(self):
"""Uses custom model when specified."""
@@ -150,7 +147,9 @@ class TestOpenAICompatibleCreateLLM:
with patch(
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat_openai:
- OpenAICompatibleProvider.create_llm(temperature=0.2)
+ OpenAICompatibleProvider.create_llm(
+ model_name="test-model", temperature=0.2
+ )
call_kwargs = mock_chat_openai.call_args[1]
assert call_kwargs["temperature"] == 0.2
@@ -177,7 +176,8 @@ class TestOpenAICompatibleCreateLLM:
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat_openai:
OpenAICompatibleProvider.create_llm(
- base_url="https://custom.api.com/v1"
+ model_name="test-model",
+ base_url="https://custom.api.com/v1",
)
call_kwargs = mock_chat_openai.call_args[1]
@@ -372,7 +372,9 @@ class TestOpenAICompatibleCreateLLMInstance:
mock_llm = Mock()
mock_chat_openai.return_value = mock_llm
- OpenAICompatibleProvider._create_llm_instance()
+ OpenAICompatibleProvider._create_llm_instance(
+ model_name="test-model"
+ )
call_kwargs = mock_chat_openai.call_args[1]
assert call_kwargs["api_key"] == "dummy-key"
diff --git a/tests/llm_providers/test_openai_base_coverage.py b/tests/llm_providers/test_openai_base_coverage.py
index 5c531a3745..04a4ef1417 100644
--- a/tests/llm_providers/test_openai_base_coverage.py
+++ b/tests/llm_providers/test_openai_base_coverage.py
@@ -86,27 +86,19 @@ class TestCreateLlm:
return_value=mock_llm,
) as MockChat,
):
- _NoKeyProvider.create_llm()
+ _NoKeyProvider.create_llm(model_name="test-model")
# dummy-key was passed
call_kwargs = MockChat.call_args[1]
assert call_kwargs["api_key"] == "dummy-key"
def test_uses_default_model_when_none_given(self):
- """model_name=None → uses cls.default_model."""
- mock_llm = MagicMock()
- with (
- patch(
- "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
- return_value=None,
- ),
- patch(
- "local_deep_research.llm.providers.openai_base.ChatOpenAI",
- return_value=mock_llm,
- ) as MockChat,
+ """model_name=None → raises ValueError (no silent default)."""
+ with patch(
+ "local_deep_research.llm.providers.openai_base.get_setting_from_snapshot",
+ return_value=None,
):
- _NoKeyProvider.create_llm(model_name=None)
- call_kwargs = MockChat.call_args[1]
- assert call_kwargs["model"] == "local-model"
+ with pytest.raises(ValueError, match="model not configured"):
+ _NoKeyProvider.create_llm(model_name=None)
def test_base_url_kwarg_overrides_default(self):
"""Passing base_url kwarg overrides cls.default_base_url."""
@@ -125,7 +117,9 @@ class TestCreateLlm:
return_value=mock_llm,
) as MockChat,
):
- _NoKeyProvider.create_llm(base_url="http://custom.local/v1")
+ _NoKeyProvider.create_llm(
+ model_name="test-model", base_url="http://custom.local/v1"
+ )
call_kwargs = MockChat.call_args[1]
assert "custom.local" in call_kwargs["base_url"]
@@ -148,7 +142,7 @@ class TestCreateLlmInstance:
return_value=mock_llm,
) as MockChat,
):
- _NoKeyProvider._create_llm_instance()
+ _NoKeyProvider._create_llm_instance(model_name="test-model")
call_kwargs = MockChat.call_args[1]
assert call_kwargs["api_key"] == "dummy-key"
diff --git a/tests/llm_providers/test_providers_high_value.py b/tests/llm_providers/test_providers_high_value.py
index 6de2e0b1c6..2f1ffd131d 100644
--- a/tests/llm_providers/test_providers_high_value.py
+++ b/tests/llm_providers/test_providers_high_value.py
@@ -120,7 +120,7 @@ class TestOpenRouterEdgeCases:
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
mock_chat.return_value = Mock()
- OpenRouterProvider.create_llm()
+ OpenRouterProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["api_key"] == " "
@@ -162,7 +162,7 @@ class TestOpenRouterEdgeCases:
"local_deep_research.llm.providers.openai_base.ChatOpenAI"
) as mock_chat:
mock_chat.return_value = Mock()
- OpenRouterProvider.create_llm()
+ OpenRouterProvider.create_llm(model_name="test-model")
call_kwargs = mock_chat.call_args[1]
assert call_kwargs["max_tokens"] == 2048
@@ -307,10 +307,10 @@ class TestCrossProviderConsistency:
"provider_cls",
[LMStudioProvider, OpenRouterProvider, XAIProvider, IONOSProvider],
)
- def test_default_model_is_non_empty(self, provider_cls):
- """Every provider must declare a non-empty default model."""
- assert provider_cls.default_model
- assert len(provider_cls.default_model) > 0
+ def test_default_model_is_empty(self, provider_cls):
+ """Every provider must declare an empty default model — users must
+ explicitly pick one. No silent fallbacks."""
+ assert provider_cls.default_model == ""
@pytest.mark.parametrize(
"provider_cls",
diff --git a/tests/news/test_topic_based_recommender_extended.py b/tests/news/test_topic_based_recommender_extended.py
index 9aa43c1ad9..2bcb1fe846 100644
--- a/tests/news/test_topic_based_recommender_extended.py
+++ b/tests/news/test_topic_based_recommender_extended.py
@@ -445,6 +445,36 @@ class TestCreateRecommendationCard:
assert result is None
+ def test_returns_none_when_llm_not_configured(self):
+ """Returns None when get_llm() raises ValueError; does NOT proceed to construct
+ AdvancedSearchSystem. Scheduler runs repeatedly — must not propagate stack trace.
+ """
+ from local_deep_research.news.recommender.topic_based import (
+ TopicBasedRecommender,
+ )
+
+ with (
+ patch(
+ "local_deep_research.config.llm_config.get_llm"
+ ) as mock_get_llm,
+ patch(
+ "local_deep_research.news.recommender.topic_based.AdvancedSearchSystem"
+ ) as MockSearch,
+ ):
+ mock_get_llm.side_effect = ValueError(
+ "LLM model not configured. ..."
+ )
+
+ recommender = TopicBasedRecommender()
+ result = recommender._create_recommendation_card(
+ "AI", "query", "user1"
+ )
+
+ assert result is None
+ mock_get_llm.assert_called_once()
+ # Critical: we returned before building the search system.
+ MockSearch.assert_not_called()
+
class TestSearchBasedRecommender:
"""Tests for SearchBasedRecommender class."""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 746c334938..d74db8244c 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -935,60 +935,46 @@
"value": null,
"visible": true
},
- "llm.llamacpp_f16_kv": {
+ "llm.llamacpp.api_key": {
"category": null,
- "description": "Use 16-bit floating point for LlamaCpp's key-value cache. Reduces memory usage compared to 32-bit; disable only if you need higher precision and have enough VRAM.",
+ "description": "Optional API key for `llama-server` if it's behind an auth proxy. Leave empty if your llama-server has no authentication.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Llamacpp F16 Kv",
+ "name": "Llamacpp API Key",
"options": null,
"step": null,
"type": "LLM",
- "ui_element": "checkbox",
- "value": true,
+ "ui_element": "password",
+ "value": "",
"visible": true
},
- "llm.llamacpp_model_path": {
+ "llm.llamacpp.url": {
"category": null,
- "description": "Path to GGUF model file relative to models directory (~/.local/share/llm_models/). For llama.cpp server connections, use 'openai_endpoint' provider instead with the server's /v1 URL.",
+ "description": "HTTP endpoint URL where llama.cpp's `llama-server` is running. Include the full path with /v1 (default: http://localhost:8080/v1). Run `llama-server -m <model.gguf>` to start it.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Llamacpp Model Path",
+ "name": "Llamacpp Url",
"options": null,
"step": null,
"type": "LLM",
"ui_element": "text",
- "value": "",
- "visible": true
- },
- "llm.llamacpp_n_batch": {
- "category": null,
- "description": "Batch size for LlamaCpp token processing. Higher values improve inference speed but increase memory usage. Reduce if experiencing out-of-memory errors.",
- "editable": true,
- "max_value": null,
- "min_value": 1,
- "name": "Llamacpp N Batch",
- "options": null,
- "step": null,
- "type": "LLM",
- "ui_element": "number",
- "value": 512,
+ "value": "http://localhost:8080/v1",
"visible": true
},
- "llm.llamacpp_n_gpu_layers": {
+ "llm.lmstudio.api_key": {
"category": null,
- "description": "Number of model layers to offload to GPU for acceleration in LlamaCpp. 0 = CPU only, higher values = more GPU usage and faster inference. Set based on your available VRAM.",
+ "description": "Optional API key for LM Studio if you've enabled authentication. Leave empty for the default no-auth setup.",
"editable": true,
"max_value": null,
- "min_value": 0,
- "name": "Llamacpp N Gpu Layers",
+ "min_value": null,
+ "name": "Lmstudio API Key",
"options": null,
"step": null,
"type": "LLM",
- "ui_element": "number",
- "value": 1,
+ "ui_element": "password",
+ "value": "",
"visible": true
},
"llm.lmstudio.url": {
@@ -1073,7 +1059,7 @@
"step": null,
"type": "LLM",
"ui_element": "select",
- "value": "gemma3:12b",
+ "value": "",
"visible": true
},
"llm.ollama.enable_thinking": {
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index d97e091349..1b76ff29bd 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -56,7 +56,8 @@ KNOWN_SELECT_ISSUES = {
# don't include it (should be e.g. 'midnight' or 'system')
"app.theme",
# Options list is suggestive (common models), not restrictive;
- # user can type any model name. Default 'gemma3:12b' is valid.
+ # user can type any model name. Default is empty so users must
+ # consciously pick a model.
"llm.model",
# Default '265' is a typo — should be '365'.
"search.journal_reputation.reanalysis_period",
diff --git a/tests/test_llm/test_providers.py b/tests/test_llm/test_providers.py
index 9b12c91dee..0bde045d61 100644
--- a/tests/test_llm/test_providers.py
+++ b/tests/test_llm/test_providers.py
@@ -180,7 +180,7 @@ class TestOpenAICompatibleProvider:
OpenAICompatibleProvider.default_base_url
== "https://api.openai.com/v1"
)
- assert OpenAICompatibleProvider.default_model == "gpt-3.5-turbo"
+ assert OpenAICompatibleProvider.default_model == ""
def test_base_provider_has_create_llm_method(self):
"""Base provider has create_llm classmethod."""
diff --git a/tests/test_llm_provider_integration.py b/tests/test_llm_provider_integration.py
index b07d1ba28f..4fae4481b9 100644
--- a/tests/test_llm_provider_integration.py
+++ b/tests/test_llm_provider_integration.py
@@ -34,7 +34,7 @@ class TestLLMProviderIntegration:
"llm.request_timeout": None,
"llm.ollama.url": "http://localhost:11434",
"llm.lmstudio.url": "http://localhost:1234",
- "llm.llamacpp_model_path": None,
+ "llm.llamacpp.url": "http://localhost:8080/v1",
"app.lock_settings": False,
"rate_limiting.llm_enabled": False,
"search.tool": "searxng",
diff --git a/tests/web/routes/test_ollama_status.py b/tests/web/routes/test_ollama_status.py
index 77a8f5a855..d6ea36c831 100644
--- a/tests/web/routes/test_ollama_status.py
+++ b/tests/web/routes/test_ollama_status.py
@@ -327,6 +327,33 @@ class TestCheckOllamaModel:
assert data["available"] is False
assert data["error_type"] == "timeout"
+ def test_model_not_configured_returns_400(self, authenticated_client):
+ """No model in query and llm.model unset → HTTP 400 + error_type."""
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "model": "",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["available"] is False
+ assert data["error_type"] == "model_not_configured"
+ assert data["model"] == ""
+
+ def test_model_not_configured_missing_key(self, authenticated_client):
+ """Same path when 'model' key is absent from config entirely."""
+ authenticated_client.application.config["LLM_CONFIG"] = {
+ "provider": "ollama",
+ "ollama_base_url": "http://localhost:11434",
+ }
+
+ response = authenticated_client.get(f"{API_PREFIX}/check/ollama_model")
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["error_type"] == "model_not_configured"
+
@patch("local_deep_research.web.routes.api_routes.safe_get")
def test_old_api_format(self, mock_safe_get, authenticated_client):
"""Test with old Ollama API format (plain array)."""