Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

refactor: Address PR feedback from djpetti and Copilot

LearningCircuit3b1c67848fe6
diff --git a/src/local_deep_research/llm/providers/__init__.py b/src/local_deep_research/llm/providers/__init__.py
index d65f216254..3b87867b28 100644
--- a/src/local_deep_research/llm/providers/__init__.py
+++ b/src/local_deep_research/llm/providers/__init__.py
@@ -5,13 +5,11 @@ from .auto_discovery import (
get_discovered_provider_options,
get_provider_class,
)
-from .openai_base import GenericOpenAIEndpoint
__all__ = [
"discover_providers",
"get_discovered_provider_options",
"get_provider_class",
- "GenericOpenAIEndpoint",
]
# Auto-discover and register all providers on import
diff --git a/src/local_deep_research/llm/providers/auto_discovery.py b/src/local_deep_research/llm/providers/auto_discovery.py
index bce2ff6488..30c11fa0f8 100644
--- a/src/local_deep_research/llm/providers/auto_discovery.py
+++ b/src/local_deep_research/llm/providers/auto_discovery.py
@@ -115,13 +115,10 @@ class ProviderDiscovery:
# Scan all Python files in the providers directory
for file_path in providers_dir.glob("*.py"):
- # Skip special files and non-auto-discoverable providers
+ # Skip special files and base classes
if file_path.name.startswith("_") or file_path.name in [
"auto_discovery.py",
- "openai_base.py",
- "openai.py", # Has its own registration
- "anthropic.py", # Has its own registration
- "ollama.py", # Has its own registration
+ "openai_base.py", # Base class, not a provider
]:
continue
@@ -146,14 +143,19 @@ class ProviderDiscovery:
provider_info
)
- # Auto-register if it has a register function
+ # Auto-register the provider
register_func_name = f"register_{module_name}_provider"
- if hasattr(module, register_func_name):
+ try:
register_func = getattr(module, register_func_name)
register_func()
logger.info(
f"Auto-registered provider: {provider_info.provider_key}"
)
+ except AttributeError:
+ logger.warning(
+ f"Provider {provider_info.provider_key} from {module_name}.py "
+ f"does not have a {register_func_name} function"
+ )
logger.info(
f"Discovered provider: {provider_info.provider_key} from {module_name}.py"
diff --git a/src/local_deep_research/llm/providers/custom_openai.py b/src/local_deep_research/llm/providers/custom_openai.py
deleted file mode 100644
index a5c29b13f0..0000000000
--- a/src/local_deep_research/llm/providers/custom_openai.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""Custom OpenAI-compatible endpoint provider for Local Deep Research."""
-
-from loguru import logger
-
-from ...config.thread_settings import (
- get_setting_from_snapshot as _get_setting_from_snapshot,
-)
-from ...utilities.url_utils import normalize_url
-from ..llm_registry import register_llm
-from .openai_base import OpenAICompatibleProvider
-
-
-def get_setting_from_snapshot(
- key, default=None, username=None, settings_snapshot=None
-):
- """Get setting from context only - no database access from threads.
-
- This is a wrapper around the shared function that enables fallback LLM check.
- """
- return _get_setting_from_snapshot(
- key, default, username, settings_snapshot, check_fallback_llm=True
- )
-
-
-class CustomOpenAIProvider(OpenAICompatibleProvider):
- """Custom OpenAI-compatible endpoint provider.
-
- This provider allows users to connect to any OpenAI-compatible API endpoint
- by specifying the URL and API key in settings.
- """
-
- provider_name = "Custom OpenAI Endpoint"
- api_key_setting = "llm.openai_endpoint.api_key"
- default_model = "gpt-3.5-turbo" # Default model, user should override
-
- # Metadata for auto-discovery
- provider_key = "OPENAI_ENDPOINT"
- company_name = "Custom"
- region = "Custom"
- country = "User-defined"
- data_location = "User-defined"
- is_cloud = True # Assume cloud by default
-
- @classmethod
- def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
- """Override to get URL from settings."""
- settings_snapshot = kwargs.get("settings_snapshot")
-
- # Get custom endpoint URL from settings
- custom_url = get_setting_from_snapshot(
- "llm.openai_endpoint.url",
- default="https://api.openai.com/v1",
- settings_snapshot=settings_snapshot,
- )
-
- # Normalize and pass the custom URL to parent implementation
- kwargs["base_url"] = (
- normalize_url(custom_url)
- if custom_url
- else "https://api.openai.com/v1"
- )
-
- return super().create_llm(model_name, temperature, **kwargs)
-
- @classmethod
- def list_models_for_api(cls, api_key=None):
- """List available models using the custom endpoint.
-
- For custom endpoints, we need to get the URL from settings.
- This is tricky in API context, so we return empty list for now.
- """
- # Custom endpoints need URL from settings which we can't easily access here
- # Users will need to manually enter model names for custom endpoints
- logger.debug(
- "Custom OpenAI endpoint - model listing not supported in API context"
- )
- return []
-
-
-# Keep the standalone functions for backward compatibility and registration
-def create_custom_openai_llm(model_name=None, temperature=0.7, **kwargs):
- """Factory function for Custom OpenAI-compatible endpoint LLMs.
-
- Args:
- model_name: Name of the model to use
- temperature: Model temperature (0.0-1.0)
- **kwargs: Additional arguments including settings_snapshot
-
- Returns:
- A configured ChatOpenAI instance pointing to custom endpoint
-
- Raises:
- ValueError: If API key is not configured
- """
- return CustomOpenAIProvider.create_llm(model_name, temperature, **kwargs)
-
-
-def is_custom_openai_available(settings_snapshot=None):
- """Check if Custom OpenAI endpoint is available.
-
- Args:
- settings_snapshot: Optional settings snapshot to use
-
- Returns:
- True if API key is configured, False otherwise
- """
- return CustomOpenAIProvider.is_available(settings_snapshot)
-
-
-def register_custom_openai_provider():
- """Register the Custom OpenAI endpoint provider with the LLM registry."""
- register_llm("openai_endpoint", create_custom_openai_llm)
- logger.info("Registered Custom OpenAI Endpoint LLM provider")
diff --git a/src/local_deep_research/llm/providers/custom_openai_endpoint.py b/src/local_deep_research/llm/providers/custom_openai_endpoint.py
new file mode 100644
index 0000000000..343c36d3a8
--- /dev/null
+++ b/src/local_deep_research/llm/providers/custom_openai_endpoint.py
@@ -0,0 +1,166 @@
+"""Custom OpenAI-compatible endpoint provider for Local Deep Research."""
+
+from loguru import logger
+
+from ...config.thread_settings import (
+ get_setting_from_snapshot as _get_setting_from_snapshot,
+)
+from ...utilities.url_utils import normalize_url
+from ..llm_registry import register_llm
+from .openai_base import OpenAICompatibleProvider
+
+
+def get_setting_from_snapshot(
+ key, default=None, username=None, settings_snapshot=None
+):
+ """Get setting from context only - no database access from threads.
+
+ This is a wrapper around the shared function that enables fallback LLM check.
+ """
+ return _get_setting_from_snapshot(
+ key, default, username, settings_snapshot, check_fallback_llm=True
+ )
+
+
+class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
+ """Custom OpenAI-compatible endpoint provider.
+
+ This provider allows users to connect to any OpenAI-compatible API endpoint
+ by specifying a custom URL in the settings.
+ """
+
+ provider_name = "Custom OpenAI Endpoint"
+ api_key_setting = "llm.openai_endpoint.api_key"
+ default_base_url = "https://api.openai.com/v1"
+ default_model = "gpt-3.5-turbo"
+
+ # Metadata for auto-discovery
+ provider_key = "OPENAI_ENDPOINT"
+ company_name = "Custom"
+ region = "Custom"
+ country = "User-defined"
+ data_location = "User-defined"
+ is_cloud = True # Assume cloud by default
+
+ @classmethod
+ def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
+ """Override to get URL from settings."""
+ settings_snapshot = kwargs.get("settings_snapshot")
+
+ # Get custom endpoint URL from settings
+ custom_url = get_setting_from_snapshot(
+ "llm.openai_endpoint.url",
+ default=cls.default_base_url,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Normalize and pass the custom URL to parent implementation
+ kwargs["base_url"] = (
+ normalize_url(custom_url) if custom_url else cls.default_base_url
+ )
+
+ return super().create_llm(model_name, temperature, **kwargs)
+
+ @classmethod
+ def list_models_for_api(cls, api_key=None, settings_snapshot=None):
+ """List available models using the custom endpoint.
+
+ Args:
+ api_key: Optional API key
+ settings_snapshot: Optional settings snapshot for getting custom URL
+
+ Returns:
+ List of model dictionaries with 'value' and 'label' keys
+ """
+ try:
+ # Get custom endpoint URL from settings if available
+ if settings_snapshot:
+ custom_url = get_setting_from_snapshot(
+ "llm.openai_endpoint.url",
+ default=cls.default_base_url,
+ settings_snapshot=settings_snapshot,
+ )
+ base_url = (
+ normalize_url(custom_url)
+ if custom_url
+ else cls.default_base_url
+ )
+ else:
+ # Fall back to default if no settings available
+ base_url = cls.default_base_url
+
+ # Check if auth is required
+ if cls.requires_auth_for_models():
+ if not api_key:
+ logger.debug(
+ f"{cls.provider_name} requires API key for model listing"
+ )
+ return []
+ else:
+ api_key = api_key or "dummy-key-for-models-list"
+
+ from openai import OpenAI
+
+ # Create OpenAI client with custom URL
+ client = OpenAI(api_key=api_key, base_url=base_url)
+
+ # Fetch models
+ logger.debug(
+ f"Fetching models from {cls.provider_name} at {base_url}"
+ )
+ models_response = client.models.list()
+
+ models = []
+ for model in models_response.data:
+ if model.id:
+ models.append(
+ {
+ "value": model.id,
+ "label": model.id,
+ }
+ )
+
+ logger.debug(f"Found {len(models)} models from {cls.provider_name}")
+ return models
+
+ except Exception:
+ logger.exception(f"Error listing models from {cls.provider_name}")
+ return []
+
+
+# Keep the standalone functions for backward compatibility
+def create_openai_endpoint_llm(model_name=None, temperature=0.7, **kwargs):
+ """Factory function for custom OpenAI-compatible endpoint LLMs.
+
+ Args:
+ model_name: Name of the model to use
+ temperature: Model temperature (0.0-1.0)
+ **kwargs: Additional arguments including settings_snapshot
+
+ Returns:
+ A configured ChatOpenAI instance pointing to custom endpoint
+
+ Raises:
+ ValueError: If API key is not configured
+ """
+ return CustomOpenAIEndpointProvider.create_llm(
+ model_name, temperature, **kwargs
+ )
+
+
+def is_openai_endpoint_available(settings_snapshot=None):
+ """Check if custom OpenAI endpoint is available.
+
+ Args:
+ settings_snapshot: Optional settings snapshot to use
+
+ Returns:
+ True if API key is configured, False otherwise
+ """
+ return CustomOpenAIEndpointProvider.is_available(settings_snapshot)
+
+
+def register_custom_openai_endpoint_provider():
+ """Register the custom OpenAI endpoint provider with the LLM registry."""
+ register_llm("openai_endpoint", create_openai_endpoint_llm)
+ logger.info("Registered Custom OpenAI Endpoint LLM provider")
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index b0b83cd996..165e5472ec 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -221,14 +221,14 @@ class OpenAICompatibleProvider:
return True
@classmethod
- def list_models_for_api(cls, api_key=None):
+ def list_models_for_api(cls, api_key=None, settings_snapshot=None):
"""List available models for API endpoint use.
- This method is designed to be called from Flask routes where we don't
- have settings_snapshot but do have session access.
+ This method is designed to be called from Flask routes.
Args:
api_key: Optional API key (if None and required, returns empty list)
+ settings_snapshot: Optional settings snapshot for provider-specific configuration
Returns:
List of model dictionaries with 'value' and 'label' keys
@@ -295,41 +295,11 @@ class OpenAICompatibleProvider:
settings_snapshot=settings_snapshot,
)
- # Use the shared implementation
- return cls.list_models_for_api(api_key)
+ # Use the shared implementation with settings_snapshot
+ return cls.list_models_for_api(api_key, settings_snapshot)
except Exception as e:
logger.exception(
f"Error listing models from {cls.provider_name}: {e}"
)
return []
-
-
-class GenericOpenAIEndpoint(OpenAICompatibleProvider):
- """Generic OpenAI-compatible endpoint provider.
-
- This is the default implementation that reads the URL from settings.
- Used when provider is set to "openai_endpoint".
- """
-
- provider_name = "OpenAI-compatible endpoint"
- api_key_setting = "llm.openai_endpoint.api_key"
- default_base_url = "https://api.openai.com/v1"
- default_model = "gpt-3.5-turbo"
-
- @classmethod
- def create_llm(cls, model_name=None, temperature=0.7, **kwargs):
- """Override to get URL from settings."""
- settings_snapshot = kwargs.get("settings_snapshot")
-
- # Get custom endpoint URL from settings
- custom_url = get_setting_from_snapshot(
- "llm.openai_endpoint.url",
- default=cls.default_base_url,
- settings_snapshot=settings_snapshot,
- )
-
- # Pass the custom URL to parent implementation
- kwargs["base_url"] = custom_url
-
- return super().create_llm(model_name, temperature, **kwargs)
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 69ae24ff57..e9a6d5193b 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -933,19 +933,10 @@ def api_get_available_models():
request.args.get("force_refresh", "false").lower() == "true"
)
- # Get discovered providers
+ # Get all auto-discovered providers
from ...llm.providers import get_discovered_provider_options
- # Start with hardcoded providers that aren't auto-discovered yet
- provider_options = [
- {"value": "OLLAMA", "label": "Ollama (Local)"},
- {"value": "OPENAI", "label": "OpenAI (Cloud)"},
- {"value": "ANTHROPIC", "label": "Anthropic (Cloud)"},
- ]
-
- # Add auto-discovered providers
- discovered_options = get_discovered_provider_options()
- provider_options.extend(discovered_options)
+ provider_options = get_discovered_provider_options()
# Add remaining hardcoded providers (complex local providers not yet migrated)
provider_options.extend(
@@ -1105,7 +1096,6 @@ def api_get_available_models():
f"Added Ollama model: {name} -> {display_name}"
)
-
except json.JSONDecodeError as json_err:
logger.exception(
f"Failed to parse Ollama API response as JSON: {json_err}"
@@ -1181,7 +1171,9 @@ def api_get_available_models():
try:
logger.info("Fetching Custom OpenAI Endpoint models")
- from ...llm.providers.openai_base import GenericOpenAIEndpoint
+ from ...llm.providers.custom_openai_endpoint import (
+ CustomOpenAIEndpointProvider,
+ )
# Get the endpoint URL and API key from settings
endpoint_url = _get_setting_from_session(
@@ -1193,12 +1185,14 @@ def api_get_available_models():
if endpoint_url and api_key:
# Need to temporarily set the URL for the provider class
- original_url = GenericOpenAIEndpoint.default_base_url
- GenericOpenAIEndpoint.default_base_url = endpoint_url
+ original_url = CustomOpenAIEndpointProvider.default_base_url
+ CustomOpenAIEndpointProvider.default_base_url = endpoint_url
try:
# Use the provider's list_models_for_api method
- models = GenericOpenAIEndpoint.list_models_for_api(api_key)
+ models = CustomOpenAIEndpointProvider.list_models_for_api(
+ api_key
+ )
# Format models for the API response
for model in models:
@@ -1222,7 +1216,7 @@ def api_get_available_models():
finally:
# Restore original URL
- GenericOpenAIEndpoint.default_base_url = original_url
+ CustomOpenAIEndpointProvider.default_base_url = original_url
else:
logger.info(
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 9e367715c4..9a060abdc7 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -1638,8 +1638,8 @@
// Process all provider models dynamically
if (data.providers) {
- // Clear and rebuild availableModels
- availableModels = {};
+ // Create a new object to avoid race conditions
+ const newAvailableModels = {};
// Iterate through all providers in the response
Object.keys(data.providers).forEach(providerKey => {
@@ -1647,8 +1647,8 @@
const providerName = providerKey.replace('_models', '').toUpperCase();
// Initialize array for this provider
- if (!availableModels[providerName]) {
- availableModels[providerName] = [];
+ if (!newAvailableModels[providerName]) {
+ newAvailableModels[providerName] = [];
}
// Process each model for this provider
@@ -1661,11 +1661,13 @@
provider: model.provider || providerName
};
formatted.push(formattedModel);
- availableModels[providerName].push(formattedModel);
+ newAvailableModels[providerName].push(formattedModel);
});
}
});
+ // Atomically update the global variable
+ availableModels = newAvailableModels;
console.log('Dynamically populated availableModels:', availableModels);
}