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.

Fix benchmark page model loading and BrowseComp questions

LearningCircuit2f713588b696
diff --git a/pdm.lock b/pdm.lock
index 657ba65279..f38c5eea83 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:b563bbfd76233a89f971c3f77ab133a18ecac1e040fe635c847f033d6a67490d"
+content_hash = "sha256:50ff5ea72f7413571a89ab1d6ec1763b13d2846b544caea2346e76756d5db248"
[[metadata.targets]]
requires_python = ">=3.10"
@@ -4043,6 +4043,21 @@ files = [
{file = "pytest-8.4.0.tar.gz", hash = "sha256:14d920b48472ea0dbf68e45b96cd1ffda4705f33307dcc86c676c1b5104838a6"},
]
+[[package]]
+name = "pytest-asyncio"
+version = "1.0.0"
+requires_python = ">=3.9"
+summary = "Pytest support for asyncio"
+groups = ["dev"]
+dependencies = [
+ "pytest<9,>=8.2",
+ "typing-extensions>=4.12; python_version < \"3.10\"",
+]
+files = [
+ {file = "pytest_asyncio-1.0.0-py3-none-any.whl", hash = "sha256:4f024da9f1ef945e680dc68610b52550e36590a67fd31bb3b4943979a1f90ef3"},
+ {file = "pytest_asyncio-1.0.0.tar.gz", hash = "sha256:d15463d13f4456e1ead2594520216b225a16f781e144f8fdf6c5bb4667c48b3f"},
+]
+
[[package]]
name = "pytest-cov"
version = "6.1.1"
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index cc9e1d7dde..bb88a64f2d 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -7,7 +7,7 @@ from loguru import logger
from .benchmark_service import benchmark_service
from ...web.utils.templates import render_template_with_defaults
from ...web.services.settings_manager import SettingsManager
-from ...utilities.db_utils import get_db_session
+from ...utilities.db_utils import get_db_session, get_db_setting
# Create blueprint for benchmark routes
benchmark_bp = Blueprint("benchmark", __name__, url_prefix="/benchmark")
@@ -16,7 +16,23 @@ benchmark_bp = Blueprint("benchmark", __name__, url_prefix="/benchmark")
@benchmark_bp.route("/")
def index():
"""Benchmark dashboard page."""
- return render_template_with_defaults("pages/benchmark.html")
+ # Load evaluation settings from database
+ eval_settings = {
+ "evaluation_provider": get_db_setting(
+ "benchmark.evaluation.provider", "openai_endpoint"
+ ),
+ "evaluation_model": get_db_setting("benchmark.evaluation.model", ""),
+ "evaluation_endpoint_url": get_db_setting(
+ "benchmark.evaluation.endpoint_url", ""
+ ),
+ "evaluation_temperature": get_db_setting(
+ "benchmark.evaluation.temperature", 0
+ ),
+ }
+
+ return render_template_with_defaults(
+ "pages/benchmark.html", eval_settings=eval_settings
+ )
@benchmark_bp.route("/results")
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index e9e33bba90..37f6d19cb8 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -331,7 +331,7 @@ class BenchmarkService:
question = example.get("problem", "")
correct_answer = example.get("answer", "")
else: # browsecomp
- question = example.get("question", "")
+ question = example.get("problem", "")
correct_answer = example.get("answer", "")
# Generate query hash
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 14fe48fc66..9dae4db2d1 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -186,6 +186,9 @@ def register_blueprints(app):
settings = {
"llm_provider": get_db_setting("llm.provider", "ollama"),
"llm_model": get_db_setting("llm.model", ""),
+ "llm_openai_endpoint_url": get_db_setting(
+ "llm.openai_endpoint.url", ""
+ ),
"search_tool": get_db_setting("search.tool", ""),
"search_iterations": get_db_setting("search.iterations", 2),
"search_questions_per_iteration": get_db_setting(
@@ -193,6 +196,9 @@ def register_blueprints(app):
),
}
+ # Debug logging
+ logger.debug(f"Settings loaded: {settings}")
+
return render_template_with_defaults(
"pages/research.html", settings=settings
)
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.py
index 650c206982..7db3eb2be1 100644
--- a/src/local_deep_research/web/database/models.py
+++ b/src/local_deep_research/web/database/models.py
@@ -220,3 +220,21 @@ class RateLimitEstimate(Base):
updated_at = Column(
DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
)
+
+
+class ProviderModel(Base):
+ """Database model for caching available models from all providers."""
+
+ __tablename__ = "provider_models"
+
+ id = Column(Integer, primary_key=True, index=True)
+ provider = Column(String(50), nullable=False, index=True)
+ model_key = Column(String(255), nullable=False)
+ model_label = Column(String(255), nullable=False)
+ model_metadata = Column(JSON, nullable=True) # For additional model info
+ last_updated = Column(DateTime, server_default=func.now(), nullable=False)
+
+ # Composite unique constraint to prevent duplicates
+ __table_args__ = (
+ UniqueConstraint("provider", "model_key", name="uix_provider_model"),
+ )
diff --git a/src/local_deep_research/web/database/schema_upgrade.py b/src/local_deep_research/web/database/schema_upgrade.py
index 53bab1ce1b..bf32683416 100644
--- a/src/local_deep_research/web/database/schema_upgrade.py
+++ b/src/local_deep_research/web/database/schema_upgrade.py
@@ -7,7 +7,7 @@ import os
import sys
from loguru import logger
-from sqlalchemy import create_engine, inspect
+from sqlalchemy import create_engine, inspect, text
# Add the parent directory to sys.path to allow relative imports
sys.path.append(
@@ -420,6 +420,50 @@ def convert_research_id_to_string_if_needed(engine):
return False
+def create_provider_models_table(engine):
+ """Create provider_models table for caching available models"""
+ with engine.connect() as conn:
+ result = conn.execute(
+ text(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='provider_models'"
+ )
+ )
+ if result.fetchone():
+ logger.info(
+ "Table 'provider_models' already exists, no action needed"
+ )
+ return
+
+ logger.info("Creating 'provider_models' table...")
+
+ # Create the table
+ conn.execute(
+ text(
+ """
+ CREATE TABLE provider_models (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ provider VARCHAR(50) NOT NULL,
+ model_key VARCHAR(255) NOT NULL,
+ model_label VARCHAR(255) NOT NULL,
+ model_metadata JSON,
+ last_updated DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
+ UNIQUE(provider, model_key)
+ )
+ """
+ )
+ )
+
+ # Create index on provider
+ conn.execute(
+ text(
+ "CREATE INDEX ix_provider_models_provider ON provider_models (provider)"
+ )
+ )
+
+ conn.commit()
+ logger.info("Table 'provider_models' created successfully")
+
+
def run_schema_upgrades():
"""
Run all schema upgrade operations on the database
@@ -461,6 +505,9 @@ def run_schema_upgrades():
# 7. Add uuid_id column to research_history if missing
add_uuid_id_column_to_research_history(engine)
+ # 8. Create provider_models table for caching
+ create_provider_models_table(engine)
+
logger.info("Schema upgrades completed successfully")
return True
except Exception:
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index ec9b5630a2..0ed85801cd 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -7,7 +7,6 @@ from typing import Any, Optional, Tuple
import requests
from flask import (
Blueprint,
- current_app,
flash,
jsonify,
redirect,
@@ -16,9 +15,8 @@ from flask import (
)
from flask_wtf.csrf import generate_csrf
from loguru import logger
-from sqlalchemy.orm import Session
-from ...utilities.db_utils import get_db_setting
+from ...utilities.db_utils import get_db_setting, get_db_session
from ...utilities.url_utils import normalize_url
from ..database.models import Setting, SettingType
from ..services.settings_service import (
@@ -27,6 +25,7 @@ from ..services.settings_service import (
get_settings_manager,
set_setting,
)
+from ..services.settings_manager import SettingsManager
from ..utils.templates import render_template_with_defaults
# Create a Blueprint for settings
@@ -111,14 +110,6 @@ def calculate_warnings():
return warnings
-def get_db_session() -> Session:
- """Get the database session from the app context"""
- if hasattr(current_app, "db_session"):
- return current_app.db_session
- else:
- return current_app.extensions["sqlalchemy"].session()
-
-
def validate_setting(
setting: Setting, value: Any
) -> Tuple[bool, Optional[str]]:
@@ -789,6 +780,15 @@ def api_get_ui_elements():
def api_get_available_models():
"""Get available LLM models from various providers"""
try:
+ from datetime import datetime, timedelta
+ from ..database.models import ProviderModel
+ from flask import request, current_app
+
+ # Check if force_refresh is requested
+ force_refresh = (
+ request.args.get("force_refresh", "false").lower() == "true"
+ )
+
# Define provider options with generic provider names
provider_options = [
{"value": "OLLAMA", "label": "Ollama (Local)"},
@@ -803,6 +803,56 @@ def api_get_available_models():
# Available models by provider
providers = {}
+ # Check database cache first (unless force_refresh is True)
+ if not force_refresh:
+ try:
+ db_session = current_app.db_session
+
+ # Define cache expiration (24 hours)
+ cache_expiry = datetime.utcnow() - timedelta(hours=24)
+
+ # Get cached models from database
+ cached_models = (
+ db_session.query(ProviderModel)
+ .filter(ProviderModel.last_updated > cache_expiry)
+ .all()
+ )
+
+ if cached_models:
+ logger.info(
+ f"Found {len(cached_models)} cached models in database"
+ )
+
+ # Group models by provider
+ for model in cached_models:
+ provider_key = f"{model.provider.lower()}_models"
+ if provider_key not in providers:
+ providers[provider_key] = []
+
+ providers[provider_key].append(
+ {
+ "value": model.model_key,
+ "label": model.model_label,
+ "provider": model.provider.upper(),
+ }
+ )
+
+ # If we have cached data for all providers, return it
+ if providers:
+ logger.info("Returning cached models from database")
+ return jsonify(
+ {
+ "provider_options": provider_options,
+ "providers": providers,
+ }
+ )
+
+ except Exception as e:
+ logger.warning(
+ f"Error reading cached models from database: {e}"
+ )
+ # Continue to fetch fresh data
+
# Try to get Ollama models
ollama_models = []
try:
@@ -1216,6 +1266,45 @@ def api_get_available_models():
providers["anthropic_models"] = anthropic_models
logger.info(f"Final Anthropic models count: {len(anthropic_models)}")
+ # Save fetched models to database cache
+ if force_refresh or not providers:
+ # We fetched fresh data, save it to database
+ try:
+ from datetime import datetime
+
+ db_session = current_app.db_session
+
+ # Clear old cache entries for providers we're updating
+ for provider_key in providers.keys():
+ provider_name = provider_key.replace("_models", "").upper()
+ db_session.query(ProviderModel).filter(
+ ProviderModel.provider == provider_name
+ ).delete()
+
+ # Insert new models
+ for provider_key, models in providers.items():
+ provider_name = provider_key.replace("_models", "").upper()
+ for model in models:
+ if (
+ isinstance(model, dict)
+ and "value" in model
+ and "label" in model
+ ):
+ new_model = ProviderModel(
+ provider=provider_name,
+ model_key=model["value"],
+ model_label=model["label"],
+ last_updated=datetime.utcnow(),
+ )
+ db_session.add(new_model)
+
+ db_session.commit()
+ logger.info("Successfully cached models to database")
+
+ except Exception as e:
+ logger.error(f"Error saving models to database cache: {e}")
+ db_session.rollback()
+
# Return all options
return jsonify(
{"provider_options": provider_options, "providers": providers}
@@ -1820,3 +1909,46 @@ def api_cleanup_rate_limiting():
except Exception:
logger.exception("Error cleaning up rate limiting data")
return jsonify({"error": "An internal error occurred"}), 500
+
+
+@settings_bp.route("/api/bulk", methods=["GET"])
+def get_bulk_settings():
+ """Get multiple settings at once for performance."""
+ try:
+ # Get requested settings from query parameters
+ requested = request.args.getlist("keys[]")
+ if not requested:
+ # Default to common settings if none specified
+ requested = [
+ "llm.provider",
+ "llm.model",
+ "search.tool",
+ "search.iterations",
+ "search.questions_per_iteration",
+ "search.search_strategy",
+ "benchmark.evaluation.provider",
+ "benchmark.evaluation.model",
+ "benchmark.evaluation.temperature",
+ "benchmark.evaluation.endpoint_url",
+ ]
+
+ # Fetch all settings at once
+ session = get_db_session()
+ settings_manager = SettingsManager(db_session=session)
+
+ result = {}
+ for key in requested:
+ try:
+ value = settings_manager.get_setting(key)
+ result[key] = {"value": value, "exists": value is not None}
+ except Exception as e:
+ logger.warning(f"Error getting setting {key}: {e}")
+ result[key] = {"value": None, "exists": False, "error": str(e)}
+
+ session.close()
+
+ return jsonify({"success": True, "settings": result})
+
+ except Exception as e:
+ logger.exception("Error getting bulk settings")
+ return jsonify({"success": False, "error": str(e)}), 500
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 6668e49891..20debae89f 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -148,6 +148,9 @@
populateModelProviders();
initializeDropdowns();
+ // Also set initial values here for immediate feedback
+ setInitialFormValues();
+
// Auto-focus the query input
if (queryInput) {
queryInput.focus();
@@ -158,14 +161,17 @@
}
// Set initial state of the advanced options panel based on localStorage
- const savedState = false; // Always start collapsed
+ const savedState = localStorage.getItem('advancedMenuOpen') === 'true';
if (savedState && advancedPanel) {
advancedPanel.style.display = 'block';
advancedPanel.classList.add('expanded');
if (advancedToggle) {
advancedToggle.classList.add('open');
+ advancedToggle.setAttribute('aria-expanded', 'true');
const icon = advancedToggle.querySelector('i');
if (icon) icon.className = 'fas fa-chevron-up';
+ const srText = advancedToggle.querySelector('.sr-only');
+ if (srText) srText.textContent = 'Click to collapse advanced options';
}
}
@@ -175,7 +181,7 @@
loadSearchEngineOptions(false)
]).then(([modelData, searchEngineData]) => {
// After loading model data, update the UI with the loaded data
- const currentProvider = modelProviderSelect ? modelProviderSelect.value : (lastProvider || 'OLLAMA');
+ const currentProvider = modelProviderSelect ? modelProviderSelect.value : 'OLLAMA';
updateModelOptionsForProvider(currentProvider, false);
// Update search engine options
@@ -228,11 +234,17 @@
}
}
+ // Set initial form values from data attributes
+ setInitialFormValues();
+
// Finally, load settings after data is available
loadSettings();
}).catch(error => {
console.error('Failed to load options:', error);
+ // Set initial form values even if data loading fails
+ setInitialFormValues();
+
// Still load settings even if data loading fails
loadSettings();
@@ -396,6 +408,65 @@
}
}
+ /**
+ * Set initial form values from data attributes
+ */
+ function setInitialFormValues() {
+ console.log('Setting initial form values...');
+
+ // Set initial model value if available
+ if (modelInput) {
+ const initialModel = modelInput.getAttribute('data-initial-value');
+ console.log('Initial model value from data attribute:', initialModel);
+ if (initialModel) {
+ // Find the matching model in the options
+ const matchingModel = modelOptions.find(m =>
+ m.value === initialModel || m.id === initialModel
+ );
+
+ if (matchingModel) {
+ modelInput.value = matchingModel.label;
+ selectedModelValue = matchingModel.value;
+ } else {
+ // If not found in options, set it as custom value
+ modelInput.value = initialModel;
+ selectedModelValue = initialModel;
+ }
+
+ // Update hidden input
+ const hiddenInput = document.getElementById('model_hidden');
+ if (hiddenInput) {
+ hiddenInput.value = selectedModelValue;
+ }
+ }
+ }
+
+ // Set initial search engine value if available
+ if (searchEngineInput) {
+ const initialSearchEngine = searchEngineInput.getAttribute('data-initial-value');
+ if (initialSearchEngine) {
+ // Find the matching search engine in the options
+ const matchingEngine = searchEngineOptions.find(e =>
+ e.value === initialSearchEngine || e.id === initialSearchEngine
+ );
+
+ if (matchingEngine) {
+ searchEngineInput.value = matchingEngine.label;
+ selectedSearchEngineValue = matchingEngine.value;
+ } else {
+ searchEngineInput.value = initialSearchEngine;
+ selectedSearchEngineValue = initialSearchEngine;
+ }
+
+ // Update hidden input
+ const hiddenInput = document.getElementById('search_engine_hidden');
+ if (hiddenInput) {
+ hiddenInput.value = selectedSearchEngineValue;
+ }
+ }
+ }
+ }
+
/**
* Setup event listeners
*/
@@ -405,23 +476,19 @@
// INITIALIZE ADVANCED OPTIONS FIRST - before any async operations
// Advanced options toggle - make immediately responsive
if (advancedToggle && advancedPanel) {
- // Set initial state based on localStorage, relying only on CSS classes
- const savedState = false; // Always start collapsed
+ // Set initial state based on localStorage
+ const savedState = localStorage.getItem('advancedMenuOpen') === 'true';
if (savedState) {
advancedToggle.classList.add('open');
advancedPanel.classList.add('expanded');
-
- // Update ARIA attributes
advancedToggle.setAttribute('aria-expanded', 'true');
- // Update screen reader text
const srText = advancedToggle.querySelector('.sr-only');
if (srText) {
srText.textContent = 'Click to collapse advanced options';
}
- // Update icon immediately
const icon = advancedToggle.querySelector('i');
if (icon) {
icon.className = 'fas fa-chevron-up';
@@ -429,17 +496,13 @@
} else {
advancedToggle.classList.remove('open');
advancedPanel.classList.remove('expanded');
-
- // Update ARIA attributes
advancedToggle.setAttribute('aria-expanded', 'false');
- // Update screen reader text
const srText = advancedToggle.querySelector('.sr-only');
if (srText) {
srText.textContent = 'Click to expand advanced options';
}
- // Ensure icon is correct
const icon = advancedToggle.querySelector('i');
if (icon) {
icon.className = 'fas fa-chevron-down';
@@ -462,7 +525,7 @@
}
// Save state to localStorage
- // Don't save to localStorage, let server handle state
+ localStorage.setItem('advancedMenuOpen', isOpen.toString());
// Update icon
const icon = this.querySelector('i');
@@ -678,11 +741,21 @@
modelProviderSelect.appendChild(option);
});
- // Default to Ollama
- modelProviderSelect.value = 'OLLAMA';
+ // Set initial value from data attribute or default to Ollama
+ const initialProvider = modelProviderSelect.getAttribute('data-initial-value') || 'OLLAMA';
+ 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';
+ } else {
+ console.warn('Endpoint container not found');
+ }
// Initial update of model options
- updateModelOptionsForProvider('OLLAMA');
+ updateModelOptionsForProvider(initialProvider.toUpperCase());
}
/**
@@ -1489,7 +1562,11 @@
}
// Fetch from API if cache is invalid or refresh is forced
- fetch(URLS.SETTINGS_API.AVAILABLE_MODELS)
+ const url = forceRefresh
+ ? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`
+ : URLS.SETTINGS_API.AVAILABLE_MODELS;
+
+ fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
@@ -1627,13 +1704,22 @@
];
}
- // Don't cache data - always use fresh from API
+ // In-memory cache to avoid excessive API calls within a session
+ const memoryCache = {};
+ const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
+
function cacheData(key, data) {
- // No-op - we don't cache anymore
+ memoryCache[key] = {
+ data: data,
+ timestamp: Date.now()
+ };
}
function getCachedData(key) {
- // No cache - always return null to force API fetch
+ const cached = memoryCache[key];
+ if (cached && (Date.now() - cached.timestamp < CACHE_DURATION)) {
+ return cached.data;
+ }
return null;
}
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 3509a134d6..ad3cc79b59 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -2644,7 +2644,11 @@
console.log('Fetching model providers from API');
// Create a promise and store it
- window.modelProvidersRequestInProgress = fetch(URLS.SETTINGS_API.AVAILABLE_MODELS)
+ const url = forceRefresh
+ ? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`
+ : URLS.SETTINGS_API.AVAILABLE_MODELS;
+
+ window.modelProvidersRequestInProgress = fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`API returned status: ${response.status}`);
diff --git a/src/local_deep_research/web/templates/components/custom_dropdown.html b/src/local_deep_research/web/templates/components/custom_dropdown.html
index 7025d3503a..76d389ffd9 100644
--- a/src/local_deep_research/web/templates/components/custom_dropdown.html
+++ b/src/local_deep_research/web/templates/components/custom_dropdown.html
@@ -1,4 +1,4 @@
-{% macro render_dropdown(input_id, dropdown_id, placeholder, label=None, help_text=None, allow_custom=False, show_refresh=False, refresh_aria_label="Refresh options", data_setting_key=None) %}
+{% macro render_dropdown(input_id, dropdown_id, placeholder, label=None, help_text=None, allow_custom=False, show_refresh=False, refresh_aria_label="Refresh options", data_setting_key=None, data_initial_value=None) %}
<div class="form-group">
{% if label %}
<label for="{{ input_id }}">{{ label }}</label>
@@ -10,12 +10,13 @@
<input type="text"
id="{{ input_id }}"
data-key="{{ data_setting_key or input_id }}"
+ {% if data_initial_value %}data-initial-value="{{ data_initial_value }}"{% endif %}
class="custom-dropdown-input"
placeholder="{{ placeholder }}"
autocomplete="off"
aria-haspopup="listbox">
<!-- Hidden input that will be included in form submission -->
- <input type="hidden" name="{{ input_id }}" id="{{ input_id }}_hidden" value="">
+ <input type="hidden" name="{{ input_id }}" id="{{ input_id }}_hidden" value="{{ data_initial_value or '' }}">
<div class="custom-dropdown-list" id="{{ dropdown_id }}-list"></div>
</div>
<button type="button"
@@ -30,12 +31,13 @@
<input type="text"
id="{{ input_id }}"
data-key="{{ data_setting_key or input_id }}"
+ {% if data_initial_value %}data-initial-value="{{ data_initial_value }}"{% endif %}
class="custom-dropdown-input"
placeholder="{{ placeholder }}"
autocomplete="off"
aria-haspopup="listbox">
<!-- Hidden input that will be included in form submission -->
- <input type="hidden" name="{{ input_id }}" id="{{ input_id }}_hidden" value="">
+ <input type="hidden" name="{{ input_id }}" id="{{ input_id }}_hidden" value="{{ data_initial_value or '' }}">
<div class="custom-dropdown-list" id="{{ dropdown_id }}-list"></div>
</div>
{% endif %}
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index 54f4f8f919..c10eea921c 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -741,7 +741,7 @@
<!-- Evaluation Provider Selection -->
<div class="form-group half">
<label for="evaluation_provider">Evaluation Provider</label>
- <select id="evaluation_provider" name="evaluation_provider" class="form-control">
+ <select id="evaluation_provider" name="evaluation_provider" class="form-control" data-initial-value="{{ eval_settings.evaluation_provider }}">
<option value="">Loading providers...</option>
</select>
<span class="input-help">Provider for the evaluation model</span>
@@ -757,7 +757,8 @@
help_text="Model to grade benchmark results",
allow_custom=true,
show_refresh=true,
- refresh_aria_label="Refresh evaluation model list"
+ refresh_aria_label="Refresh evaluation model list",
+ data_initial_value=eval_settings.evaluation_model
) }}
</div>
</div>
@@ -766,14 +767,14 @@
<!-- Evaluation Endpoint URL -->
<div class="form-group half">
<label for="evaluation_endpoint_url">Endpoint URL</label>
- <input type="text" id="evaluation_endpoint_url" name="evaluation_endpoint_url" class="form-control" placeholder="https://openrouter.ai/api/v1">
+ <input type="text" id="evaluation_endpoint_url" name="evaluation_endpoint_url" class="form-control" placeholder="https://openrouter.ai/api/v1" value="{{ eval_settings.evaluation_endpoint_url }}">
<span class="input-help">API endpoint for evaluation model</span>
</div>
<!-- Evaluation Temperature -->
<div class="form-group half">
<label for="evaluation_temperature">Temperature</label>
- <input type="range" id="evaluation_temperature" name="evaluation_temperature" class="form-control" min="0" max="1" step="0.1" value="0">
+ <input type="range" id="evaluation_temperature" name="evaluation_temperature" class="form-control" min="0" max="1" step="0.1" value="{{ eval_settings.evaluation_temperature }}">
<span class="input-help">0 recommended for consistent evaluation</span>
</div>
</div>
@@ -970,6 +971,13 @@
let currentBenchmarkId = null;
let progressInterval = null;
+// Global variables for evaluation settings data
+let evalProviderData = null;
+let evalModelData = null;
+let evalTempData = null;
+let evalEndpointData = null;
+
+
// Charts for performance tracking
let accuracyChart = null;
let timingChart = null;
@@ -987,9 +995,13 @@ let recentSearchCounts = [];
let searchQualityAlert = false;
document.addEventListener('DOMContentLoaded', function() {
- // Initialize socket service first
+ // Initialize socket service first - but don't let it keep retrying if it fails
if (window.socket && typeof window.socket.initializeSocket === 'function') {
- window.socket.initializeSocket();
+ try {
+ window.socket.initializeSocket();
+ } catch (e) {
+ console.warn('Socket initialization failed, continuing without real-time updates');
+ }
}
initializeBenchmarkForm();
@@ -1154,7 +1166,7 @@ function startProgressTracking() {
progressInterval = setInterval(() => {
updateBenchmarkProgress();
- }, 2000); // Update every 2 seconds
+ }, 3000); // Update every 3 seconds (reduced from 2 for better performance)
// Initialize socket if not already done
if (!window.socket || !window.socket.initializeSocket) {
@@ -1187,6 +1199,10 @@ function handleDetailedProgress(data) {
}
+// Track last update times to avoid too frequent updates
+let lastResultsUpdate = 0;
+let lastChartsUpdate = 0;
+
function updateBenchmarkProgress() {
if (!currentBenchmarkId) return;
@@ -1199,10 +1215,19 @@ function updateBenchmarkProgress() {
// Update question/answer displays
updateCurrentQuestion(status);
- updateRecentResults();
- // Update charts with current data
- updateCharts(status);
+ // Only update results every 10 seconds to avoid performance issues
+ const now = Date.now();
+ if (now - lastResultsUpdate > 10000) {
+ updateRecentResults();
+ lastResultsUpdate = now;
+ }
+
+ // Update charts every 5 seconds
+ if (now - lastChartsUpdate > 5000) {
+ updateCharts(status);
+ lastChartsUpdate = now;
+ }
// Update search result monitoring
updateSearchQualityMonitoring();
@@ -1328,6 +1353,15 @@ function resetForm() {
document.getElementById('performance-charts-section').style.display = 'none';
currentBenchmarkId = null;
+ // Clear any running intervals
+ if (progressInterval) {
+ clearInterval(progressInterval);
+ progressInterval = null;
+ }
+
+ // Reset loading flags
+ window.modelsLoading = false;
+
// Reset chart data
chartData = {
examples: [],
@@ -1355,9 +1389,9 @@ function resetForm() {
searchResultsChart = null;
}
- if (progressInterval) {
- clearInterval(progressInterval);
- progressInterval = null;
+ // Unsubscribe from socket events if connected
+ if (window.socket && window.socket.unsubscribeFromResearch) {
+ window.socket.unsubscribeFromResearch(currentBenchmarkId);
}
}
@@ -1408,51 +1442,61 @@ async function loadCurrentSettings() {
console.log('Starting loadCurrentSettings...');
try {
- // Load all settings individually
- console.log('Fetching settings from API...');
- const [llmResponse, searchToolResponse, iterationsResponse, questionsResponse, strategyResponse, evalProviderResponse, evalModelResponse, evalTempResponse, evalEndpointResponse] = await Promise.all([
- fetch('/research/settings/api/llm'),
- fetch('/research/settings/api/search.tool'),
- fetch('/research/settings/api/search.iterations'),
- fetch('/research/settings/api/search.questions_per_iteration'),
- fetch('/research/settings/api/search.search_strategy'),
- fetch('/research/settings/api/benchmark.evaluation.provider'),
- fetch('/research/settings/api/benchmark.evaluation.model'),
- fetch('/research/settings/api/benchmark.evaluation.temperature'),
- fetch('/research/settings/api/benchmark.evaluation.endpoint_url')
+ // Load settings individually
+ const [
+ llmProviderResp,
+ llmModelResp,
+ searchToolResp,
+ iterationsResp,
+ questionsResp,
+ strategyResp,
+ evalProviderResp,
+ evalModelResp,
+ evalTempResp,
+ evalEndpointResp
+ ] = await Promise.all([
+ fetch('/settings/api/llm.provider'),
+ fetch('/settings/api/llm.model'),
+ fetch('/settings/api/search.tool'),
+ fetch('/settings/api/search.iterations'),
+ fetch('/settings/api/search.questions_per_iteration'),
+ fetch('/settings/api/search.search_strategy'),
+ fetch('/settings/api/benchmark.evaluation.provider'),
+ fetch('/settings/api/benchmark.evaluation.model'),
+ fetch('/settings/api/benchmark.evaluation.temperature'),
+ fetch('/settings/api/benchmark.evaluation.endpoint_url')
]);
- console.log('API responses received, checking status...');
- console.log('LLM response status:', llmResponse.status);
- console.log('Search tool response status:', searchToolResponse.status);
-
- const llmData = await llmResponse.json();
- const searchToolData = await searchToolResponse.json();
- const iterationsData = await iterationsResponse.json();
- const questionsData = await questionsResponse.json();
- const strategyData = await strategyResponse.json();
- const evalProviderData = await evalProviderResponse.json();
- const evalModelData = await evalModelResponse.json();
- const evalTempData = await evalTempResponse.json();
- const evalEndpointData = await evalEndpointResponse.json();
-
- console.log('Loaded settings:', { llmData, searchToolData, iterationsData, questionsData, strategyData, evalProviderData, evalModelData, evalTempData, evalEndpointData });
+ // Parse responses
+ const llmProviderData = await llmProviderResp.json();
+ const llmModelData = await llmModelResp.json();
+ const searchToolData = await searchToolResp.json();
+ const iterationsData = await iterationsResp.json();
+ const questionsData = await questionsResp.json();
+ const strategyData = await strategyResp.json();
+ evalProviderData = await evalProviderResp.json();
+ evalModelData = await evalModelResp.json();
+ evalTempData = await evalTempResp.json();
+ evalEndpointData = await evalEndpointResp.json();
// Display LLM settings with error handling
try {
- if (llmData && llmData.settings && llmData.settings.value) {
- const settings = llmData.settings.value;
-
- const providerEl = document.getElementById('current-provider');
- const modelEl = document.getElementById('current-model');
+ const providerEl = document.getElementById('current-provider');
+ const modelEl = document.getElementById('current-model');
- if (providerEl) providerEl.textContent = settings.provider ? settings.provider.toUpperCase() : 'Not set';
- if (modelEl) modelEl.textContent = settings.model || 'Not set';
+ // Set provider
+ if (llmProviderData && llmProviderData.settings && llmProviderData.settings.value) {
+ const provider = llmProviderData.settings.value;
+ if (providerEl) providerEl.textContent = provider ? provider.toUpperCase() : 'Not set';
} else {
- // Set defaults if no data
- const providerEl = document.getElementById('current-provider');
- const modelEl = document.getElementById('current-model');
if (providerEl) providerEl.textContent = 'Not set';
+ }
+
+ // Set model
+ if (llmModelData && llmModelData.settings && llmModelData.settings.value) {
+ const model = llmModelData.settings.value;
+ if (modelEl) modelEl.textContent = model || 'Not set';
+ } else {
if (modelEl) modelEl.textContent = 'Not set';
}
} catch (e) {
@@ -1471,7 +1515,7 @@ async function loadCurrentSettings() {
}
// Display search iterations
- if (iterationsData && iterationsData.settings && iterationsData.settings.value) {
+ if (iterationsData && iterationsData.settings && iterationsData.settings.value !== null) {
document.getElementById('current-iterations').textContent =
iterationsData.settings.value || '8';
} else {
@@ -1479,7 +1523,7 @@ async function loadCurrentSettings() {
}
// Display questions per iteration
- if (questionsData && questionsData.settings && questionsData.settings.value) {
+ if (questionsData && questionsData.settings && questionsData.settings.value !== null) {
document.getElementById('current-questions').textContent =
questionsData.settings.value || '5';
} else {
@@ -1549,14 +1593,24 @@ function updateCurrentQuestion(status) {
}
}
+// Cache last results to avoid unnecessary re-renders
+let lastResultsData = null;
+
function updateRecentResults() {
if (!currentBenchmarkId) return;
- fetch(`/benchmark/api/results/${currentBenchmarkId}?limit=100`)
+ fetch(`/benchmark/api/results/${currentBenchmarkId}?limit=50`) // Reduced from 100 for performance
.then(response => response.json())
.then(data => {
if (data.success && data.results) {
- displayRecentResults(data.results);
+ // Only update if data has changed
+ const newResultsStr = JSON.stringify(data.results);
+ const oldResultsStr = JSON.stringify(lastResultsData);
+
+ if (newResultsStr !== oldResultsStr) {
+ lastResultsData = data.results;
+ displayRecentResults(data.results);
+ }
}
})
.catch(error => {
@@ -2110,6 +2164,9 @@ let evaluationTemperatureInput = null;
function initializeEvaluationSettings() {
console.log('Initializing evaluation settings...');
+ // Initialize the global models object
+ window.evaluationModels = window.evaluationModels || {};
+
// Get DOM elements
evaluationProviderSelect = document.getElementById('evaluation_provider');
evaluationModelInput = document.getElementById('evaluation_model');
@@ -2123,17 +2180,17 @@ function initializeEvaluationSettings() {
temperature: !!evaluationTemperatureInput
});
+ // Populate evaluation provider dropdown
+ populateEvaluationProviders();
+
// Setup evaluation model dropdown using existing custom dropdown
setupEvaluationModelDropdown();
// Setup event handlers
setupEvaluationEventHandlers();
- // Load models from API (reuse research page data if available)
- const cachedModels = getCachedData('deepResearch.availableModels');
- if (!cachedModels) {
- loadEvaluationModelsFromAPI();
- }
+ // Load models from API - this will populate window.evaluationModels
+ loadEvaluationModelsFromAPI();
// Load settings with a small delay to ensure DOM is ready
setTimeout(() => {
@@ -2141,6 +2198,45 @@ function initializeEvaluationSettings() {
}, 100);
}
+function populateEvaluationProviders() {
+ if (!evaluationProviderSelect) return;
+
+ // Clear existing options
+ evaluationProviderSelect.innerHTML = '';
+
+ // Provider options (same as research page)
+ const 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)' }
+ ];
+
+ // Add options
+ providers.forEach(provider => {
+ const option = document.createElement('option');
+ option.value = provider.value;
+ option.textContent = provider.label;
+ evaluationProviderSelect.appendChild(option);
+ });
+
+ // Set initial value from data attribute
+ const initialProvider = evaluationProviderSelect.getAttribute('data-initial-value') || 'openai_endpoint';
+ console.log('Setting initial evaluation provider to:', initialProvider);
+ evaluationProviderSelect.value = initialProvider;
+
+ // Show/hide endpoint field based on initial provider
+ if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
+ evaluationEndpointInput.parentNode.style.display =
+ initialProvider === 'openai_endpoint' ? 'block' : 'none';
+ }
+
+ console.log('Populated evaluation providers with initial value:', initialProvider);
+}
+
function setupEvaluationModelDropdown() {
if (!evaluationModelInput) return;
@@ -2149,10 +2245,22 @@ function setupEvaluationModelDropdown() {
// Setup custom dropdown using the existing component
if (window.setupCustomDropdown) {
- window.setupCustomDropdown(
+ window.evaluationDropdownInstance = window.setupCustomDropdown(
evaluationModelInput,
dropdownList,
- getEvaluationModelOptions, // Function to get current options
+ function() {
+ // Get models dynamically based on current provider
+ const provider = evaluationProviderSelect ? evaluationProviderSelect.value : 'openai_endpoint';
+
+ // Use loaded models if available
+ if (window.evaluationModels && window.evaluationModels[provider]) {
+ console.log(`Returning ${window.evaluationModels[provider].length} loaded models for ${provider}`);
+ return window.evaluationModels[provider];
+ }
+
+ // Otherwise return defaults
+ return getEvaluationModelOptions();
+ },
function(value, item) {
// On selection callback
const hiddenInput = document.getElementById('evaluation_model_hidden');
@@ -2169,173 +2277,244 @@ function setupEvaluationModelDropdown() {
// Setup refresh button
const refreshBtn = document.querySelector('[data-target="evaluation-model-dropdown"] .refresh-btn');
if (refreshBtn) {
- refreshBtn.addEventListener('click', function() {
+ refreshBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ console.log('Refresh button clicked, force reloading models...');
+
+ // Show loading state
+ const icon = this.querySelector('i');
+ if (icon) {
+ icon.classList.add('fa-spin');
+ }
+
// Force reload models from API
- loadEvaluationModelsFromAPI();
+ window.modelsLoading = false; // Reset the flag
+
+ fetch('/settings/api/available-models?force_refresh=true')
+ .then(response => response.json())
+ .then(data => {
+ console.log('Force refresh received model data:', data);
+
+ if (data && data.providers) {
+ // Store the formatted models
+ window.evaluationModels = {};
+
+ // Process each provider's models
+ Object.entries(data.providers).forEach(([providerKey, models]) => {
+ if (Array.isArray(models)) {
+ // Map provider keys to expected provider names
+ let providerName = providerKey.replace('_models', '').toLowerCase();
+
+ // Special handling for openai_endpoint
+ if (providerName === 'openai_endpoint') {
+ providerName = 'openai_endpoint';
+ }
+
+ window.evaluationModels[providerName] = models.map(model => ({
+ value: model.value || model.id,
+ label: model.label || model.name || model.value
+ }));
+ console.log(`Loaded ${models.length} models for ${providerName}`);
+ }
+ });
+
+ // Update dropdown with new data
+ refreshEvaluationModels();
+ }
+ })
+ .catch(error => {
+ console.error('Error loading evaluation models:', error);
+ })
+ .finally(() => {
+ // Remove loading state
+ if (icon) {
+ icon.classList.remove('fa-spin');
+ }
+ window.modelsLoading = false;
+ });
});
}
}
function getEvaluationModelOptions() {
- // Get cached models from the research page's model loading system
- const cachedModels = getCachedData('deepResearch.availableModels');
- if (!cachedModels || !Array.isArray(cachedModels)) {
- console.log('No cached model data, loading...');
+ const provider = evaluationProviderSelect ? evaluationProviderSelect.value : 'openai_endpoint';
+ console.log('Getting evaluation model options for provider:', provider);
+
+ // Check if we have loaded models
+ if (window.evaluationModels && window.evaluationModels[provider] && window.evaluationModels[provider].length > 0) {
+ console.log(`Returning ${window.evaluationModels[provider].length} cached models for ${provider}`);
+ return window.evaluationModels[provider];
+ }
+
+ // Load models from API if not already loading
+ if (!window.modelsLoading) {
+ window.modelsLoading = true;
loadEvaluationModelsFromAPI();
- // Return fallback while loading
+ }
+
+ // Return minimal defaults while loading
+ console.log(`No models loaded yet for ${provider}, returning defaults`);
+ if (provider === 'openai_endpoint') {
+ return [
+ { value: 'anthropic/claude-3.5-sonnet', label: 'Claude 3.5 Sonnet' },
+ { value: 'openai/gpt-4o', label: 'GPT-4o' },
+ { value: '01-ai/yi-large', label: 'Yi Large' }
+ ];
+ } else if (provider === 'openai') {
return [
- { value: 'anthropic/claude-3.7-sonnet', label: 'Claude 3.7 Sonnet (Loading...)' }
+ { value: 'gpt-4o', label: 'GPT-4o' },
+ { value: 'gpt-4', label: 'GPT-4' },
+ { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' }
];
+ } else if (provider === 'anthropic') {
+ return [
+ { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet' },
+ { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' }
+ ];
+ } else {
+ // Return empty array for other providers
+ return [];
}
+}
- // Filter models by current provider (same logic as research page)
- const provider = evaluationProviderSelect ? evaluationProviderSelect.value : 'openai_endpoint';
- const providerUpper = provider.toUpperCase();
-
- let filteredModels = [];
-
- if (providerUpper === 'OPENAI_ENDPOINT') {
- filteredModels = cachedModels.filter(model => {
- const modelProvider = (model.provider || '').toUpperCase();
- return modelProvider === 'OPENAI_ENDPOINT';
- });
-
- if (filteredModels.length === 0) {
- // Fallback models for OpenRouter
- filteredModels = [
- { id: 'anthropic/claude-3.7-sonnet', name: 'Claude 3.7 Sonnet (OpenRouter)', provider: 'OPENAI_ENDPOINT' },
- { id: 'openai/gpt-4o', name: 'GPT-4o (OpenRouter)', provider: 'OPENAI_ENDPOINT' }
- ];
- }
- } else if (providerUpper === 'ANTHROPIC') {
- filteredModels = cachedModels.filter(model => {
- const modelProvider = (model.provider || '').toUpperCase();
- const modelName = (model.name || '').toLowerCase();
- const modelId = (model.id || '').toLowerCase();
-
- return modelProvider === 'ANTHROPIC' ||
- modelName.includes('claude') ||
- modelId.includes('claude');
- });
+// Debounce function to prevent too many API calls
+function debounce(func, wait) {
+ let timeout;
+ return function executedFunction(...args) {
+ const later = () => {
+ clearTimeout(timeout);
+ func(...args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ };
+}
- if (filteredModels.length === 0) {
- filteredModels = [
- { id: 'claude-3-5-sonnet-latest', name: 'Claude 3.5 Sonnet (Anthropic)', provider: 'ANTHROPIC' }
- ];
- }
- } else if (providerUpper === 'OPENAI') {
- filteredModels = cachedModels.filter(model => {
- const modelProvider = (model.provider || '').toUpperCase();
- const modelName = (model.name || '').toLowerCase();
- const modelId = (model.id || '').toLowerCase();
-
- return modelProvider === 'OPENAI' ||
- modelName.includes('gpt') ||
- modelId.includes('gpt');
- });
+// Debounced version of loadEvaluationModelsFromAPI
+const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false) {
+ console.log('Loading evaluation models from API...', forceRefresh ? '(force refresh)' : '');
- if (filteredModels.length === 0) {
- filteredModels = [
- { id: 'gpt-4o', name: 'GPT-4o (OpenAI)', provider: 'OPENAI' }
- ];
- }
- } else {
- // Generic filtering
- filteredModels = cachedModels.filter(model => {
- const modelProvider = (model.provider || '').toUpperCase();
- return modelProvider === providerUpper;
- });
+ // Prevent multiple simultaneous loads
+ if (window.modelsLoading && !forceRefresh) {
+ console.log('Models already loading, skipping...');
+ return;
}
- // Format for dropdown
- return filteredModels.map(model => ({
- value: model.id || model.value || '',
- label: model.name || model.label || model.id || 'Unknown model'
- }));
-}
+ window.modelsLoading = true;
+
+ // Use the correct API endpoint with optional force_refresh parameter
+ const url = forceRefresh ? '/settings/api/available-models?force_refresh=true' : '/settings/api/available-models';
-function loadEvaluationModelsFromAPI() {
- // Use the same API endpoint as research page
- fetch('/research/settings/api/available-models')
+ fetch(url)
.then(response => response.json())
.then(data => {
+ console.log('Received model data:', data);
+
if (data && data.providers) {
- // Format and cache the data (same as research page)
- const formattedModels = [];
-
- data.providers.forEach(provider => {
- if (provider.models && Array.isArray(provider.models)) {
- provider.models.forEach(model => {
- formattedModels.push({
- id: model.id || model.value,
- name: model.label || model.name || model.id,
- provider: provider.name?.toUpperCase() || 'UNKNOWN',
- value: model.id || model.value
- });
- });
+ // Store the formatted models in a temporary variable
+ window.evaluationModels = {};
+
+ // Process each provider's models
+ Object.entries(data.providers).forEach(([providerKey, models]) => {
+ if (Array.isArray(models)) {
+ // Map provider keys to expected provider names
+ let providerName = providerKey.replace('_models', '').toLowerCase();
+
+ // Special handling for openai_endpoint
+ if (providerName === 'openai_endpoint') {
+ providerName = 'openai_endpoint';
+ }
+
+ window.evaluationModels[providerName] = models.map(model => ({
+ value: model.value || model.id,
+ label: model.label || model.name || model.value
+ }));
+ console.log(`Loaded ${models.length} models for ${providerName}`);
}
});
- // Cache the data (same keys as research page)
- cacheData('deepResearch.availableModels', formattedModels);
- cacheData('deepResearch.cacheTimestamp', Date.now());
-
// Update dropdown with new data
refreshEvaluationModels();
}
})
.catch(error => {
console.error('Error loading evaluation models:', error);
+ })
+ .finally(() => {
+ window.modelsLoading = false;
});
+}, 500); // Wait 500ms before making the API call
+
+function filterModelsForProvider(models, provider) {
+ const providerUpper = provider.toUpperCase();
+
+ let filtered = models.filter(model => {
+ const modelProvider = (model.provider || '').toUpperCase();
+ // Handle provider name variations
+ if (providerUpper === 'OPENAI_ENDPOINT' && modelProvider === 'OPENAI_ENDPOINT') return true;
+ if (providerUpper === 'OPENAI' && modelProvider === 'OPENAI') return true;
+ if (providerUpper === 'ANTHROPIC' && modelProvider === 'ANTHROPIC') return true;
+ if (providerUpper === 'OLLAMA' && modelProvider === 'OLLAMA') return true;
+ return modelProvider === providerUpper;
+ });
+
+ // If no models found for provider, return some defaults
+ if (filtered.length === 0) {
+ if (providerUpper === 'OPENAI_ENDPOINT') {
+ return [
+ { value: '01-ai/yi-large', label: 'Yi Large' },
+ { value: 'anthropic/claude-3.5-sonnet', label: 'Claude 3.5 Sonnet' },
+ { value: 'openai/gpt-4o', label: 'GPT-4o' }
+ ];
+ } else if (providerUpper === 'OPENAI') {
+ return [
+ { value: 'gpt-4o', label: 'GPT-4o' },
+ { value: 'gpt-4', label: 'GPT-4' },
+ { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' }
+ ];
+ } else if (providerUpper === 'ANTHROPIC') {
+ return [
+ { value: 'claude-3-5-sonnet-latest', label: 'Claude 3.5 Sonnet' },
+ { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' }
+ ];
+ }
+ }
+
+ return filtered.map(model => ({
+ value: model.value || model.id,
+ label: model.label || model.name || model.value
+ }));
}
function refreshEvaluationModels() {
+ const provider = evaluationProviderSelect ? evaluationProviderSelect.value : 'openai_endpoint';
+ const options = window.evaluationModels && window.evaluationModels[provider] ?
+ window.evaluationModels[provider] : [];
+
+ console.log(`Refreshing evaluation dropdown with ${options.length} options for provider ${provider}`);
+
+ // If we have the updateDropdownOptions function and the input
if (window.updateDropdownOptions && evaluationModelInput) {
- const options = getEvaluationModelOptions();
+ // Update the dropdown with the actual loaded models
window.updateDropdownOptions(evaluationModelInput, options);
}
-}
-// Cache helper functions (same as research page)
-function getCachedData(key) {
- try {
- const data = localStorage.getItem(key);
- return data ? JSON.parse(data) : null;
- } catch (error) {
- console.error('Error reading from cache:', error);
- return null;
+ // Force a click event to show the dropdown with new options
+ if (evaluationModelInput && options.length > 0) {
+ // Trigger a click to show the dropdown with updated options
+ setTimeout(() => {
+ evaluationModelInput.click();
+ }, 100);
}
}
-function cacheData(key, data) {
- try {
- localStorage.setItem(key, JSON.stringify(data));
- } catch (error) {
- console.error('Error writing to cache:', error);
- }
-}
function setupEvaluationEventHandlers() {
// Provider change handler
if (evaluationProviderSelect) {
- // Populate providers first
- const providers = [
- { value: 'openai_endpoint', label: 'OpenRouter (Recommended)' },
- { value: 'openai', label: 'OpenAI API' },
- { value: 'anthropic', label: 'Anthropic API' },
- { value: 'ollama', label: 'Ollama (Local)' }
- ];
-
- evaluationProviderSelect.innerHTML = '';
- providers.forEach(provider => {
- const option = document.createElement('option');
- option.value = provider.value;
- option.textContent = provider.label;
- evaluationProviderSelect.appendChild(option);
- });
-
evaluationProviderSelect.addEventListener('change', function() {
const provider = this.value;
+ console.log('Evaluation provider changed to:', provider);
// Show/hide endpoint URL field
if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
@@ -2382,80 +2561,83 @@ function loadEvaluationSettings() {
temperature: !!evaluationTemperatureInput
});
- fetch('/research/settings/api', {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json'
+ // Use the same evalProviderData, evalModelData, etc. that were already loaded
+ if (!evalProviderData || !evalModelData || !evalEndpointData || !evalTempData) {
+ console.log('Evaluation settings not loaded yet, skipping...');
+ return;
+ }
+
+ // Set provider
+ if (evaluationProviderSelect && evalProviderData && evalProviderData.settings) {
+ const providerValue = evalProviderData.settings.value || 'openai_endpoint';
+ console.log('Setting evaluation provider to:', providerValue);
+ evaluationProviderSelect.value = providerValue;
+
+ // Show/hide endpoint field
+ if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
+ evaluationEndpointInput.parentNode.style.display =
+ providerValue === 'openai_endpoint' ? 'block' : 'none';
}
- })
- .then(response => response.json())
- .then(data => {
- console.log('Evaluation settings API response:', data);
+ }
- if (data && data.settings) {
- // Set provider
- const providerSetting = data.settings["benchmark.evaluation.provider"];
- console.log('Provider setting:', providerSetting);
-
- if (evaluationProviderSelect) {
- const providerValue = providerSetting?.value || 'openai_endpoint';
- console.log('Setting provider to:', providerValue, 'on element:', evaluationProviderSelect);
- evaluationProviderSelect.value = providerValue;
- console.log('Provider value after setting:', evaluationProviderSelect.value);
-
- // Show/hide endpoint field
- if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
- evaluationEndpointInput.parentNode.style.display =
- providerValue === 'openai_endpoint' ? 'block' : 'none';
- console.log('Endpoint field visibility:', evaluationEndpointInput.parentNode.style.display);
- }
- } else {
- console.warn('evaluationProviderSelect is null');
- }
+ // Set model
+ if (evaluationModelInput && evalModelData && evalModelData.settings) {
+ const modelValue = evalModelData.settings.value || 'anthropic/claude-3.7-sonnet';
+ console.log('Setting evaluation model to:', modelValue);
- // Set model
- const modelSetting = data.settings["benchmark.evaluation.model"];
- console.log('Model setting:', modelSetting);
+ // Wait for models to be loaded, then set the value
+ const setModelValue = () => {
+ const provider = evaluationProviderSelect ? evaluationProviderSelect.value : 'openai_endpoint';
+ const models = window.evaluationModels && window.evaluationModels[provider] ?
+ window.evaluationModels[provider] : [];
- if (evaluationModelInput) {
- const modelValue = modelSetting?.value || 'anthropic/claude-3.7-sonnet';
- console.log('Setting model to:', modelValue, 'on element:', evaluationModelInput);
- evaluationModelInput.value = modelValue;
- console.log('Model value after setting:', evaluationModelInput.value);
+ // Find the matching model to get the label
+ const matchingModel = models.find(m => m.value === modelValue);
+
+ if (matchingModel) {
+ // Set the display value to the label
+ evaluationModelInput.value = matchingModel.label;
+ console.log('Found matching model, setting label:', matchingModel.label);
} else {
- console.warn('evaluationModelInput is null');
+ // If no match, just set the raw value
+ evaluationModelInput.value = modelValue;
+ console.log('No matching model found, setting raw value:', modelValue);
}
- // Set endpoint URL
- const endpointSetting = data.settings["benchmark.evaluation.endpoint_url"];
- if (evaluationEndpointInput) {
- const endpointValue = endpointSetting?.value || 'https://openrouter.ai/api/v1';
- console.log('Setting endpoint to:', endpointValue, 'on element:', evaluationEndpointInput);
- evaluationEndpointInput.value = endpointValue;
- console.log('Endpoint value after setting:', evaluationEndpointInput.value);
- } else {
- console.warn('evaluationEndpointInput is null');
+ // Update hidden input
+ const hiddenInput = document.getElementById('evaluation_model_hidden');
+ if (hiddenInput) {
+ hiddenInput.value = modelValue;
}
- // Set temperature
- const temperatureSetting = data.settings["benchmark.evaluation.temperature"];
- if (evaluationTemperatureInput) {
- const tempValue = temperatureSetting?.value || 0;
- console.log('Setting temperature to:', tempValue, 'on element:', evaluationTemperatureInput);
- evaluationTemperatureInput.value = tempValue;
- console.log('Temperature value after setting:', evaluationTemperatureInput.value);
- } else {
- console.warn('evaluationTemperatureInput is null');
+ // Use the dropdown instance's setValue method if available
+ if (window.evaluationDropdownInstance && window.evaluationDropdownInstance.setValue) {
+ window.evaluationDropdownInstance.setValue(modelValue, false);
}
+ };
+
+ // If models are already loaded, set immediately
+ if (window.evaluationModels && Object.keys(window.evaluationModels).length > 0) {
+ setModelValue();
} else {
- console.log('No settings found in response, using defaults');
- setEvaluationDefaults();
+ // Otherwise wait for models to load
+ setTimeout(setModelValue, 1000);
}
- })
- .catch(error => {
- console.error('Error loading evaluation settings:', error);
- setEvaluationDefaults();
- });
+ }
+
+ // Set endpoint URL
+ if (evaluationEndpointInput && evalEndpointData && evalEndpointData.settings) {
+ const endpointValue = evalEndpointData.settings.value || 'https://openrouter.ai/api/v1';
+ console.log('Setting evaluation endpoint to:', endpointValue);
+ evaluationEndpointInput.value = endpointValue;
+ }
+
+ // Set temperature
+ if (evaluationTemperatureInput && evalTempData && evalTempData.settings) {
+ const tempValue = evalTempData.settings.value || 0;
+ console.log('Setting evaluation temperature to:', tempValue);
+ evaluationTemperatureInput.value = tempValue;
+ }
}
function setEvaluationDefaults() {
@@ -2473,18 +2655,24 @@ function setEvaluationDefaults() {
}
function saveEvaluationSetting(key, value) {
- fetch('/research/settings/api', {
- method: 'POST',
+ console.log('Saving evaluation setting:', key, '=', value);
+
+ // Get CSRF token
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+
+ fetch(`/settings/api/${key}`, {
+ method: 'PUT',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
},
- body: JSON.stringify({
- [key]: value
- })
+ body: JSON.stringify({ value: value })
})
.then(response => response.json())
.then(data => {
- if (!data.success) {
+ if (data.success) {
+ console.log('Successfully saved evaluation setting:', key);
+ } else {
console.error('Failed to save evaluation setting:', data.error);
}
})
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 495348f10d..7e2972136b 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -81,7 +81,7 @@
<!-- Model Provider Selection -->
<div class="form-group half">
<label for="model_provider">Model Provider</label>
- <select id="model_provider" name="model_provider" class="form-control">
+ <select id="model_provider" name="model_provider" class="form-control" data-initial-value="{{ settings.llm_provider }}">
<!-- Will be populated dynamically -->
<option value="">Loading providers...</option>
</select>
@@ -91,7 +91,7 @@
<!-- 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">
+ <input type="text" id="custom_endpoint" name="custom_endpoint" class="form-control" placeholder="https://your-endpoint-url/v1" value="{{ settings.llm_openai_endpoint_url }}">
<span class="input-help">Enter the OpenAI-compatible API endpoint URL</span>
</div>
</div>
@@ -106,7 +106,8 @@
label="Language Model",
help_text="Select or enter a custom model name",
show_refresh=True,
- refresh_aria_label="Refresh model list"
+ refresh_aria_label="Refresh model list",
+ data_initial_value=settings.llm_model
) }}
</div>
@@ -119,7 +120,8 @@
label="Search Engine",
help_text="Select the search engine to use for research",
show_refresh=True,
- refresh_aria_label="Refresh search engine list"
+ refresh_aria_label="Refresh search engine list",
+ data_initial_value=settings.search_tool
) }}
</div>
</div>