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.

upd: enhance research UI by adding model provider selection and custom endpoint support. custom dropdowns.

hashedviking7b0c967a2991
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index f1dd07d5a4..b0d3a6468f 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -3,30 +3,23 @@ import logging
import os
import platform
import subprocess
-import traceback
from datetime import datetime
-from importlib import resources as importlib_resources
from flask import (
Blueprint,
jsonify,
- make_response,
redirect,
render_template,
request,
send_from_directory,
url_for,
)
-from flask_socketio import emit
from ..models.database import (
add_log_to_db,
calculate_duration,
- get_logs_for_research,
- init_db,
)
from ..services.research_service import (
- cleanup_research_resources,
run_research_process,
start_research_process,
)
@@ -146,8 +139,10 @@ def start_research():
query = data.get("query")
mode = data.get("mode", "quick")
- # Get search engine and model selections
+ # Get model provider and model selections
+ model_provider = data.get("model_provider", "OLLAMA")
model = data.get("model")
+ custom_endpoint = data.get("custom_endpoint")
search_engine = data.get("search_engine") or data.get("search_tool")
max_results = data.get("max_results")
time_period = data.get("time_period")
@@ -156,7 +151,7 @@ def start_research():
# Log the selections for troubleshooting
logger.info(
- f"Starting research with model: {model}, search engine: {search_engine}"
+ f"Starting research with provider: {model_provider}, model: {model}, search engine: {search_engine}"
)
logger.info(
f"Additional parameters: max_results={max_results}, time_period={time_period}, iterations={iterations}, questions={questions_per_iteration}"
@@ -165,6 +160,21 @@ def start_research():
if not query:
return jsonify({"status": "error", "message": "Query is required"}), 400
+ # Validate required parameters based on provider
+ if model_provider == "OPENAI_ENDPOINT" and not custom_endpoint:
+ return (
+ jsonify(
+ {
+ "status": "error",
+ "message": "Custom endpoint URL is required for OpenAI endpoint provider",
+ }
+ ),
+ 400,
+ )
+
+ if not model:
+ return jsonify({"status": "error", "message": "Model is required"}), 400
+
# Check if there's any active research that's actually still running
if active_research:
# Verify each active research is still valid
@@ -220,7 +230,9 @@ def start_research():
# Save research settings in the metadata field
research_settings = {
+ "model_provider": model_provider,
"model": model,
+ "custom_endpoint": custom_endpoint,
"search_engine": search_engine,
"max_results": max_results,
"time_period": time_period,
@@ -253,7 +265,9 @@ def start_research():
active_research,
termination_flags,
run_research_process,
+ model_provider=model_provider,
model=model,
+ custom_endpoint=custom_endpoint,
search_engine=search_engine,
max_results=max_results,
time_period=time_period,
@@ -261,6 +275,9 @@ def start_research():
questions_per_iteration=questions_per_iteration,
)
+ # Store the thread reference in active_research
+ active_research[research_id]["thread"] = research_thread
+
return jsonify({"status": "success", "research_id": research_id})
@@ -602,6 +619,7 @@ def get_history():
conn.close()
return jsonify({"status": "success", "items": history_items})
except Exception as e:
+ # Import traceback only when needed
import traceback
print(f"Error getting history: {e}")
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7d8c04e1ee..21ab0a852f 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -5,8 +5,6 @@ import threading
import traceback
from datetime import datetime
-from flask_socketio import emit
-
from ..models.database import add_log_to_db, calculate_duration, get_db_connection
# Initialize logger
@@ -78,7 +76,7 @@ def run_research_process(
mode: The research mode (quick/detailed)
active_research: Dictionary of active research processes
termination_flags: Dictionary of termination flags
- **kwargs: Additional parameters for the research (model, search_engine, etc.)
+ **kwargs: Additional parameters for the research (model_provider, model, search_engine, etc.)
"""
try:
# Check if this research has been terminated before we even start
@@ -90,7 +88,9 @@ def run_research_process(
logger.info(f"Starting research process for ID {research_id}, query: {query}")
# Extract key parameters
+ model_provider = kwargs.get("model_provider")
model = kwargs.get("model")
+ custom_endpoint = kwargs.get("custom_endpoint")
search_engine = kwargs.get("search_engine")
max_results = kwargs.get("max_results")
time_period = kwargs.get("time_period")
@@ -99,7 +99,9 @@ def run_research_process(
# Log all parameters for debugging
logger.info(
- f"Research parameters: model={model}, search_engine={search_engine}, max_results={max_results}, time_period={time_period}, iterations={iterations}, questions_per_iteration={questions_per_iteration}"
+ f"Research parameters: provider={model_provider}, model={model}, search_engine={search_engine}, "
+ f"max_results={max_results}, time_period={time_period}, iterations={iterations}, "
+ f"questions_per_iteration={questions_per_iteration}, custom_endpoint={custom_endpoint}"
)
# Set up the AI Context Manager
@@ -233,10 +235,10 @@ def run_research_process(
system.set_progress_callback(progress_callback)
# Configure the system with the specified parameters
- if model or search_engine:
+ if model or search_engine or model_provider:
# Log that we're overriding system settings
logger.info(
- f"Overriding system settings with: model={model}, search_engine={search_engine}"
+ f"Overriding system settings with: provider={model_provider}, model={model}, search_engine={search_engine}"
)
# Import configuration modules
@@ -244,18 +246,45 @@ def run_research_process(
from ...config.llm_config import get_llm
from ...config.search_config import get_search
- # Override LLM if specified
- if model:
+ # Override LLM if model or model_provider specified
+ if model or model_provider:
try:
- # Temporarily override the model setting
+ # Temporarily override settings
original_model = settings.llm.model
- settings.llm.model = model
+ original_provider = settings.llm.provider
+
+ # Set model if provided
+ if model:
+ settings.llm.model = model
+
+ # Set provider if provided
+ if model_provider:
+ settings.llm.provider = model_provider
+
+ # Set custom endpoint if provided for OpenAI endpoint provider
+ if model_provider == "OPENAI_ENDPOINT" and custom_endpoint:
+ original_endpoint = getattr(
+ settings.llm, "openai_endpoint_url", ""
+ )
+ settings.llm.openai_endpoint_url = custom_endpoint
+
+ # Get LLM with the overridden settings
system.model = get_llm()
- # Restore original setting
+
+ # Restore original settings
settings.llm.model = original_model
- logger.info(f"Successfully set LLM to: {model}")
+ settings.llm.provider = original_provider
+ if model_provider == "OPENAI_ENDPOINT" and custom_endpoint:
+ settings.llm.openai_endpoint_url = original_endpoint
+
+ logger.info(
+ f"Successfully set LLM to: provider={model_provider}, model={model}"
+ )
except Exception as e:
- logger.error(f"Error setting LLM model to {model}: {str(e)}")
+ logger.error(
+ f"Error setting LLM provider={model_provider}, model={model}: {str(e)}"
+ )
+ logger.error(traceback.format_exc())
# Override search engine if specified
if search_engine:
diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.css
index eddabd3afc..e2ed60e3c7 100644
--- a/src/local_deep_research/web/static/css/styles.css
+++ b/src/local_deep_research/web/static/css/styles.css
@@ -684,7 +684,7 @@ textarea:focus, input[type="text"]:focus {
color: var(--text-secondary);
}
-.results-content ul,
+.results-content ul,
.results-content ol {
margin-bottom: 1rem;
padding-left: 1.5rem;
@@ -990,7 +990,7 @@ textarea:focus, input[type="text"]:focus {
width: 60px;
overflow: hidden;
}
-
+
/* Hide all text in the logo and center icon */
.sidebar-header {
padding: 1rem 0;
@@ -1000,32 +1000,32 @@ textarea:focus, input[type="text"]:focus {
justify-content: center;
height: 60px;
}
-
+
.sidebar-header h2 {
font-size: 0;
display: flex;
justify-content: center;
width: 100%;
}
-
+
.sidebar-header h2 i {
font-size: 1.4rem;
display: flex;
align-items: center;
justify-content: center;
}
-
+
/* Hide all text in nav items and center icons */
.sidebar-nav {
display: flex;
flex-direction: column;
padding-top: 0.5rem;
}
-
+
.sidebar-nav ul {
width: 100%;
}
-
+
.sidebar-nav li {
text-indent: -9999px;
white-space: nowrap;
@@ -1036,7 +1036,7 @@ textarea:focus, input[type="text"]:focus {
align-items: center;
justify-content: center;
}
-
+
.sidebar-nav li i {
text-indent: 0;
margin: 0;
@@ -1045,23 +1045,23 @@ textarea:focus, input[type="text"]:focus {
align-items: center;
justify-content: center;
}
-
+
/* Active state fix for icon view */
.sidebar-nav li.active {
border-left-width: 3px;
}
-
+
/* Hide footer */
.sidebar-footer {
display: none;
}
-
+
/* Adjust main content */
.main-content {
margin-left: 60px;
width: calc(100% - 60px);
}
-
+
.mode-selection {
flex-direction: column;
}
@@ -1077,46 +1077,46 @@ textarea:focus, input[type="text"]:focus {
width: 100%;
padding-bottom: 70px; /* Account for mobile tab bar */
}
-
+
/* Adjust padding for mobile when log panel is visible */
.page#research-progress.active ~ .main-content,
.page#research-results.active ~ .main-content {
padding-bottom: calc(42vh + 60px); /* Log panel + mobile tab bar */
}
-
+
.sidebar {
width: 0;
transform: translateX(-100%);
}
-
+
.sidebar.active {
width: 240px;
transform: translateX(0);
}
-
+
/* Restore text in logo when sidebar is active on mobile */
.sidebar.active .sidebar-header h2 {
font-size: 1.25rem;
}
-
+
/* Restore text in nav items when sidebar is active on mobile */
.sidebar.active .sidebar-nav li {
text-indent: 0;
padding: 0.75rem 1.5rem;
text-align: left;
}
-
+
.sidebar.active .sidebar-nav li i {
display: inline;
width: 20px;
margin-right: 0.75rem;
font-size: 1rem;
}
-
+
.sidebar.active .sidebar-footer {
display: flex;
}
-
+
/* Show mobile tab bar */
.mobile-tab-bar {
display: flex !important; /* Use !important to ensure it displays */
@@ -1692,4 +1692,102 @@ input[type="number"].form-control::-webkit-inner-spin-button {
.notification-group .btn-sm:hover {
background-color: var(--accent-primary);
color: white;
-}
\ No newline at end of file
+}
+
+/* Custom Dropdown Component */
+.custom-dropdown {
+ position: relative;
+ width: 100%;
+ font-family: inherit;
+ margin-bottom: 0.25rem;
+}
+
+.custom-dropdown-input {
+ width: 100%;
+ padding: 8px 12px;
+ font-size: 0.95rem;
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ background-color: var(--bg-tertiary);
+ color: var(--text-primary);
+ cursor: pointer;
+}
+
+.custom-dropdown-input:focus {
+ outline: none;
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.2);
+}
+
+.custom-dropdown-list {
+ position: absolute;
+ width: 100%;
+ max-height: 220px;
+ overflow-y: auto;
+ border: 1px solid var(--border-color);
+ border-radius: 8px;
+ background-color: var(--bg-secondary);
+ display: none;
+ z-index: 1000;
+ margin-top: 4px;
+ box-shadow: var(--card-shadow);
+}
+
+.custom-dropdown-item {
+ padding: 8px 12px;
+ cursor: pointer;
+ color: var(--text-primary);
+ transition: background-color 0.15s ease;
+}
+
+.custom-dropdown-item:hover {
+ background-color: var(--bg-tertiary);
+}
+
+.custom-dropdown-item.active {
+ background-color: rgba(110, 79, 246, 0.2);
+}
+
+.custom-dropdown-item .highlight {
+ color: var(--accent-primary);
+ font-weight: 500;
+}
+
+.custom-dropdown-no-results {
+ padding: 8px 12px;
+ color: var(--text-muted);
+ font-style: italic;
+}
+
+.custom-dropdown-footer {
+ padding: 8px 12px;
+ border-top: 1px solid var(--border-color);
+ color: var(--accent-tertiary);
+ font-size: 0.9em;
+ background-color: rgba(110, 79, 246, 0.05);
+}
+
+.model-warning {
+ color: var(--warning-color);
+ font-size: 0.85rem;
+ margin-top: 5px;
+ display: none;
+}
+
+/* Form Layout Helpers */
+.form-row {
+ display: flex;
+ gap: 1rem;
+ margin-bottom: 1rem;
+}
+
+.form-group.half {
+ flex: 1;
+}
+
+.input-help {
+ display: block;
+ margin-top: 0.25rem;
+ font-size: 0.8rem;
+ color: var(--text-muted);
+}
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 4950294560..267a1a6037 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -9,15 +9,59 @@
let modeOptions = null;
let notificationToggle = null;
let startBtn = null;
- let modelSelect = null;
- let searchEngineSelect = null;
- let maxResultsInput = null;
- let timePeriodSelect = null;
+ let modelProviderSelect = null;
+ let customEndpointInput = null;
+ let endpointContainer = null;
+ let modelInput = null;
+ let modelDropdown = null;
+ let modelDropdownList = null;
+ let searchEngineInput = null;
+ let searchEngineDropdown = null;
+ let searchEngineDropdownList = null;
let iterationsInput = null;
let questionsPerIterationInput = null;
let advancedToggle = null;
let advancedPanel = null;
+ // State variables for dropdowns
+ let modelOptions = [];
+ let selectedModelValue = '';
+ let modelSelectedIndex = -1;
+ let searchEngineOptions = [];
+ let selectedSearchEngineValue = '';
+ let searchEngineSelectedIndex = -1;
+
+ // 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: []
+ };
+
/**
* Initialize the research component
*/
@@ -28,10 +72,19 @@
modeOptions = document.querySelectorAll('.mode-option');
notificationToggle = document.getElementById('notification-toggle');
startBtn = document.getElementById('start-research-btn');
- modelSelect = document.getElementById('model');
- searchEngineSelect = document.getElementById('search_engine');
- maxResultsInput = document.getElementById('max_results');
- timePeriodSelect = document.getElementById('time_period');
+ modelProviderSelect = document.getElementById('model_provider');
+ customEndpointInput = document.getElementById('custom_endpoint');
+ endpointContainer = document.getElementById('endpoint_container');
+
+ // Custom dropdown elements
+ modelInput = document.getElementById('model');
+ modelDropdown = document.getElementById('model-dropdown');
+ modelDropdownList = document.getElementById('model-dropdown-list');
+
+ searchEngineInput = document.getElementById('search_engine');
+ searchEngineDropdown = document.getElementById('search-engine-dropdown');
+ searchEngineDropdownList = document.getElementById('search-engine-dropdown-list');
+
iterationsInput = document.getElementById('iterations');
questionsPerIterationInput = document.getElementById('questions_per_iteration');
advancedToggle = document.querySelector('.advanced-options-toggle');
@@ -45,6 +98,9 @@
// Set up event listeners
setupEventListeners();
+ // Populate providers dropdown
+ populateModelProviders();
+
// Load data
loadModelOptions();
loadSearchEngineOptions();
@@ -91,6 +147,324 @@
}
});
}
+
+ // Handle model provider change
+ if (modelProviderSelect) {
+ modelProviderSelect.addEventListener('change', function() {
+ const provider = this.value;
+
+ // Show/hide custom endpoint input
+ if (endpointContainer) {
+ endpointContainer.style.display = provider === 'OPENAI_ENDPOINT' ? 'block' : 'none';
+ }
+
+ // Update model options based on provider and reset the selected model
+ updateModelOptionsForProvider(provider, true);
+ });
+ }
+
+ // Setup custom dropdown for model
+ setupCustomDropdown(
+ modelInput,
+ modelDropdownList,
+ () => modelOptions,
+ (value, item) => {
+ selectedModelValue = item ? item.value : value;
+ modelInput.value = item ? item.label : value;
+ showCustomModelWarning(!item && value);
+ },
+ true, // allowCustomValues
+ 'No models available. Type to enter a custom model name.'
+ );
+
+ // Setup custom dropdown for search engine
+ setupCustomDropdown(
+ searchEngineInput,
+ searchEngineDropdownList,
+ () => searchEngineOptions,
+ (value, item) => {
+ selectedSearchEngineValue = item ? item.value : null;
+ searchEngineInput.value = item ? item.label : value;
+ },
+ false, // allowCustomValues
+ 'No search engines available.'
+ );
+ }
+
+ /**
+ * Setup a custom dropdown component
+ * @param {HTMLElement} input - The input element
+ * @param {HTMLElement} dropdownList - The dropdown list element
+ * @param {Function} getOptions - Function that returns the current options array
+ * @param {Function} onSelect - Callback when an item is selected
+ * @param {boolean} allowCustomValues - Whether to allow values not in the options list
+ * @param {string} noResultsText - Text to show when no results are found
+ */
+ function setupCustomDropdown(input, dropdownList, getOptions, onSelect, allowCustomValues = false, noResultsText = 'No results found.') {
+ let selectedIndex = -1;
+ let isOpen = false;
+ let showAllOptions = false; // Flag to track if we should show all options
+
+ // Function to filter options
+ function filterOptions(searchText, showAll = false) {
+ const options = getOptions();
+ if (showAll || !searchText.trim()) return options;
+
+ return options.filter(item =>
+ item.label.toLowerCase().includes(searchText.toLowerCase()) ||
+ item.value.toLowerCase().includes(searchText.toLowerCase())
+ );
+ }
+
+ // Function to highlight matched text
+ function highlightText(text, search) {
+ if (!search.trim() || showAllOptions) return text;
+ const regex = new RegExp(`(${search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
+ return text.replace(regex, '<span class="highlight">$1</span>');
+ }
+
+ // Function to show the dropdown
+ function showDropdown() {
+ dropdownList.style.display = 'block';
+ input.setAttribute('aria-expanded', 'true');
+ isOpen = true;
+ }
+
+ // Function to hide the dropdown
+ function hideDropdown() {
+ dropdownList.style.display = 'none';
+ input.setAttribute('aria-expanded', 'false');
+ selectedIndex = -1;
+ isOpen = false;
+ showAllOptions = false; // Reset the flag when closing dropdown
+ }
+
+ // Function to update the dropdown
+ function updateDropdown() {
+ const searchText = input.value;
+ const filteredData = filterOptions(searchText, showAllOptions);
+
+ dropdownList.innerHTML = '';
+
+ if (filteredData.length === 0) {
+ dropdownList.innerHTML = `<div class="custom-dropdown-no-results">${noResultsText}</div>`;
+
+ if (allowCustomValues && searchText.trim()) {
+ const customOption = document.createElement('div');
+ customOption.className = 'custom-dropdown-footer';
+ customOption.textContent = `Press Enter to use "${searchText}"`;
+ dropdownList.appendChild(customOption);
+ }
+
+ return;
+ }
+
+ filteredData.forEach((item, index) => {
+ const div = document.createElement('div');
+ div.className = 'custom-dropdown-item';
+ div.innerHTML = highlightText(item.label, searchText);
+ div.setAttribute('data-value', item.value);
+ div.addEventListener('click', () => {
+ onSelect(item.value, item);
+ hideDropdown();
+ });
+
+ if (index === selectedIndex) {
+ div.classList.add('active');
+ }
+
+ dropdownList.appendChild(div);
+ });
+ }
+
+ // Input event - filter as user types
+ input.addEventListener('input', () => {
+ showAllOptions = false; // Reset when typing
+ showDropdown();
+ updateDropdown();
+ selectedIndex = -1;
+ });
+
+ // Click event - show all options when clicking in the input
+ input.addEventListener('click', (e) => {
+ if (!isOpen) {
+ showAllOptions = true; // Show all options on click
+ showDropdown();
+ updateDropdown();
+ }
+ e.stopPropagation(); // Prevent immediate closing by document click handler
+ });
+
+ // Focus event - show dropdown when input is focused
+ input.addEventListener('focus', () => {
+ if (!isOpen) {
+ showAllOptions = true; // Show all options on focus
+ showDropdown();
+ updateDropdown();
+ }
+ });
+
+ // Keyboard navigation
+ input.addEventListener('keydown', (e) => {
+ const items = dropdownList.querySelectorAll('.custom-dropdown-item');
+
+ // If dropdown is not open, only open on arrow down
+ if (!isOpen && e.key === 'ArrowDown') {
+ showAllOptions = true; // Show all options when opening with arrow down
+ showDropdown();
+ updateDropdown();
+ return;
+ }
+
+ if (!isOpen) return;
+
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+
+ // Show all options when using arrow keys
+ if (!showAllOptions) {
+ showAllOptions = true;
+ updateDropdown(); // Update to show all options
+ }
+
+ if (e.key === 'ArrowDown') {
+ selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
+ if (selectedIndex === -1 && items.length > 0) {
+ selectedIndex = 0;
+ }
+ } else {
+ selectedIndex = Math.max(selectedIndex - 1, -1);
+ }
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+
+ if (selectedIndex >= 0 && selectedIndex < items.length) {
+ // Select the highlighted item
+ const selectedItem = items[selectedIndex];
+ const value = selectedItem.getAttribute('data-value');
+ const item = getOptions().find(o => o.value === value);
+ onSelect(value, item);
+ } else if (allowCustomValues && input.value.trim()) {
+ // Use the custom value
+ onSelect(input.value.trim(), null);
+ }
+
+ hideDropdown();
+ return;
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ hideDropdown();
+ return;
+ } else {
+ // Any other key should reset the showAllOptions flag to let filtering work
+ showAllOptions = false;
+ return;
+ }
+
+ // Update active item styling
+ items.forEach((item, idx) => {
+ if (idx === selectedIndex) {
+ item.classList.add('active');
+ item.scrollIntoView({ block: 'nearest' });
+ } else {
+ item.classList.remove('active');
+ }
+ });
+ });
+
+ // Click outside to close
+ document.addEventListener('click', (e) => {
+ const isClickInsideDropdown = input.contains(e.target) || dropdownList.contains(e.target);
+ if (!isClickInsideDropdown && isOpen) {
+ hideDropdown();
+ }
+ });
+ }
+
+ /**
+ * Show or hide warning about custom model entries
+ * @param {boolean} show - Whether to show the warning
+ */
+ function showCustomModelWarning(show) {
+ let warningEl = document.getElementById('custom-model-warning');
+
+ if (!warningEl && show) {
+ warningEl = document.createElement('div');
+ warningEl.id = 'custom-model-warning';
+ warningEl.className = 'model-warning';
+ warningEl.textContent = 'Custom model name entered. Make sure it exists in your provider.';
+ const parent = modelDropdown.closest('.form-group');
+ if (parent) {
+ parent.appendChild(warningEl);
+ }
+ }
+
+ if (warningEl) {
+ warningEl.style.display = show ? 'block' : 'none';
+ }
+ }
+
+ /**
+ * Populate model provider dropdown
+ */
+ function populateModelProviders() {
+ if (!modelProviderSelect) return;
+
+ // Clear existing options
+ modelProviderSelect.innerHTML = '';
+
+ // Add options
+ MODEL_PROVIDERS.forEach(provider => {
+ const option = document.createElement('option');
+ option.value = provider.value;
+ option.textContent = provider.label;
+ modelProviderSelect.appendChild(option);
+ });
+
+ // Default to Ollama - ensure it's explicitly set to OLLAMA
+ modelProviderSelect.value = 'OLLAMA';
+
+ // Initial update of model options
+ updateModelOptionsForProvider('OLLAMA');
+ }
+
+ /**
+ * Update model options based on selected provider
+ * @param {string} provider - The selected provider
+ * @param {boolean} resetSelectedModel - Whether to reset the selected model
+ */
+ function updateModelOptionsForProvider(provider, resetSelectedModel = false) {
+ // Get models for this provider
+ const models = availableModels[provider] || [];
+
+ // Update model options
+ modelOptions = models;
+
+ // Reset model input if requested or if empty
+ if (resetSelectedModel || !modelInput.value.trim()) {
+ if (models.length > 0) {
+ // Select the first model from the new provider
+ modelInput.value = models[0].label;
+ selectedModelValue = models[0].value;
+ } else {
+ // No models available for this provider
+ modelInput.value = '';
+ selectedModelValue = '';
+ }
+ }
+
+ // Set placeholder text based on available models
+ if (models.length === 0) {
+ modelInput.placeholder = 'Enter custom model name';
+ } else {
+ modelInput.placeholder = 'Enter or select a model';
+ }
+
+ // Update dropdown list if visible
+ if (modelDropdownList.style.display === 'block') {
+ const event = new Event('input');
+ modelInput.dispatchEvent(event);
+ }
}
/**
@@ -168,10 +542,19 @@
const query = queryInput.value.trim();
const activeMode = document.querySelector('.mode-option.active');
const mode = activeMode ? activeMode.dataset.mode : 'quick';
- const model = modelSelect ? modelSelect.value : '';
- const searchEngine = searchEngineSelect ? searchEngineSelect.value : '';
- const maxResults = maxResultsInput ? maxResultsInput.value : '10';
- const timePeriod = timePeriodSelect ? timePeriodSelect.value : 'all';
+
+ // Get advanced options
+ const modelProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
+ const customEndpoint = customEndpointInput && modelProvider === 'OPENAI_ENDPOINT'
+ ? customEndpointInput.value.trim()
+ : '';
+
+ // Get model value - could be a selected value or custom text
+ let model = selectedModelValue || modelInput.value.trim();
+
+ // Force search engine to be auto
+ let searchEngine = 'auto';
+
const iterations = iterationsInput ? iterationsInput.value : '2';
const questionsPerIteration = questionsPerIterationInput ? questionsPerIterationInput.value : '3';
const enableNotifications = notificationToggle ? notificationToggle.checked : true;
@@ -182,30 +565,48 @@
return;
}
+ // Validate model provider specific requirements
+ if (modelProvider === 'OPENAI_ENDPOINT' && !customEndpoint) {
+ showFormError('Please enter a custom endpoint URL');
+ return;
+ }
+
+ if (!model) {
+ showFormError('Please select or enter a model name');
+ return;
+ }
+
+ if (!searchEngine) {
+ showFormError('Please select a search engine');
+ return;
+ }
+
// Debug selected values
- console.log(`Starting research with model: ${model}, search engine: ${searchEngine}`);
+ console.log(`Starting research with provider: ${modelProvider}, model: ${model}, search engine: ${searchEngine}`);
// Disable form
setFormSubmitting(true);
try {
- // First check if Ollama is running and model is available
- const ollamaCheck = await checkOllamaModel();
- if (!ollamaCheck.success) {
- showFormError(`${ollamaCheck.error} ${ollamaCheck.solution}`);
- setFormSubmitting(false);
- return;
+ // Check if Ollama is running if using Ollama provider
+ if (modelProvider === 'OLLAMA') {
+ const ollamaCheck = await checkOllamaModel();
+ if (!ollamaCheck.success) {
+ showFormError(`${ollamaCheck.error} ${ollamaCheck.solution}`);
+ setFormSubmitting(false);
+ return;
+ }
}
- // Prepare request payload - ensure consistent property names with backend
+ // Prepare request payload
const payload = {
query,
mode,
+ model_provider: modelProvider,
model,
- search_engine: searchEngine, // Make sure these match what backend expects
- search_tool: searchEngine, // Include both for backward compatibility
- max_results: maxResults,
- time_period: timePeriod,
+ custom_endpoint: customEndpoint,
+ search_engine: searchEngine,
+ search_tool: searchEngine, // Include both for backward compatibility
iterations,
questions_per_iteration: questionsPerIteration
};
@@ -230,6 +631,7 @@
if (data && data.status === 'success' && data.research_id) {
// Store research settings
window.localStorage.setItem('notificationsEnabled', enableNotifications);
+ window.localStorage.setItem('lastUsedModelProvider', modelProvider);
window.localStorage.setItem('lastUsedModel', model);
window.localStorage.setItem('lastUsedSearchEngine', searchEngine);
@@ -322,13 +724,11 @@
* Load language model options from API
*/
function loadModelOptions() {
- if (!modelSelect) return;
-
- // Set "Loading..." option temporarily
- modelSelect.innerHTML = '<option value="">Loading models...</option>';
+ // Show loading state
+ modelInput.placeholder = 'Loading models...';
+ modelInput.disabled = true;
- // Only populate the dropdown once with all options combined
- // Fetch all data sources in parallel first
+ // Fetch all data sources in parallel
Promise.all([
// Get available models from API
fetch('/research/api/available-models')
@@ -340,77 +740,79 @@
.catch(() => ({ settings: {} })) // Fallback if API fails
])
.then(([modelsData, settingsData]) => {
- let modelOptions = [];
- let selectedValue = null;
-
- // 1. Add Ollama models if available
+ // Process Ollama models
if (modelsData.providers && modelsData.providers.ollama_models && modelsData.providers.ollama_models.length > 0) {
console.log('Found Ollama models:', modelsData.providers.ollama_models);
- // Add all Ollama models from the API
- modelOptions = [...modelOptions, ...modelsData.providers.ollama_models];
+ availableModels.OLLAMA = modelsData.providers.ollama_models;
} else if (modelsData.ollama_models && modelsData.ollama_models.length > 0) {
// Backward compatibility
console.log('Found Ollama models (legacy format):', modelsData.ollama_models);
- modelOptions = [...modelOptions, ...modelsData.ollama_models];
+ availableModels.OLLAMA = modelsData.ollama_models;
} else {
- // If we don't have Ollama models from API, add common Ollama models as fallback
- modelOptions = [
- ...modelOptions,
- { value: 'gemma3:12b', label: 'Gemma 3 12B (Ollama)' },
- { value: 'mistral', label: 'Mistral (Ollama)' },
- { value: 'deepseek-r1', label: 'DeepSeek R1 (Ollama)' },
- { value: 'deepseek-r1:14b', label: 'DeepSeek R1 14B (Ollama)' },
- { value: 'deepseek-r1:32b', label: 'DeepSeek R1 32B (Ollama)' }
+ // Fallback Ollama models
+ availableModels.OLLAMA = [
+ { value: 'gemma3:12b', label: 'Gemma 3 12B' },
+ { value: 'mistral', label: 'Mistral' },
+ { value: 'deepseek-r1', label: 'DeepSeek R1' }
];
}
- // 2. Add standard model options (these always appear, even without Ollama)
- modelOptions = [
- ...modelOptions,
- { value: 'gpt-4o', label: 'GPT-4o (OpenAI)' },
- { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo (OpenAI)' },
- { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet (Anthropic)' },
- { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus (Anthropic)' }
- ];
-
- // 3. Get the currently selected model value from settings if available
- const currentModelSetting = settingsData?.settings?.['llm.model'];
- if (currentModelSetting) {
- selectedValue = currentModelSetting;
+ // Check for current provider setting
+ const currentProvider = settingsData?.settings?.['llm.provider'] || 'OLLAMA';
+
+ // Ensure provider is set to a valid value - default to OLLAMA if empty or invalid
+ if (modelProviderSelect) {
+ // Only update if it's a valid provider, otherwise use OLLAMA as default
+ if (currentProvider && MODEL_PROVIDERS.some(p => p.value === currentProvider)) {
+ modelProviderSelect.value = currentProvider;
+ } else {
+ modelProviderSelect.value = 'OLLAMA';
+ }
+ }
+
+ // Check for endpoint setting
+ const currentEndpoint = settingsData?.settings?.['llm.openai_endpoint'];
+ if (currentEndpoint && customEndpointInput) {
+ customEndpointInput.value = currentEndpoint;
+ }
+
+ // Show/hide endpoint input based on provider
+ if (endpointContainer) {
+ endpointContainer.style.display = modelProviderSelect.value === 'OPENAI_ENDPOINT' ? 'block' : 'none';
}
- // 4. Get the model specified in the legacy config file.
- const configModels = modelsData?.providers?.config_models ?? [];
- modelOptions = [...modelOptions, ...configModels.map(m => ({ value: m, label: m }))];
+ // Check for current model setting
+ const currentModel = settingsData?.settings?.['llm.model'];
- // Make sure we don't have duplicates (by value)
- const uniqueOptions = [];
- const uniqueValues = new Set();
+ // Update model options for the current provider
+ updateModelOptionsForProvider(modelProviderSelect.value);
- modelOptions.forEach(option => {
- if (!uniqueValues.has(option.value)) {
- uniqueValues.add(option.value);
- uniqueOptions.push(option);
+ // Set default model if available
+ if (currentModel) {
+ // Try to find the model in the current provider's options
+ const modelOption = modelOptions.find(m => m.value === currentModel);
+ if (modelOption) {
+ modelInput.value = modelOption.label;
+ selectedModelValue = modelOption.value;
+ } else {
+ // If not found, set it as a custom value
+ modelInput.value = currentModel;
+ selectedModelValue = currentModel;
}
- });
+ } else if (modelOptions.length > 0) {
+ // Default to first model in the list
+ modelInput.value = modelOptions[0].label;
+ selectedModelValue = modelOptions[0].value;
+ }
- // Finally populate the dropdown once with all options
- populateSelectWithOptions(modelSelect, uniqueOptions, selectedValue || 'mistral');
+ // Re-enable the input
+ modelInput.disabled = false;
})
.catch(error => {
console.error('Error loading LLM models:', error);
-
- // Fallback to default options if all API calls fail
- const defaultOptions = [
- { value: 'gemma3:12b', label: 'Gemma 3 12B (Ollama)' },
- { value: 'mistral', label: 'Mistral (Ollama)' },
- { value: 'deepseek-r1', label: 'DeepSeek R1 (Ollama)' },
- { value: 'gpt-4o', label: 'GPT-4o (OpenAI)' },
- { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo (OpenAI)' },
- { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet (Anthropic)' }
- ];
-
- populateSelectWithOptions(modelSelect, defaultOptions, 'mistral');
+ // Use fallback options
+ updateModelOptionsForProvider('OLLAMA');
+ modelInput.disabled = false;
});
}
@@ -418,7 +820,16 @@
* Load search engine options from API
*/
function loadSearchEngineOptions() {
- if (!searchEngineSelect) return;
+ // FORCE set default to Auto immediately
+ searchEngineInput.value = 'Auto (Default)';
+ selectedSearchEngineValue = 'auto';
+
+ // Store this in localStorage to avoid any issues
+ window.localStorage.setItem('defaultSearchEngine', 'auto');
+
+ // Show loading state
+ searchEngineInput.placeholder = 'Loading search engines...';
+ searchEngineInput.disabled = true;
// Set default options in case API call fails
const defaultOptions = [
@@ -430,7 +841,10 @@
];
// Start with default options
- populateSelectWithOptions(searchEngineSelect, defaultOptions, 'auto');
+ searchEngineOptions = defaultOptions;
+
+ // Re-enable the input
+ searchEngineInput.disabled = false;
// Try to get search engine options from API
fetch('/research/api/available-search-engines')
@@ -440,43 +854,39 @@
})
.then(data => {
if (data.engine_options && data.engine_options.length > 0) {
- // Ensure 'auto' is the first option if it exists
- const autoOption = data.engine_options.find(opt => opt.value === 'auto');
- if (autoOption) {
- // Remove auto from its current position
- data.engine_options = data.engine_options.filter(opt => opt.value !== 'auto');
- // Add it back as the first option
- data.engine_options.unshift(autoOption);
- } else {
- // If 'auto' doesn't exist in the options, add it
- data.engine_options.unshift({ value: 'auto', label: 'Auto (Default)' });
- }
+ // Build options list with Auto first
+ let engineOptions = [];
- // Always use 'auto' as the default value
- populateSelectWithOptions(searchEngineSelect, data.engine_options, 'auto');
- }
+ // Always add Auto as the first option
+ engineOptions.push({ value: 'auto', label: 'Auto (Default)' });
- // Also get the current setting value
- return fetch('/research/api/?type=search');
- })
- .then(response => {
- if (!response.ok) throw new Error(`API returned ${response.status}`);
- return response.json();
- })
- .then(data => {
- // Simply log the server's default value but don't apply it
- // This ensures we always keep 'auto' as the default
- const searchEngineSetting = data?.settings?.['search.tool'];
- console.log('Server default search engine:', searchEngineSetting);
-
- // Override default with 'auto' regardless of server setting
- const autoOption = Array.from(searchEngineSelect.options).find(opt => opt.value === 'auto');
- if (autoOption) {
- autoOption.selected = true;
+ // Add all other options (except auto since we already added it)
+ data.engine_options.forEach(option => {
+ if (option.value !== 'auto') {
+ engineOptions.push(option);
+ }
+ });
+
+ // Update the search engine options
+ searchEngineOptions = engineOptions;
}
+
+ // FORCE set to Auto one more time to avoid issues
+ searchEngineInput.value = 'Auto (Default)';
+ selectedSearchEngineValue = 'auto';
+
+ // Skip loading settings as we always want Auto
+ return Promise.resolve({
+ settings: {
+ 'search.tool': 'auto'
+ }
+ });
})
.catch(error => {
console.error('Error loading search settings:', error);
+ // Default to Auto on error
+ searchEngineInput.value = 'Auto (Default)';
+ selectedSearchEngineValue = 'auto';
});
}
@@ -485,40 +895,10 @@
*/
function loadSettings() {
// Set default values
- if (maxResultsInput) maxResultsInput.value = 10;
- if (timePeriodSelect) {
- const allTimeOption = timePeriodSelect.querySelector('option[value="all"]');
- if (allTimeOption) allTimeOption.selected = true;
- }
if (iterationsInput) iterationsInput.value = 2;
if (questionsPerIterationInput) questionsPerIterationInput.value = 3;
if (notificationToggle) notificationToggle.checked = true;
- // Try to load search settings
- fetch('/research/api/?type=search')
- .then(response => {
- if (!response.ok) throw new Error(`API returned ${response.status}`);
- return response.json();
- })
- .then(data => {
- if (data?.settings) {
- if (maxResultsInput && data.settings['search.max_results'] !== undefined) {
- maxResultsInput.value = data.settings['search.max_results'];
- }
-
- if (timePeriodSelect && data.settings['search.time_period']) {
- const timePeriod = data.settings['search.time_period'];
- const option = timePeriodSelect.querySelector(`option[value="${timePeriod}"]`);
- if (option) {
- option.selected = true;
- }
- }
- }
- })
- .catch(error => {
- console.error('Error loading search settings:', error);
- });
-
// Try to load app settings
fetch('/research/api/?type=app')
.then(response => {
@@ -545,31 +925,6 @@
});
}
- /**
- * Populate a select element with options
- * @param {HTMLSelectElement} selectElement - The select element to populate
- * @param {Array} options - Array of option objects with value and label properties
- * @param {string} defaultValue - The default value to select
- */
- function populateSelectWithOptions(selectElement, options, defaultValue) {
- // Clear existing options
- selectElement.innerHTML = '';
-
- // Add options
- options.forEach(option => {
- const optionEl = document.createElement('option');
- optionEl.value = option.value;
- optionEl.textContent = option.label;
-
- // Select default or matching value
- if (option.value === defaultValue) {
- optionEl.selected = true;
- }
-
- selectElement.appendChild(optionEl);
- });
- }
-
// Initialize on DOM content loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeResearch);
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 5eea4f3e94..af2d1f1314 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -35,58 +35,67 @@
</div>
</div>
</div>
-
+
<!-- Advanced Options -->
<div class="advanced-options-toggle">
<span class="toggle-text">Advanced Options</span>
<i class="fas fa-chevron-down"></i>
</div>
-
+
<div class="advanced-options-panel">
<div class="form-row">
- <!-- Model Selection -->
+ <!-- Model Provider Selection -->
<div class="form-group half">
- <label for="model">Language Model</label>
- <select id="model" name="model" class="form-control">
+ <label for="model_provider">Model Provider</label>
+ <select id="model_provider" name="model_provider" class="form-control">
<!-- Will be populated dynamically -->
- <option value="">Loading models...</option>
+ <option value="">Loading providers...</option>
</select>
- <span class="input-help">Select the language model to use for analysis</span>
+ <span class="input-help">Select the LLM provider to use</span>
</div>
-
- <!-- Search Engine Selection -->
- <div class="form-group half">
- <label for="search_engine">Search Engine</label>
- <select id="search_engine" name="search_engine" class="form-control">
- <!-- Will be populated dynamically -->
- <option value="">Loading search engines...</option>
- </select>
- <span class="input-help">Select the search engine to use for research</span>
+
+ <!-- Custom Endpoint (hidden by default) -->
+ <div class="form-group half" id="endpoint_container" style="display: none;">
+ <label for="custom_endpoint">Custom Endpoint</label>
+ <input type="text" id="custom_endpoint" name="custom_endpoint" class="form-control" placeholder="https://your-endpoint-url/v1">
+ <span class="input-help">Enter the OpenAI-compatible API endpoint URL</span>
</div>
</div>
-
+
<div class="form-row">
- <!-- Search Results Setting -->
+ <!-- Model Selection -->
<div class="form-group half">
- <label for="max_results">Max Search Results</label>
- <input type="number" id="max_results" name="max_results" class="form-control" min="3" max="50" value="10">
- <span class="input-help">Maximum number of search results to retrieve</span>
+ <label for="model">Language Model</label>
+ <div class="custom-dropdown" id="model-dropdown">
+ <input type="text"
+ id="model"
+ name="model"
+ class="custom-dropdown-input"
+ placeholder="Enter or select a model"
+ autocomplete="off"
+ aria-haspopup="listbox">
+ <div class="custom-dropdown-list" id="model-dropdown-list"></div>
+ </div>
+ <span class="input-help">Select or enter a custom model name</span>
</div>
-
- <!-- Search Time Period -->
+
+ <!-- Search Engine Selection -->
<div class="form-group half">
- <label for="time_period">Time Period</label>
- <select id="time_period" name="time_period" class="form-control">
- <option value="all">All time</option>
- <option value="d">Past 24 hours</option>
- <option value="w">Past week</option>
- <option value="m">Past month</option>
- <option value="y">Past year</option>
- </select>
- <span class="input-help">Limit search results to a specific time period</span>
+ <label for="search_engine">Search Engine</label>
+ <div class="custom-dropdown" id="search-engine-dropdown">
+ <input type="text"
+ id="search_engine"
+ name="search_engine"
+ class="custom-dropdown-input"
+ placeholder="Select a search engine"
+ autocomplete="off"
+ aria-haspopup="listbox">
+ <div class="custom-dropdown-list" id="search-engine-dropdown-list"></div>
+ </div>
+ <span class="input-help">Select the search engine to use for research</span>
</div>
</div>
-
+
<div class="form-row">
<!-- Research Iterations -->
<div class="form-group half">
@@ -94,7 +103,7 @@
<input type="number" id="iterations" name="iterations" class="form-control" min="1" max="5" value="2">
<span class="input-help">Number of research cycles to perform</span>
</div>
-
+
<!-- Questions Per Iteration -->
<div class="form-group half">
<label for="questions_per_iteration">Questions Per Iteration</label>
@@ -103,7 +112,7 @@
</div>
</div>
</div>
-
+
<div class="form-options">
<div class="form-option">
<label for="notification-toggle" class="checkbox-label">
@@ -112,7 +121,7 @@
</label>
</div>
</div>
-
+
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="start-research-btn"><i class="fas fa-rocket"></i> Start Research</button>
</div>
@@ -124,4 +133,4 @@
{% block component_scripts %}
<script src="{{ url_for('research.serve_static', path='js/components/research.js') }}"></script>
-{% endblock %}
\ No newline at end of file
+{% endblock %}