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: Add Google Gemini and OpenRouter LLM provider support

LearningCircuitae1054a62ab8
diff --git a/src/local_deep_research/llm/providers/google.py b/src/local_deep_research/llm/providers/google.py
index c31e7e2ffe..5c3a46b0d0 100644
--- a/src/local_deep_research/llm/providers/google.py
+++ b/src/local_deep_research/llm/providers/google.py
@@ -19,6 +19,72 @@ class GoogleProvider(OpenAICompatibleProvider):
default_base_url = "https://generativelanguage.googleapis.com/v1beta/openai"
default_model = "gemini-1.5-flash"
+ @classmethod
+ def requires_auth_for_models(cls):
+ """Google requires authentication for listing models.
+
+ Note: Google's OpenAI-compatible /models endpoint has a bug (returns 401).
+ The native Gemini API endpoint requires an API key.
+ """
+ return True
+
+ @classmethod
+ def list_models_for_api(cls, api_key=None):
+ """List available models using Google's native API.
+
+ Google's OpenAI-compatible /models endpoint returns 401 (bug),
+ so we use the native Gemini API endpoint instead.
+ """
+ if not api_key:
+ logger.debug("Google Gemini requires API key for listing models")
+ return []
+
+ try:
+ import requests
+
+ # Use the native Gemini API endpoint (not OpenAI-compatible)
+ url = f"https://generativelanguage.googleapis.com/v1beta/models?key={api_key}"
+
+ response = requests.get(url, timeout=10)
+
+ if response.status_code == 200:
+ data = response.json()
+ models = []
+
+ for model in data.get("models", []):
+ model_name = model.get("name", "")
+ # Extract just the model ID from "models/gemini-1.5-flash"
+ if model_name.startswith("models/"):
+ model_id = model_name[7:] # Remove "models/" prefix
+ else:
+ model_id = model_name
+
+ # Only include generative models (not embedding models)
+ supported_methods = model.get(
+ "supportedGenerationMethods", []
+ )
+ if "generateContent" in supported_methods and model_id:
+ models.append(
+ {
+ "value": model_id,
+ "label": model_id,
+ }
+ )
+
+ logger.info(
+ f"Found {len(models)} generative models from Google Gemini API"
+ )
+ return models
+ else:
+ logger.warning(
+ f"Google Gemini API returned status {response.status_code}"
+ )
+ return []
+
+ except Exception:
+ logger.exception("Error fetching Google Gemini models")
+ return []
+
# Keep the standalone functions for backward compatibility and registration
def create_google_llm(model_name=None, temperature=0.7, **kwargs):
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index 604b52d4ba..5775bdd77c 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -158,6 +158,101 @@ class OpenAICompatibleProvider:
except Exception:
return False
+ @classmethod
+ def requires_auth_for_models(cls):
+ """Check if this provider requires authentication for listing models.
+
+ Override in subclasses that don't require auth.
+
+ Returns:
+ True if authentication is required, False otherwise
+ """
+ return True
+
+ @classmethod
+ def list_models_for_api(cls, api_key=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.
+
+ Args:
+ api_key: Optional API key (if None and required, returns empty list)
+
+ Returns:
+ List of model dictionaries with 'value' and 'label' keys
+ """
+ try:
+ # 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:
+ # Use a dummy key for providers that don't require auth
+ api_key = api_key or "dummy-key-for-models-list"
+
+ from openai import OpenAI
+
+ # Create OpenAI client
+ client = OpenAI(api_key=api_key, base_url=cls.default_base_url)
+
+ # Fetch models
+ logger.debug(
+ f"Fetching models from {cls.provider_name} at {cls.default_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.info(f"Found {len(models)} models from {cls.provider_name}")
+ return models
+
+ except Exception as e:
+ logger.exception(
+ f"Error listing models from {cls.provider_name}: {e}"
+ )
+ return []
+
+ @classmethod
+ def list_models(cls, settings_snapshot=None):
+ """List available models from this provider.
+
+ Args:
+ settings_snapshot: Optional settings snapshot to use
+
+ Returns:
+ List of model dictionaries with 'value' and 'label' keys
+ """
+ try:
+ # Get API key from settings if auth is required
+ api_key = None
+ if cls.requires_auth_for_models():
+ api_key = get_setting_from_snapshot(
+ cls.api_key_setting,
+ default=None,
+ settings_snapshot=settings_snapshot,
+ )
+
+ # Use the shared implementation
+ return cls.list_models_for_api(api_key)
+
+ except Exception as e:
+ logger.exception(
+ f"Error listing models from {cls.provider_name}: {e}"
+ )
+ return []
+
class GenericOpenAIEndpoint(OpenAICompatibleProvider):
"""Generic OpenAI-compatible endpoint provider.
diff --git a/src/local_deep_research/llm/providers/openrouter.py b/src/local_deep_research/llm/providers/openrouter.py
index fe48a99843..9d355d0b7d 100644
--- a/src/local_deep_research/llm/providers/openrouter.py
+++ b/src/local_deep_research/llm/providers/openrouter.py
@@ -21,6 +21,11 @@ class OpenRouterProvider(OpenAICompatibleProvider):
"meta-llama/llama-3.2-3b-instruct:free" # A free model as default
)
+ @classmethod
+ def requires_auth_for_models(cls):
+ """OpenRouter doesn't require authentication for listing models."""
+ return False
+
# Keep the standalone functions for backward compatibility and registration
def create_openrouter_llm(model_name=None, temperature=0.7, **kwargs):
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 52a427a042..b49b463f91 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -134,6 +134,21 @@ def login():
logger.info(f"User {username} logged in successfully")
+ # Clear the model cache on login to ensure fresh provider data
+ try:
+ from ...database.models import ProviderModel
+
+ user_db_session = db_manager.get_session(username)
+ if user_db_session:
+ # Delete all cached models for this user
+ deleted_count = user_db_session.query(ProviderModel).delete()
+ user_db_session.commit()
+ logger.info(
+ f"Cleared {deleted_count} cached models for user {username} on login"
+ )
+ except Exception:
+ logger.exception("Failed to clear model cache on login")
+
# Redirect to original requested page or dashboard
# Validate redirect URL to prevent open redirect vulnerability
from urllib.parse import urlparse
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 942ecb3e54..930d45f566 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -938,6 +938,8 @@ def api_get_available_models():
{"value": "OLLAMA", "label": "Ollama (Local)"},
{"value": "OPENAI", "label": "OpenAI (Cloud)"},
{"value": "ANTHROPIC", "label": "Anthropic (Cloud)"},
+ {"value": "GOOGLE", "label": "Google Gemini (Cloud)"},
+ {"value": "OPENROUTER", "label": "OpenRouter (Cloud)"},
{"value": "OPENAI_ENDPOINT", "label": "Custom OpenAI Endpoint"},
{"value": "VLLM", "label": "vLLM (Local)"},
{"value": "LMSTUDIO", "label": "LM Studio (Local)"},
@@ -1094,8 +1096,7 @@ def api_get_available_models():
f"Added Ollama model: {name} -> {display_name}"
)
- # Sort models alphabetically
- ollama_models.sort(key=lambda x: x["label"])
+ # Keep original order from Ollama
except json.JSONDecodeError as json_err:
logger.exception(
@@ -1167,12 +1168,12 @@ def api_get_available_models():
},
]
- # Try to get Custom OpenAI Endpoint models using the OpenAI package
+ # Try to get Custom OpenAI Endpoint models using the provider class
openai_endpoint_models = []
try:
- logger.info(
- "Attempting to connect to Custom OpenAI Endpoint using OpenAI package"
- )
+ logger.info("Fetching Custom OpenAI Endpoint models")
+
+ from ...llm.providers.openai_base import GenericOpenAIEndpoint
# Get the endpoint URL and API key from settings
endpoint_url = _get_setting_from_session(
@@ -1183,99 +1184,46 @@ def api_get_available_models():
)
if endpoint_url and api_key:
- # Import OpenAI package here to avoid dependency issues if not installed
- import openai
- from openai import OpenAI
-
- # Create OpenAI client with custom endpoint
- client = OpenAI(api_key=api_key, base_url=endpoint_url)
+ # Need to temporarily set the URL for the provider class
+ original_url = GenericOpenAIEndpoint.default_base_url
+ GenericOpenAIEndpoint.default_base_url = endpoint_url
try:
- # Fetch models using the client
- logger.debug("Fetching models from OpenAI API")
- models_response = client.models.list()
-
- # Process models from the response
- for model in models_response.data:
- model_id = model.id
- if model_id:
- # Create a clean display name
- display_name = model_id.replace("-", " ").strip()
- display_name = " ".join(
- word.capitalize()
- for word in display_name.split()
- )
-
- openai_endpoint_models.append(
- {
- "value": model_id,
- "label": f"{display_name} (Custom)",
- "provider": "OPENAI_ENDPOINT",
- }
- )
- logger.debug(
- f"Added Custom OpenAI Endpoint model: {model_id} -> {display_name}"
- )
-
- # Sort models alphabetically
- openai_endpoint_models.sort(key=lambda x: x["label"])
-
- except openai.APIError as api_err:
- logger.exception(f"OpenAI API error: {api_err!s}")
- raise Exception(f"OpenAI API error: {api_err!s}")
+ # Use the provider's list_models_for_api method
+ models = GenericOpenAIEndpoint.list_models_for_api(api_key)
+
+ # Format models for the API response
+ for model in models:
+ # Create a clean display name
+ display_name = model["label"].replace("-", " ").strip()
+ display_name = " ".join(
+ word.capitalize() for word in display_name.split()
+ )
- else:
- logger.info("OpenAI Endpoint URL or API key not configured")
- # Don't raise an exception, just continue with empty models list
+ openai_endpoint_models.append(
+ {
+ "value": model["value"],
+ "label": f"{display_name} (Custom)",
+ "provider": "OPENAI_ENDPOINT",
+ }
+ )
- except ImportError:
- logger.warning(
- "OpenAI package not installed. Using manual API request fallback."
- )
- # Fallback to manual API request if OpenAI package is not installed
- try:
- if endpoint_url and api_key:
- # Ensure the URL ends with a slash
- if not endpoint_url.endswith("/"):
- endpoint_url += "/"
-
- # Make the request to the endpoint's models API
- headers = {"Authorization": f"Bearer {api_key}"}
- endpoint_response = requests.get(
- f"{endpoint_url}models", headers=headers, timeout=5
+ logger.info(
+ f"Successfully fetched {len(openai_endpoint_models)} models from Custom OpenAI Endpoint"
)
- if endpoint_response.status_code == 200:
- endpoint_data = endpoint_response.json()
- # Process models from the response
- if "data" in endpoint_data:
- for model in endpoint_data.get("data", []):
- model_id = model.get("id", "")
- if model_id:
- # Create a clean display name
- display_name = model_id.replace(
- "-", " "
- ).strip()
- display_name = " ".join(
- word.capitalize()
- for word in display_name.split()
- )
+ finally:
+ # Restore original URL
+ GenericOpenAIEndpoint.default_base_url = original_url
- openai_endpoint_models.append(
- {
- "value": model_id,
- "label": f"{display_name} (Custom)",
- "provider": "OPENAI_ENDPOINT",
- }
- )
- except Exception as e:
- logger.exception(f"Fallback API request failed: {e!s}")
+ else:
+ logger.info(
+ "Custom OpenAI Endpoint URL or API key not configured"
+ )
except Exception as e:
- logger.exception(f"Error getting OpenAI Endpoint models: {e!s}")
- # Use fallback models (empty in this case)
- logger.info(
- "Using fallback (empty) OpenAI Endpoint models due to error"
+ logger.exception(
+ f"Error getting Custom OpenAI Endpoint models: {e!s}"
)
# Always set the openai_endpoint_models in providers
@@ -1295,7 +1243,6 @@ def api_get_available_models():
api_key = _get_setting_from_session("llm.openai.api_key", "")
if api_key:
- # Import OpenAI package here to avoid dependency issues if not installed
import openai
from openai import OpenAI
@@ -1329,8 +1276,7 @@ def api_get_available_models():
f"Added OpenAI model: {model_id} -> {display_name}"
)
- # Sort models alphabetically
- openai_models.sort(key=lambda x: x["label"])
+ # Keep original order from OpenAI
except openai.APIError as api_err:
logger.exception(f"OpenAI API error: {api_err!s}")
@@ -1341,8 +1287,6 @@ def api_get_available_models():
"OpenAI API key not configured, no models available"
)
- except ImportError:
- logger.warning("OpenAI package not installed. No models available.")
except Exception as e:
logger.exception(f"Error getting OpenAI models: {e!s}")
logger.info("No OpenAI models available due to error")
@@ -1395,8 +1339,7 @@ def api_get_available_models():
f"Added Anthropic model: {model_id} -> {display_name}"
)
- # Sort models alphabetically
- anthropic_models.sort(key=lambda x: x["label"])
+ # Keep original order from Anthropic
except Exception as api_err:
logger.exception(f"Anthropic API error: {api_err!s}")
@@ -1414,6 +1357,74 @@ def api_get_available_models():
providers["anthropic_models"] = anthropic_models
logger.info(f"Final Anthropic models count: {len(anthropic_models)}")
+ # Try to get Google Gemini models using the provider class
+ google_models = []
+ try:
+ logger.info("Fetching Google Gemini models")
+
+ from ...llm.providers.google import GoogleProvider
+
+ # Get API key if configured (Google doesn't require it for listing models)
+ api_key = _get_setting_from_session("llm.google.api_key", "")
+
+ # Use the provider's list_models_for_api method
+ models = GoogleProvider.list_models_for_api(api_key)
+
+ # Format models for the API response
+ for model in models:
+ google_models.append(
+ {
+ "value": model["value"],
+ "label": f"{model['label']} (Google)",
+ "provider": "GOOGLE",
+ }
+ )
+
+ logger.info(
+ f"Successfully fetched {len(google_models)} models from Google Gemini"
+ )
+
+ except Exception as e:
+ logger.exception(f"Error getting Google Gemini models: {e!s}")
+
+ # Set google_models in providers
+ providers["google_models"] = google_models
+ logger.info(f"Final Google models count: {len(google_models)}")
+
+ # Try to get OpenRouter models using the provider class
+ openrouter_models = []
+ try:
+ logger.info("Fetching OpenRouter models")
+
+ from ...llm.providers.openrouter import OpenRouterProvider
+
+ # Get API key if configured (OpenRouter doesn't require it for listing models)
+ api_key = _get_setting_from_session("llm.openrouter.api_key", "")
+
+ # Use the provider's list_models_for_api method
+ models = OpenRouterProvider.list_models_for_api(api_key)
+
+ # Format models for the API response
+ for model in models:
+ openrouter_models.append(
+ {
+ "value": model["value"],
+ "label": f"{model['label']} (OpenRouter)",
+ "provider": "OPENROUTER",
+ }
+ )
+
+ logger.info(
+ f"Successfully fetched {len(openrouter_models)} models from OpenRouter"
+ )
+
+ except Exception as e:
+ logger.exception(f"Error getting OpenRouter models: {e!s}")
+
+ # Set openrouter_models in providers
+ providers["openrouter_models"] = openrouter_models
+ logger.info(f"Final OpenRouter models count: {len(openrouter_models)}")
+
# Save fetched models to database cache
if force_refresh or providers:
# We fetched fresh data, save it to database
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 ebe62c69f1..9e367715c4 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -72,36 +72,11 @@
}
}
- // Model provider options from README
- const MODEL_PROVIDERS = [
- { value: 'OLLAMA', label: 'Ollama (Local)' },
- { value: 'OPENAI', label: 'OpenAI (Cloud)' },
- { value: 'ANTHROPIC', label: 'Anthropic (Cloud)' },
- { value: 'OPENAI_ENDPOINT', label: 'Custom OpenAI Endpoint' },
- { value: 'VLLM', label: 'vLLM (Local)' },
- { value: 'LMSTUDIO', label: 'LM Studio (Local)' },
- { value: 'LLAMACPP', label: 'Llama.cpp (Local)' }
- ];
-
- // Store available models by provider
- let availableModels = {
- OLLAMA: [],
- OPENAI: [
- { value: 'gpt-4o', label: 'GPT-4o' },
- { value: 'gpt-4', label: 'GPT-4' },
- { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' }
- ],
- ANTHROPIC: [
- { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet' },
- { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' },
- { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet' },
- { value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku' }
- ],
- VLLM: [],
- LMSTUDIO: [],
- LLAMACPP: [],
- OPENAI_ENDPOINT: []
- };
+ // Model provider options - will be populated dynamically from API
+ let MODEL_PROVIDERS = [];
+
+ // Store available models by provider - will be populated dynamically from API
+ let availableModels = {};
/**
* Initialize the research component
@@ -141,7 +116,8 @@
// Initialize the UI first (immediate operations)
setupEventListeners();
- populateModelProviders();
+ // Don't populate providers yet - wait for API data
+ // populateModelProviders();
initializeDropdowns();
// Also set initial values here for immediate feedback
@@ -730,6 +706,15 @@
function populateModelProviders() {
if (!modelProviderSelect) return;
+ // Don't populate if we don't have providers yet
+ if (MODEL_PROVIDERS.length === 0) {
+ console.log('No providers loaded yet, skipping populate');
+ return;
+ }
+
+ // Store current value before clearing
+ const currentValue = modelProviderSelect.value;
+
// Clear existing options
modelProviderSelect.innerHTML = '';
@@ -741,21 +726,27 @@
modelProviderSelect.appendChild(option);
});
- // Set initial value from data attribute or default to Ollama
+ // Restore previous value if it exists in new options, otherwise use initial value
const initialProvider = modelProviderSelect.getAttribute('data-initial-value') || 'OLLAMA';
- console.log('Initial provider from data attribute:', initialProvider);
- modelProviderSelect.value = initialProvider.toUpperCase();
+ if (currentValue && Array.from(modelProviderSelect.options).some(opt => opt.value === currentValue)) {
+ modelProviderSelect.value = currentValue;
+ } else {
+ console.log('Initial provider from data attribute:', initialProvider);
+ modelProviderSelect.value = initialProvider.toUpperCase();
+ }
// Show custom endpoint input if OpenAI endpoint is selected
if (endpointContainer) {
- console.log('Setting endpoint container display for provider:', initialProvider.toUpperCase());
- endpointContainer.style.display = initialProvider.toUpperCase() === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ const selectedProvider = modelProviderSelect.value || initialProvider.toUpperCase();
+ console.log('Setting endpoint container display for provider:', selectedProvider);
+ endpointContainer.style.display = selectedProvider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
} else {
console.warn('Endpoint container not found');
}
// Initial update of model options
- updateModelOptionsForProvider(initialProvider.toUpperCase());
+ const providerToUpdate = modelProviderSelect.value || initialProvider.toUpperCase();
+ updateModelOptionsForProvider(providerToUpdate);
}
/**
@@ -1582,6 +1573,14 @@
if (data && data.providers) {
console.log('Got model data from API:', data);
+ // Update MODEL_PROVIDERS from API if available
+ if (data.provider_options) {
+ MODEL_PROVIDERS = data.provider_options;
+ console.log('Updated MODEL_PROVIDERS from API:', MODEL_PROVIDERS);
+ // Re-populate the provider dropdown with new options
+ populateModelProviders();
+ }
+
// Format the data for our dropdown
const formattedModels = formatModelsFromAPI(data);
@@ -1637,48 +1636,37 @@
});
}
- // Process Ollama models
- if (data.providers && data.providers.ollama_models) {
- data.providers.ollama_models.forEach(model => {
- formatted.push({
- ...model,
- id: model.value,
- provider: 'OLLAMA'
- });
- });
- }
+ // Process all provider models dynamically
+ if (data.providers) {
+ // Clear and rebuild availableModels
+ availableModels = {};
- // Process OpenAI models
- if (data.providers && data.providers.openai_models) {
- data.providers.openai_models.forEach(model => {
- formatted.push({
- ...model,
- id: model.value,
- provider: 'OPENAI'
- });
- });
- }
+ // Iterate through all providers in the response
+ Object.keys(data.providers).forEach(providerKey => {
+ // Extract provider name from key (e.g., 'ollama_models' -> 'OLLAMA')
+ const providerName = providerKey.replace('_models', '').toUpperCase();
- // Process Anthropic models
- if (data.providers && data.providers.anthropic_models) {
- data.providers.anthropic_models.forEach(model => {
- formatted.push({
- ...model,
- id: model.value,
- provider: 'ANTHROPIC'
- });
- });
- }
+ // Initialize array for this provider
+ if (!availableModels[providerName]) {
+ availableModels[providerName] = [];
+ }
- // Process Custom OpenAI Endpoint models
- if (data.providers && data.providers.openai_endpoint_models) {
- data.providers.openai_endpoint_models.forEach(model => {
- formatted.push({
- ...model,
- id: model.value,
- provider: 'OPENAI_ENDPOINT'
- });
+ // Process each model for this provider
+ const models = data.providers[providerKey];
+ if (Array.isArray(models)) {
+ models.forEach(model => {
+ const formattedModel = {
+ ...model,
+ id: model.value,
+ provider: model.provider || providerName
+ };
+ formatted.push(formattedModel);
+ availableModels[providerName].push(formattedModel);
+ });
+ }
});
+
+ console.log('Dynamically populated availableModels:', availableModels);
}
return formatted;