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.

feat(lmstudio): add optional API key support for authenticated instances (#3573) (#3740)

LearningCircuit1b558bc1ba49
diff --git a/.gitleaks.toml b/.gitleaks.toml
index bf9d56e206..1faba353c2 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -108,6 +108,8 @@ paths = [
# LLM and embedding provider implementations use api_key/provider_key variable names (not actual secrets)
'''src/local_deep_research/llm/providers/.*\.py$''',
'''src/local_deep_research/embeddings/providers/.*\.py$''',
+ # LLM config dispatcher constructs ChatOpenAI/ChatOllama with api_key= kwargs (not actual secrets)
+ '''src/local_deep_research/config/llm_config\.py$''',
# Web search engines use api_key variable names (not actual secrets)
'''src/local_deep_research/web_search_engines/engines/.*\.py$''',
'''src/local_deep_research/web_search_engines/search_engine_factory\.py$''',
diff --git a/docker-compose.yml b/docker-compose.yml
index 84fb294cbd..df4845b9ca 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -118,6 +118,7 @@ services:
# ============================================================================
# - LDR_LLM_PROVIDER=lmstudio
# - LDR_LLM_LMSTUDIO_URL=http://host.docker.internal:1234
+ # - LDR_LLM_LMSTUDIO_API_KEY=<api-key-if-required> # optional; leave out for unauth instances
# - LDR_LLM_MODEL=<your-loaded-model-name>
volumes:
- ldr_data:/data
diff --git a/docs/docker-compose-guide.md b/docs/docker-compose-guide.md
index b8c6e229b9..3a16a4b647 100644
--- a/docs/docker-compose-guide.md
+++ b/docs/docker-compose-guide.md
@@ -147,6 +147,7 @@ environment:
environment:
- LDR_LLM_PROVIDER=lmstudio
- LDR_LLM_LMSTUDIO_URL=http://host.docker.internal:1234/v1
+ # - LDR_LLM_LMSTUDIO_API_KEY=<api-key-if-required> # optional; leave out for unauth instances
- LDR_LLM_MODEL=<your-loaded-model>
```
diff --git a/docs/faq.md b/docs/faq.md
index bc1714ed79..1659cdeae5 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -270,6 +270,10 @@ services:
```
Then use `http://host.docker.internal:1234`
+### No models appear after I set my LM Studio API key
+
+If you paste the API key into Settings → LLM → LM Studio and immediately click the model-refresh button, the key may not have been saved yet — the field saves on blur (when you click or tab away from it), not on keypress. Click outside the API key field, or press Tab, to save the value first, then click the refresh button. The model list should populate normally.
+
### Context length not respected
Known issue with Ollama (#500). Workaround:
diff --git a/src/local_deep_research/llm/providers/implementations/lmstudio.py b/src/local_deep_research/llm/providers/implementations/lmstudio.py
index 9187705f88..89fa55c386 100644
--- a/src/local_deep_research/llm/providers/implementations/lmstudio.py
+++ b/src/local_deep_research/llm/providers/implementations/lmstudio.py
@@ -9,6 +9,8 @@ class LMStudioProvider(OpenAICompatibleProvider):
"""LM Studio provider using OpenAI-compatible endpoint.
LM Studio provides a local OpenAI-compatible API for running models.
+ Recent LM Studio versions can require an API key on the local server;
+ the key is optional here so unauthenticated instances keep working.
"""
provider_name = "LM Studio"
@@ -27,6 +29,30 @@ class LMStudioProvider(OpenAICompatibleProvider):
company_name = "LM Studio"
is_cloud = False # Local provider
+ # Hardcoded since `api_key_setting` is None at the class level (the route
+ # reads via `cls.api_key_setting`; LM Studio handles the key inside its
+ # own methods instead, so the route's path stays neutral).
+ _API_KEY_PATH = "llm.lmstudio.api_key"
+
+ @classmethod
+ def _get_auth_headers(cls, settings_snapshot=None):
+ """Build Authorization header from the optional API key setting.
+
+ Returns an empty dict when no key is configured so unauthenticated
+ LM Studio instances continue to work.
+ """
+ from ....config.thread_settings import get_setting_from_snapshot
+
+ headers: dict[str, str] = {}
+ api_key = get_setting_from_snapshot(
+ cls._API_KEY_PATH,
+ "",
+ settings_snapshot=settings_snapshot,
+ )
+ if api_key and str(api_key).strip():
+ headers["Authorization"] = f"Bearer {str(api_key).strip()}"
+ return headers
+
@classmethod
def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
"""Override to handle LM Studio specifics."""
@@ -41,7 +67,7 @@ class LMStudioProvider(OpenAICompatibleProvider):
settings_snapshot=settings_snapshot,
)
api_key = get_setting_from_snapshot(
- "llm.lmstudio.api_key",
+ cls._API_KEY_PATH,
"",
settings_snapshot=settings_snapshot,
)
@@ -59,7 +85,12 @@ class LMStudioProvider(OpenAICompatibleProvider):
@classmethod
def is_available(cls, settings_snapshot=None):
- """Check if LM Studio is available."""
+ """Check if LM Studio is available.
+
+ Sends ``Authorization: Bearer`` when a key is configured so
+ authenticated LM Studio instances are correctly detected as available.
+ Empty key → no auth header → unauthenticated installs still work.
+ """
try:
from ....config.thread_settings import get_setting_from_snapshot
from ....security import safe_get
@@ -71,10 +102,10 @@ class LMStudioProvider(OpenAICompatibleProvider):
)
# Use URL as-is (default already includes /v1)
base_url = normalize_url(lmstudio_url)
- # LM Studio typically uses OpenAI-compatible endpoints
response = safe_get(
f"{base_url}/models",
timeout=1,
+ headers=cls._get_auth_headers(settings_snapshot),
allow_localhost=True,
allow_private_ips=True,
)
@@ -84,5 +115,43 @@ class LMStudioProvider(OpenAICompatibleProvider):
@classmethod
def requires_auth_for_models(cls):
- """LM Studio doesn't require authentication for listing models."""
+ """LM Studio doesn't require authentication for listing models.
+
+ Returning False keeps unauthenticated installs working (parent
+ ``list_models_for_api`` substitutes a dummy key when the real key is
+ falsy). Authenticated installs are handled by the override of
+ ``list_models_for_api`` below, which reads the user's key from
+ settings when no key is passed in directly by the caller.
+ """
return False
+
+ @classmethod
+ def list_models_for_api(cls, api_key=None, base_url=None):
+ """List models, attaching the optional API key when configured.
+
+ When ``api_key`` is provided directly (e.g., from the settings route),
+ it is used as-is. When the caller doesn't supply a key (e.g., via the
+ high-level ``list_models(settings_snapshot)`` classmethod), the key is
+ read from settings here so authenticated installs are handled
+ correctly on both paths. Empty/whitespace falls through to the
+ parent's dummy-key path, preserving backward compat for
+ unauthenticated installs.
+ """
+ from ....config.thread_settings import get_setting_from_snapshot
+
+ if not api_key:
+ raw = get_setting_from_snapshot(
+ cls._API_KEY_PATH,
+ "",
+ settings_snapshot=None,
+ )
+ api_key = str(raw or "").strip() or None
+
+ if not base_url:
+ base_url = get_setting_from_snapshot(
+ cls.url_setting,
+ cls.default_base_url,
+ settings_snapshot=None,
+ )
+
+ return super().list_models_for_api(api_key=api_key, base_url=base_url)
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 45f2b9fb61..eb8196910e 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -39,6 +39,8 @@
let openaiEndpointApiKeyContainer = null;
let ollamaApiKeyInput = null;
let ollamaApiKeyContainer = null;
+ let lmstudioApiKeyInput = null;
+ let lmstudioApiKeyContainer = null;
let modelInput = null;
let modelDropdown = null;
let modelDropdownList = null;
@@ -276,6 +278,8 @@
openaiEndpointApiKeyContainer = document.getElementById('openai_endpoint_api_key_container');
ollamaApiKeyInput = document.getElementById('ollama_api_key');
ollamaApiKeyContainer = document.getElementById('ollama_api_key_container');
+ lmstudioApiKeyInput = document.getElementById('lmstudio_api_key');
+ lmstudioApiKeyContainer = document.getElementById('lmstudio_api_key_container');
// Custom dropdown elements
modelInput = document.getElementById('model');
@@ -777,6 +781,9 @@
if (ollamaApiKeyContainer) {
ollamaApiKeyContainer.style.display = provider === 'OLLAMA' ? 'block' : 'none';
}
+ if (lmstudioApiKeyContainer) {
+ lmstudioApiKeyContainer.style.display = provider === 'LMSTUDIO' ? 'block' : 'none';
+ }
// Update model options based on provider
// Don't reset model selection - preserve it if valid for new provider
@@ -899,6 +906,11 @@
saveSearchSetting('llm.ollama.api_key', this.value);
});
}
+ if (lmstudioApiKeyInput) {
+ lmstudioApiKeyInput.addEventListener('change', function() {
+ saveSearchSetting('llm.lmstudio.api_key', this.value);
+ });
+ }
// Load options data from APIs
Promise.all([
@@ -1027,6 +1039,9 @@
if (ollamaApiKeyContainer) {
ollamaApiKeyContainer.style.display = selectedProvider === 'OLLAMA' ? 'block' : 'none';
}
+ if (lmstudioApiKeyContainer) {
+ lmstudioApiKeyContainer.style.display = selectedProvider === 'LMSTUDIO' ? 'block' : 'none';
+ }
// Initial update of model options
const providerToUpdate = modelProviderSelect.value || initialProvider.toUpperCase();
@@ -1431,6 +1446,9 @@
if (ollamaApiKeyContainer) {
ollamaApiKeyContainer.style.display = providerValue === 'OLLAMA' ? 'block' : 'none';
}
+ if (lmstudioApiKeyContainer) {
+ lmstudioApiKeyContainer.style.display = providerValue === 'LMSTUDIO' ? 'block' : 'none';
+ }
}
// Update the custom endpoint URl if we have one.
@@ -1515,6 +1533,12 @@
ollamaApiKeyInput.disabled = !ollamaApiKeySetting.editable;
}
+ const lmstudioApiKeySetting = data.settings['llm.lmstudio.api_key'];
+ if (lmstudioApiKeySetting && lmstudioApiKeyInput) {
+ lmstudioApiKeyInput.value = lmstudioApiKeySetting.value || '';
+ lmstudioApiKeyInput.disabled = !lmstudioApiKeySetting.editable;
+ }
+
// Load model options based on the current provider
const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
updateModelOptionsForProvider(currentProvider, false).then(() => {
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 1ec1381746..095324e2b8 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -180,6 +180,14 @@
placeholder="Optional, for authenticated instances" autocomplete="off">
<span class="ldr-input-help">Only needed for authenticated Ollama instances</span>
</div>
+
+ <!-- LM Studio API Key (hidden by default, optional for authenticated instances) -->
+ <div class="ldr-form-group ldr-half" id="lmstudio_api_key_container" style="display: none;">
+ <label for="lmstudio_api_key">LM Studio API Key (Optional)</label>
+ <input type="password" id="lmstudio_api_key" name="lmstudio_api_key" class="ldr-form-control"
+ placeholder="Optional, for authenticated instances" autocomplete="off">
+ <span class="ldr-input-help">Only needed if your LM Studio server requires an API key</span>
+ </div>
</div>
<div class="ldr-form-row">
diff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.py
index c5ffba8f47..b985e8d36f 100644
--- a/tests/config/test_llm_config.py
+++ b/tests/config/test_llm_config.py
@@ -788,6 +788,70 @@ class TestGetLlm:
assert call_kwargs["model"] == "local-model"
assert "localhost:1234" in call_kwargs.get("base_url", "")
+ def test_lmstudio_passes_configured_api_key(self):
+ """User-set llm.lmstudio.api_key flows through the direct get_llm path."""
+ from langchain_openai import ChatOpenAI
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": "local-model",
+ "llm.temperature": 0.7,
+ "llm.provider": "lmstudio",
+ "llm.lmstudio.url": "http://localhost:1234",
+ "llm.lmstudio.api_key": "my-secret-key",
+ "llm.local_context_window_size": 4096,
+ "llm.context_window_unrestricted": False,
+ "llm.context_window_size": 8192,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "rate_limiting.llm_enabled": False,
+ }.get(key, default)
+
+ with patch.object(
+ ChatOpenAI, "__init__", return_value=None
+ ) as mock_init:
+ get_llm(provider="lmstudio")
+ call_kwargs = mock_init.call_args.kwargs
+ assert call_kwargs["api_key"] == "my-secret-key"
+
+ def test_lmstudio_falls_back_to_placeholder_when_no_api_key(self):
+ """Empty/missing llm.lmstudio.api_key falls back to the placeholder."""
+ from langchain_openai import ChatOpenAI
+
+ with patch(
+ "local_deep_research.config.llm_config.is_llm_registered",
+ return_value=False,
+ ):
+ with patch(
+ "local_deep_research.config.llm_config.get_setting_from_snapshot"
+ ) as mock_get:
+ mock_get.side_effect = lambda key, default=None, **kwargs: {
+ "llm.model": "local-model",
+ "llm.temperature": 0.7,
+ "llm.provider": "lmstudio",
+ "llm.lmstudio.url": "http://localhost:1234",
+ "llm.lmstudio.api_key": "",
+ "llm.local_context_window_size": 4096,
+ "llm.context_window_unrestricted": False,
+ "llm.context_window_size": 8192,
+ "llm.supports_max_tokens": True,
+ "llm.max_tokens": 4096,
+ "rate_limiting.llm_enabled": False,
+ }.get(key, default)
+
+ with patch.object(
+ ChatOpenAI, "__init__", return_value=None
+ ) as mock_init:
+ get_llm(provider="lmstudio")
+ call_kwargs = mock_init.call_args.kwargs
+ assert call_kwargs["api_key"] == "lm-studio"
+
def test_custom_factory_function_is_called(self):
"""Should call factory function for custom registered LLM."""
from langchain_core.language_models import BaseChatModel
diff --git a/tests/llm_providers/implementations/test_lmstudio_provider.py b/tests/llm_providers/implementations/test_lmstudio_provider.py
index a5b30a0146..755eb48c26 100644
--- a/tests/llm_providers/implementations/test_lmstudio_provider.py
+++ b/tests/llm_providers/implementations/test_lmstudio_provider.py
@@ -247,6 +247,46 @@ class TestLMStudioIsAvailable:
result = LMStudioProvider.is_available()
assert result is False
+ def test_is_available_sends_bearer_header_when_key_set(self):
+ """Sends Authorization: Bearer header when a 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-secret"
+ )
+
+ 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
+
+ LMStudioProvider.is_available()
+
+ _args, call_kwargs = mock_get.call_args
+ assert call_kwargs["headers"] == {
+ "Authorization": "Bearer my-secret"
+ }
+
+ def test_is_available_no_auth_header_when_key_empty(self):
+ """Sends no Authorization header when no 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"
+ )
+
+ 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
+
+ LMStudioProvider.is_available()
+
+ _args, call_kwargs = mock_get.call_args
+ assert call_kwargs["headers"] == {}
+
class TestLMStudioRequiresAuth:
"""Tests for requires_auth_for_models method."""
@@ -254,3 +294,68 @@ class TestLMStudioRequiresAuth:
def test_does_not_require_auth_for_models(self):
"""LM Studio doesn't require authentication for listing models."""
assert LMStudioProvider.requires_auth_for_models() is False
+
+
+class TestLMStudioListModels:
+ """Tests for the list_models_for_api override."""
+
+ def test_list_models_uses_dummy_key_when_no_key_set(self):
+ """Falls back to parent's dummy-key path when no 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"
+ )
+
+ with patch("openai.OpenAI") as mock_openai_cls:
+ mock_client = Mock()
+ mock_openai_cls.return_value = mock_client
+ mock_client.models.list.return_value = Mock(data=[])
+
+ result = LMStudioProvider.list_models_for_api()
+
+ assert result == []
+ call_kwargs = mock_openai_cls.call_args.kwargs
+ assert call_kwargs["api_key"] == "dummy-key-for-models-list"
+
+ def test_list_models_sends_user_key_when_set(self):
+ """Reads the user's key from settings when caller didn't supply one."""
+ 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-secret"
+ )
+
+ with patch("openai.OpenAI") as mock_openai_cls:
+ mock_client = Mock()
+ mock_openai_cls.return_value = mock_client
+ mock_model = Mock()
+ mock_model.id = "llama-3"
+ mock_client.models.list.return_value = Mock(data=[mock_model])
+
+ result = LMStudioProvider.list_models_for_api()
+
+ call_kwargs = mock_openai_cls.call_args.kwargs
+ assert call_kwargs["api_key"] == "my-secret"
+ assert result == [{"value": "llama-3", "label": "llama-3"}]
+
+ def test_list_models_passthrough_key_not_overwritten(self):
+ """Caller-provided key short-circuits the settings read entirely."""
+ with patch(
+ "local_deep_research.config.thread_settings.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ with patch("openai.OpenAI") as mock_openai_cls:
+ mock_client = Mock()
+ mock_openai_cls.return_value = mock_client
+ mock_client.models.list.return_value = Mock(data=[])
+
+ LMStudioProvider.list_models_for_api(
+ api_key="route-provided-key",
+ base_url="http://localhost:1234/v1",
+ )
+
+ mock_get_setting.assert_not_called()
+ call_kwargs = mock_openai_cls.call_args.kwargs
+ assert call_kwargs["api_key"] == "route-provided-key"