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.

Force the model selector to show the model specified in the config file.

Daniel Petti79bcef2a3e04
diff --git a/src/local_deep_research/web/routes/settings_api.py b/src/local_deep_research/web/routes/settings_api.py
index ed3600d891..933124aad7 100644
--- a/src/local_deep_research/web/routes/settings_api.py
+++ b/src/local_deep_research/web/routes/settings_api.py
@@ -1,12 +1,23 @@
import logging
-from typing import Dict, List, Optional, Any, Union
+from pathlib import Path
-from flask import Blueprint, jsonify, request, current_app
+import requests
+import toml
+from flask import Blueprint, current_app, jsonify, request
from sqlalchemy.orm import Session
+from ...config.config_files import get_config_dir
+from ...config.llm_config import (
+ VALID_PROVIDERS,
+ get_available_providers,
+ is_ollama_available,
+ settings,
+)
+from ...web_search_engines.search_engine_factory import (
+ get_available_engines,
+)
from ..database.models import Setting, SettingType
from ..services.settings_manager import SettingsManager
-from ..models.settings import BaseSetting, SettingsGroup
# Initialize logger
logger = logging.getLogger(__name__)
@@ -14,25 +25,27 @@ logger = logging.getLogger(__name__)
# Create a Blueprint for settings API
settings_api_bp = Blueprint("settings_api", __name__, url_prefix="/")
+
def get_db_session() -> Session:
"""Get the database session from the app context"""
- if hasattr(current_app, 'db_session'):
+ if hasattr(current_app, "db_session"):
return current_app.db_session
else:
- return current_app.extensions['sqlalchemy'].session()
+ return current_app.extensions["sqlalchemy"].session()
+
@settings_api_bp.route("/", methods=["GET"])
def get_all_settings():
"""Get all settings"""
try:
# Get query parameters
- setting_type = request.args.get('type')
- category = request.args.get('category')
-
+ setting_type = request.args.get("type")
+ category = request.args.get("category")
+
# Create settings manager
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Get settings
if setting_type:
try:
@@ -42,41 +55,42 @@ def get_all_settings():
return jsonify({"error": f"Invalid setting type: {setting_type}"}), 400
else:
settings = settings_manager.get_all_settings()
-
+
# Filter by category if requested
if category:
filtered_settings = {}
# Need to get all setting details to check category
db_settings = db_session.query(Setting).all()
category_keys = [s.key for s in db_settings if s.category == category]
-
+
# Filter settings by keys
for key, value in settings.items():
if key in category_keys:
filtered_settings[key] = value
-
+
settings = filtered_settings
-
+
return jsonify({"settings": settings})
except Exception as e:
logger.error(f"Error getting settings: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/<path:key>", methods=["GET"])
def get_setting(key):
"""Get a specific setting by key"""
try:
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Get setting
value = settings_manager.get_setting(key)
if value is None:
return jsonify({"error": f"Setting not found: {key}"}), 404
-
+
# Get additional metadata from database
db_setting = db_session.query(Setting).filter(Setting.key == key).first()
-
+
if db_setting:
# Return full setting details
setting_data = {
@@ -92,20 +106,18 @@ def get_setting(key):
"max_value": db_setting.max_value,
"step": db_setting.step,
"visible": db_setting.visible,
- "editable": db_setting.editable
+ "editable": db_setting.editable,
}
else:
# Return minimal info
- setting_data = {
- "key": key,
- "value": value
- }
-
+ setting_data = {"key": key, "value": value}
+
return jsonify({"setting": setting_data})
except Exception as e:
logger.error(f"Error getting setting {key}: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/<path:key>", methods=["PUT"])
def update_setting(key):
"""Update a setting"""
@@ -114,23 +126,23 @@ def update_setting(key):
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
-
+
value = data.get("value")
if value is None:
return jsonify({"error": "No value provided"}), 400
-
+
# Get DB session and settings manager
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Check if setting exists
db_setting = db_session.query(Setting).filter(Setting.key == key).first()
-
+
if db_setting:
# Check if setting is editable
if not db_setting.editable:
return jsonify({"error": f"Setting {key} is not editable"}), 403
-
+
# Update setting
success = settings_manager.set_setting(key, value)
if success:
@@ -142,47 +154,64 @@ def update_setting(key):
setting_dict = {
"key": key,
"value": value,
- "name": key.split('.')[-1].replace('_', ' ').title(),
- "description": f"Setting for {key}"
+ "name": key.split(".")[-1].replace("_", " ").title(),
+ "description": f"Setting for {key}",
}
-
+
# Add additional metadata if provided
- for field in ["type", "name", "description", "category", "ui_element",
- "options", "min_value", "max_value", "step", "visible", "editable"]:
+ for field in [
+ "type",
+ "name",
+ "description",
+ "category",
+ "ui_element",
+ "options",
+ "min_value",
+ "max_value",
+ "step",
+ "visible",
+ "editable",
+ ]:
if field in data:
setting_dict[field] = data[field]
-
+
# Create setting
db_setting = settings_manager.create_or_update_setting(setting_dict)
-
+
if db_setting:
- return jsonify({
- "message": f"Setting {key} created successfully",
- "setting": {
- "key": db_setting.key,
- "value": db_setting.value,
- "type": db_setting.type.value,
- "name": db_setting.name
- }
- }), 201
+ return (
+ jsonify(
+ {
+ "message": f"Setting {key} created successfully",
+ "setting": {
+ "key": db_setting.key,
+ "value": db_setting.value,
+ "type": db_setting.type.value,
+ "name": db_setting.name,
+ },
+ }
+ ),
+ 201,
+ )
else:
return jsonify({"error": f"Failed to create setting {key}"}), 500
except Exception as e:
logger.error(f"Error updating setting {key}: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/<path:key>", methods=["DELETE"])
def delete_setting(key):
"""Delete a setting"""
try:
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Check if setting exists
db_setting = db_session.query(Setting).filter(Setting.key == key).first()
if not db_setting:
return jsonify({"error": f"Setting not found: {key}"}), 404
-
+
# Delete setting
success = settings_manager.delete_setting(key)
if success:
@@ -193,26 +222,30 @@ def delete_setting(key):
logger.error(f"Error deleting setting {key}: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/export", methods=["POST"])
def export_settings():
"""Export settings to file"""
try:
data = request.get_json() or {}
setting_type_str = data.get("type")
-
+
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Export settings
if setting_type_str:
try:
setting_type = SettingType[setting_type_str.upper()]
success = settings_manager.export_to_file(setting_type)
except KeyError:
- return jsonify({"error": f"Invalid setting type: {setting_type_str}"}), 400
+ return (
+ jsonify({"error": f"Invalid setting type: {setting_type_str}"}),
+ 400,
+ )
else:
success = settings_manager.export_to_file()
-
+
if success:
return jsonify({"message": "Settings exported successfully"})
else:
@@ -221,26 +254,30 @@ def export_settings():
logger.error(f"Error exporting settings: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/import", methods=["POST"])
def import_settings():
"""Import settings from file"""
try:
data = request.get_json() or {}
setting_type_str = data.get("type")
-
+
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Import settings
if setting_type_str:
try:
setting_type = SettingType[setting_type_str.upper()]
success = settings_manager.import_from_file(setting_type)
except KeyError:
- return jsonify({"error": f"Invalid setting type: {setting_type_str}"}), 400
+ return (
+ jsonify({"error": f"Invalid setting type: {setting_type_str}"}),
+ 400,
+ )
else:
success = settings_manager.import_from_file()
-
+
if success:
return jsonify({"message": "Settings imported successfully"})
else:
@@ -249,21 +286,23 @@ def import_settings():
logger.error(f"Error importing settings: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/categories", methods=["GET"])
def get_categories():
"""Get all setting categories"""
try:
db_session = get_db_session()
-
+
# Get all distinct categories
categories = db_session.query(Setting.category).distinct().all()
category_list = [c[0] for c in categories if c[0] is not None]
-
+
return jsonify({"categories": category_list})
except Exception as e:
logger.error(f"Error getting categories: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/types", methods=["GET"])
def get_types():
"""Get all setting types"""
@@ -275,222 +314,229 @@ def get_types():
logger.error(f"Error getting types: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/ui_elements", methods=["GET"])
def get_ui_elements():
"""Get all UI element types"""
try:
# Define supported UI element types
ui_elements = [
- "text", "select", "checkbox", "slider", "number",
- "textarea", "color", "date", "file", "password"
+ "text",
+ "select",
+ "checkbox",
+ "slider",
+ "number",
+ "textarea",
+ "color",
+ "date",
+ "file",
+ "password",
]
-
+
return jsonify({"ui_elements": ui_elements})
except Exception as e:
logger.error(f"Error getting UI elements: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/available-models", methods=["GET"])
def get_available_models():
"""Get available language models"""
try:
- # Import needed modules
- from ...config.llm_config import get_available_providers, VALID_PROVIDERS, is_ollama_available
-
# Get available providers
providers = get_available_providers()
-
+
# Add more Ollama models if available
- if 'ollama' in providers:
+ if "ollama" in providers:
# Try to get Ollama models directly from Ollama API
try:
- import requests
- from ...config.llm_config import settings
-
# Get the Ollama base URL from settings
base_url = settings.get(
- "OLLAMA_BASE_URL",
- settings.llm.get("ollama_base_url", "http://localhost:11434")
+ "OLLAMA_BASE_URL",
+ settings.llm.get("ollama_base_url", "http://localhost:11434"),
)
-
+
# Try to fetch available models from Ollama
response = requests.get(f"{base_url}/api/tags", timeout=3.0)
if response.status_code == 200:
ollama_data = response.json()
- if 'models' in ollama_data:
- ollama_models = ollama_data['models']
+ if "models" in ollama_data:
+ ollama_models = ollama_data["models"]
else:
# Older Ollama API versions might return a simpler structure
- ollama_models = [{"name": m} for m in ollama_data.get('models', [])]
-
+ ollama_models = [
+ {"name": m} for m in ollama_data.get("models", [])
+ ]
+
# Create a list of Ollama model options
ollama_model_options = []
for model in ollama_models:
- model_name = model.get('name')
+ model_name = model.get("name")
if model_name:
# Format label to be more readable
- if ':' in model_name:
- base_name, variant = model_name.split(':', 1)
+ if ":" in model_name:
+ base_name, variant = model_name.split(":", 1)
label = f"{base_name.title()} {variant} (Ollama)"
else:
label = f"{model_name.title()} (Ollama)"
-
- ollama_model_options.append({
- "value": model_name,
- "label": label
- })
-
+
+ ollama_model_options.append(
+ {"value": model_name, "label": label}
+ )
+
# Add additional context to the response
providers["ollama_models"] = ollama_model_options
+
except Exception as e:
logger.error(f"Error fetching Ollama models: {e}")
# Don't fail if we can't get Ollama models
providers["ollama_models"] = []
-
+
+ # Ensure that the model specified in the config file is always an
+ # option.
+ providers["config_models"] = [settings.llm.model]
+
# Prepare response data
models_info = {
"providers": providers,
"valid_providers": VALID_PROVIDERS,
"provider_options": [
- {"value": key, "label": value}
- for key, value in providers.items()
+ {"value": key, "label": value} for key, value in providers.items()
],
- "ollama_available": is_ollama_available()
+ "ollama_available": is_ollama_available(),
}
-
+
return jsonify(models_info)
except Exception as e:
logger.error(f"Error getting available models: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/available-search-engines", methods=["GET"])
def get_available_search_engines():
"""Get available search engines"""
try:
# First try to get engines from search_engines.toml file
engines_dict = get_engines_from_file()
-
+
# If we got engines from file, use those
if engines_dict:
# Make sure searxng is included if it should be
- if 'searxng' not in engines_dict:
- engines_dict['searxng'] = {
- 'display_name': 'SearXNG (Self-hosted)',
- 'description': 'Self-hosted metasearch engine',
- 'strengths': ['privacy', 'customization', 'no API key needed']
+ if "searxng" not in engines_dict:
+ engines_dict["searxng"] = {
+ "display_name": "SearXNG (Self-hosted)",
+ "description": "Self-hosted metasearch engine",
+ "strengths": ["privacy", "customization", "no API key needed"],
}
-
+
# Format as options for dropdown
engine_options = [
- {"value": key, "label": engines_dict.get(key, {}).get("display_name", key)}
+ {
+ "value": key,
+ "label": engines_dict.get(key, {}).get("display_name", key),
+ }
for key in engines_dict.keys()
]
-
- return jsonify({
- "engines": engines_dict,
- "engine_options": engine_options
- })
-
+
+ return jsonify({"engines": engines_dict, "engine_options": engine_options})
+
# Fallback to factory function if file method failed
try:
- # Import needed modules
- from ...web_search_engines.search_engine_factory import get_available_engines
- from ...defaults import search_engines as default_engines
-
# Get available engines
search_engines = get_available_engines(include_api_key_services=True)
-
+
# Handle if search_engines is a list (not a dict)
if isinstance(search_engines, list):
# Convert to dict with engine name as key and display name as value
- engines_dict = {engine: engine.replace('_', ' ').title() for engine in search_engines}
+ engines_dict = {
+ engine: engine.replace("_", " ").title()
+ for engine in search_engines
+ }
else:
engines_dict = search_engines
-
+
# Make sure searxng is included
- if 'searxng' not in engines_dict:
- engines_dict['searxng'] = 'SearXNG (Self-hosted)'
-
+ if "searxng" not in engines_dict:
+ engines_dict["searxng"] = "SearXNG (Self-hosted)"
+
# Format as options for dropdown
engine_options = [
- {"value": key, "label": value if isinstance(value, str) else key.replace('_', ' ').title()}
+ {
+ "value": key,
+ "label": (
+ value
+ if isinstance(value, str)
+ else key.replace("_", " ").title()
+ ),
+ }
for key, value in engines_dict.items()
]
-
- return jsonify({
- "engines": engines_dict,
- "engine_options": engine_options
- })
+
+ return jsonify({"engines": engines_dict, "engine_options": engine_options})
except Exception as e:
# If both methods fail, return default engines with searxng
logger.error(f"Error getting available search engines from factory: {e}")
-
+
# Use hardcoded defaults from search_engines.toml
defaults = {
"wikipedia": "Wikipedia",
- "arxiv": "ArXiv Papers",
+ "arxiv": "ArXiv Papers",
"pubmed": "PubMed Medical",
"github": "GitHub Code",
"searxng": "SearXNG (Self-hosted)",
"serpapi": "SerpAPI (Google)",
"google_pse": "Google PSE",
- "auto": "Auto-select"
+ "auto": "Auto-select",
}
-
+
engine_options = [
- {"value": key, "label": value}
- for key, value in defaults.items()
+ {"value": key, "label": value} for key, value in defaults.items()
]
-
- return jsonify({
- "engines": defaults,
- "engine_options": engine_options
- })
-
+
+ return jsonify({"engines": defaults, "engine_options": engine_options})
+
except Exception as e:
logger.error(f"Error getting available search engines: {e}")
return jsonify({"error": str(e)}), 500
+
def get_engines_from_file():
"""Get available search engines directly from the toml file"""
try:
- import toml
- from pathlib import Path
- from ...config.config_files import CONFIG_DIR, get_config_dir
-
# Try to load from the actual config directory
config_dir = get_config_dir()
search_engines_file = config_dir / "config" / "search_engines.toml"
-
+
# If file doesn't exist in user config, try the defaults
if not search_engines_file.exists():
# Look in the defaults folder instead
- from ...defaults import search_engines
import inspect
-
+
+ from ...defaults import search_engines
+
# Get the path to the search_engines.toml file
module_path = inspect.getfile(search_engines)
default_file = Path(module_path)
-
- if default_file.exists() and default_file.suffix == '.toml':
+
+ if default_file.exists() and default_file.suffix == ".toml":
search_engines_file = default_file
-
+
# If we found a file, load it
if search_engines_file.exists():
data = toml.load(search_engines_file)
-
+
# Filter out the metadata entries (like DEFAULT_SEARCH_ENGINE)
engines = {k: v for k, v in data.items() if isinstance(v, dict)}
-
+
# Add display names for each engine
for key, engine in engines.items():
- if 'display_name' not in engine:
+ if "display_name" not in engine:
# Create a display name from the key
- engine['display_name'] = key.replace('_', ' ').title()
-
+ engine["display_name"] = key.replace("_", " ").title()
+
return engines
-
+
return None
except Exception as e:
logger.error(f"Error loading search engines from file: {e}")
- return None
\ No newline at end of file
+ return None
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 b13e257a70..4950294560 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -17,7 +17,7 @@
let questionsPerIterationInput = null;
let advancedToggle = null;
let advancedPanel = null;
-
+
/**
* Initialize the research component
*/
@@ -36,23 +36,23 @@
questionsPerIterationInput = document.getElementById('questions_per_iteration');
advancedToggle = document.querySelector('.advanced-options-toggle');
advancedPanel = document.querySelector('.advanced-options-panel');
-
+
if (!form || !queryInput || !modeOptions.length || !startBtn) {
console.error('Required DOM elements not found for research component');
return;
}
-
+
// Set up event listeners
setupEventListeners();
-
+
// Load data
loadModelOptions();
loadSearchEngineOptions();
loadSettings();
-
+
console.log('Research component initialized');
}
-
+
/**
* Set up event listeners for the research form
*/
@@ -62,27 +62,27 @@
option.addEventListener('click', function() {
// Remove active class from all options
modeOptions.forEach(opt => opt.classList.remove('active'));
-
+
// Add active class to clicked option
this.classList.add('active');
});
});
-
+
// Form submission
form.addEventListener('submit', handleResearchSubmit);
-
+
// Advanced options toggle
if (advancedToggle && advancedPanel) {
// Set initial state (closed by default)
advancedPanel.style.display = 'none';
advancedToggle.classList.remove('open');
-
+
advancedToggle.addEventListener('click', function() {
const isVisible = advancedPanel.style.display === 'block';
-
+
// Toggle panel visibility
advancedPanel.style.display = isVisible ? 'none' : 'block';
-
+
// Toggle class for arrow rotation
if (isVisible) {
advancedToggle.classList.remove('open');
@@ -92,7 +92,7 @@
});
}
}
-
+
/**
* Check if Ollama is running and model is available
* @returns {Promise<Object>} Result with status and error message if any
@@ -103,15 +103,15 @@
// First check if the Ollama service is running
try {
const statusResponse = await fetch('/research/api/check/ollama_status');
-
+
// If we get a 404, assume the API doesn't exist and skip the check
if (statusResponse.status === 404) {
console.log('Ollama status check endpoint not available, skipping check');
return { success: true };
}
-
+
const statusData = await statusResponse.json();
-
+
if (!statusData.running) {
return {
success: false,
@@ -119,18 +119,18 @@
solution: "Run 'ollama serve' in your terminal to start the service."
};
}
-
+
// Then check if the model is available
const modelResponse = await fetch('/research/api/check/ollama_model');
-
+
// If we get a 404, assume the API doesn't exist and skip the check
if (modelResponse.status === 404) {
console.log('Ollama model check endpoint not available, skipping check');
return { success: true };
}
-
+
const modelData = await modelResponse.json();
-
+
if (!modelData.available) {
const modelName = modelData.model || "gemma3:12b";
return {
@@ -145,7 +145,7 @@
console.log('Error checking Ollama status, skipping check:', error);
return { success: true };
}
-
+
return { success: true };
} catch (error) {
console.error('Error checking Ollama:', error);
@@ -156,14 +156,14 @@
};
}
}
-
+
/**
* Handle research form submission
* @param {Event} e - The form submit event
*/
async function handleResearchSubmit(e) {
e.preventDefault();
-
+
// Get form values
const query = queryInput.value.trim();
const activeMode = document.querySelector('.mode-option.active');
@@ -175,19 +175,19 @@
const iterations = iterationsInput ? iterationsInput.value : '2';
const questionsPerIteration = questionsPerIterationInput ? questionsPerIterationInput.value : '3';
const enableNotifications = notificationToggle ? notificationToggle.checked : true;
-
+
// Validate input
if (!query) {
showFormError('Please enter a research query');
return;
}
-
+
// Debug selected values
console.log(`Starting research with model: ${model}, search engine: ${searchEngine}`);
-
+
// Disable form
setFormSubmitting(true);
-
+
try {
// First check if Ollama is running and model is available
const ollamaCheck = await checkOllamaModel();
@@ -196,7 +196,7 @@
setFormSubmitting(false);
return;
}
-
+
// Prepare request payload - ensure consistent property names with backend
const payload = {
query,
@@ -209,9 +209,9 @@
iterations,
questions_per_iteration: questionsPerIteration
};
-
+
console.log('Sending research request with payload:', JSON.stringify(payload));
-
+
// Start research process using fetch API
window.fetch('/research/api/start_research', {
method: 'POST',
@@ -232,7 +232,7 @@
window.localStorage.setItem('notificationsEnabled', enableNotifications);
window.localStorage.setItem('lastUsedModel', model);
window.localStorage.setItem('lastUsedSearchEngine', searchEngine);
-
+
// Navigate to progress page
navigateToResearchProgress(data.research_id, query, mode);
} else {
@@ -241,14 +241,14 @@
})
.catch(error => {
console.error('Error starting research:', error);
-
+
// Handle common errors
if (error.message.includes('409')) {
showFormError('Another research is already in progress. Please wait for it to complete.');
} else {
showFormError(`Error starting research: ${error.message}`);
}
-
+
// Re-enable the form
setFormSubmitting(false);
});
@@ -258,7 +258,7 @@
setFormSubmitting(false);
}
}
-
+
/**
* Show an error message on the form
* @param {string} message - The error message to display
@@ -266,24 +266,24 @@
function showFormError(message) {
// Check if error element already exists
let errorEl = form.querySelector('.form-error');
-
+
if (!errorEl) {
// Create error element
errorEl = document.createElement('div');
errorEl.className = 'form-error error-message';
form.insertBefore(errorEl, form.querySelector('.form-actions'));
}
-
+
// Set error message
errorEl.textContent = message;
errorEl.style.display = 'block';
-
+
// Hide error after 5 seconds
setTimeout(() => {
errorEl.style.display = 'none';
}, 5000);
}
-
+
/**
* Set the form to submitting state
* @param {boolean} isSubmitting - Whether the form is submitting
@@ -291,17 +291,17 @@
function setFormSubmitting(isSubmitting) {
startBtn.disabled = isSubmitting;
queryInput.disabled = isSubmitting;
-
+
modeOptions.forEach(option => {
option.style.pointerEvents = isSubmitting ? 'none' : 'auto';
option.style.opacity = isSubmitting ? '0.7' : '1';
});
-
- startBtn.innerHTML = isSubmitting ?
- '<i class="fas fa-spinner fa-spin"></i> Starting...' :
+
+ startBtn.innerHTML = isSubmitting ?
+ '<i class="fas fa-spinner fa-spin"></i> Starting...' :
'<i class="fas fa-rocket"></i> Start Research';
}
-
+
/**
* Navigate to the research progress page
* @param {number} researchId - The research ID
@@ -313,27 +313,27 @@
window.localStorage.setItem('currentResearchId', researchId);
window.localStorage.setItem('currentQuery', query);
window.localStorage.setItem('currentMode', mode);
-
+
// Navigate to progress page
window.location.href = `/research/progress/${researchId}`;
}
-
+
/**
* Load language model options from API
*/
function loadModelOptions() {
if (!modelSelect) return;
-
+
// Set "Loading..." option temporarily
modelSelect.innerHTML = '<option value="">Loading models...</option>';
-
+
// Only populate the dropdown once with all options combined
// Fetch all data sources in parallel first
Promise.all([
// Get available models from API
fetch('/research/api/available-models')
.then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`)),
-
+
// Get current setting value
fetch('/research/api/?type=llm')
.then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`))
@@ -342,7 +342,7 @@
.then(([modelsData, settingsData]) => {
let modelOptions = [];
let selectedValue = null;
-
+
// 1. Add Ollama models if available
if (modelsData.providers && modelsData.providers.ollama_models && modelsData.providers.ollama_models.length > 0) {
console.log('Found Ollama models:', modelsData.providers.ollama_models);
@@ -363,7 +363,7 @@
{ value: 'deepseek-r1:32b', label: 'DeepSeek R1 32B (Ollama)' }
];
}
-
+
// 2. Add standard model options (these always appear, even without Ollama)
modelOptions = [
...modelOptions,
@@ -372,30 +372,34 @@
{ 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;
}
-
+
+ // 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 }))];
+
// Make sure we don't have duplicates (by value)
const uniqueOptions = [];
const uniqueValues = new Set();
-
+
modelOptions.forEach(option => {
if (!uniqueValues.has(option.value)) {
uniqueValues.add(option.value);
uniqueOptions.push(option);
}
});
-
+
// Finally populate the dropdown once with all options
populateSelectWithOptions(modelSelect, uniqueOptions, selectedValue || 'mistral');
})
.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)' },
@@ -405,17 +409,17 @@
{ 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');
});
}
-
+
/**
* Load search engine options from API
*/
function loadSearchEngineOptions() {
if (!searchEngineSelect) return;
-
+
// Set default options in case API call fails
const defaultOptions = [
{ value: 'auto', label: 'Auto (Default)' },
@@ -424,10 +428,10 @@
{ value: 'serpapi', label: 'SerpAPI (Google)' },
{ value: 'duckduckgo', label: 'DuckDuckGo' }
];
-
+
// Start with default options
populateSelectWithOptions(searchEngineSelect, defaultOptions, 'auto');
-
+
// Try to get search engine options from API
fetch('/research/api/available-search-engines')
.then(response => {
@@ -447,11 +451,11 @@
// If 'auto' doesn't exist in the options, add it
data.engine_options.unshift({ value: 'auto', label: 'Auto (Default)' });
}
-
+
// Always use 'auto' as the default value
populateSelectWithOptions(searchEngineSelect, data.engine_options, 'auto');
}
-
+
// Also get the current setting value
return fetch('/research/api/?type=search');
})
@@ -464,7 +468,7 @@
// 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) {
@@ -475,7 +479,7 @@
console.error('Error loading search settings:', error);
});
}
-
+
/**
* Load other settings from API
*/
@@ -489,7 +493,7 @@
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 => {
@@ -501,7 +505,7 @@
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}"]`);
@@ -514,7 +518,7 @@
.catch(error => {
console.error('Error loading search settings:', error);
});
-
+
// Try to load app settings
fetch('/research/api/?type=app')
.then(response => {
@@ -526,11 +530,11 @@
if (iterationsInput && data.settings['app.research_iterations'] !== undefined) {
iterationsInput.value = data.settings['app.research_iterations'];
}
-
+
if (questionsPerIterationInput && data.settings['app.questions_per_iteration'] !== undefined) {
questionsPerIterationInput.value = data.settings['app.questions_per_iteration'];
}
-
+
if (notificationToggle && data.settings['app.enable_notifications'] !== undefined) {
notificationToggle.checked = data.settings['app.enable_notifications'];
}
@@ -540,7 +544,7 @@
console.error('Error loading app settings:', error);
});
}
-
+
/**
* Populate a select element with options
* @param {HTMLSelectElement} selectElement - The select element to populate
@@ -550,26 +554,26 @@
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);
} else {
initializeResearch();
}
-})();
\ No newline at end of file
+})();