~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Add SearXNG optimization warning for high iteration counts
LearningCircuit5a9ae0c50352
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex b0b0f77b0c..3eaa5b9966 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -242,16 +242,37 @@ def get_llm("temperature": temperature,}- # Get context window size from settings- context_window_size = get_db_setting("llm.context_window_size", 32000)+ # Get context window size from settings (use different defaults for local vs cloud providers)+ def get_context_window_size(provider_type):+ if provider_type in ["ollama", "llamacpp", "lmstudio"]:+ # Local providers: use smaller default to prevent memory issues+ return get_db_setting("llm.local_context_window_size", 4096)+ else:+ # Cloud providers: check if unrestricted mode is enabled+ use_unrestricted = get_db_setting(+ "llm.context_window_unrestricted", True+ )+ if use_unrestricted:+ # Let cloud providers auto-handle context (return None or very large value)+ return None # Will be handled per provider+ else:+ # Use user-specified limit+ return get_db_setting("llm.context_window_size", 128000)++ context_window_size = get_context_window_size(provider)if get_db_setting("llm.supports_max_tokens", True):# Use 80% of context window to leave room for prompts- max_tokens = min(- int(get_db_setting("llm.max_tokens", 30000)),- int(context_window_size * 0.8),- )- common_params["max_tokens"] = max_tokens+ if context_window_size is not None:+ max_tokens = min(+ int(get_db_setting("llm.max_tokens", 30000)),+ int(context_window_size * 0.8),+ )+ common_params["max_tokens"] = max_tokens+ else:+ # Unrestricted context: use provider's default max_tokens+ max_tokens = int(get_db_setting("llm.max_tokens", 30000))+ common_params["max_tokens"] = max_tokens# Handle different providersif provider == "anthropic":@@ -394,8 +415,12 @@ def get_llm(f"Creating ChatOllama with model={model_name}, base_url={base_url}")try:+ # Add num_ctx parameter for Ollama context window size+ ollama_params = {**common_params}+ if context_window_size is not None:+ ollama_params["num_ctx"] = context_window_sizellm = ChatOllama(- model=model_name, base_url=base_url, **common_params+ model=model_name, base_url=base_url, **ollama_params)# Log the actual client configuration after creation@@ -498,7 +523,7 @@ def get_llm(n_gpu_layers=n_gpu_layers,n_batch=n_batch,f16_kv=f16_kv,- n_ctx=context_window_size, # Set context window size directly+ n_ctx=context_window_size, # Set context window size directly (None = use default)verbose=True,)diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex ec32e813b8..0ed130b50d 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -194,13 +194,27 @@"value": 30000,"visible": true},+ "llm.context_window_unrestricted": {+ "category": "llm_parameters",+ "description": "Let cloud providers automatically handle context sizing (recommended). Uncheck to set a specific limit.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Use Unrestricted Cloud Context Window",+ "options": null,+ "step": null,+ "type": "LLM",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },"llm.context_window_size": {"category": "llm_parameters",- "description": "Maximum context window size in tokens for the LLM",+ "description": "Maximum context window size in tokens for cloud LLMs. Only used when unrestricted context is disabled.","editable": true,"max_value": 20000000.0,"min_value": 512.0,- "name": "Context Window Size",+ "name": "Cloud Provider Context Window Limit","options": null,"step": null,"type": "LLM",@@ -208,6 +222,20 @@"value": 128000,"visible": true},+ "llm.local_context_window_size": {+ "category": "llm_parameters",+ "description": "Context window size in tokens for local LLMs (Ollama, LlamaCpp). Smaller values prevent memory issues.",+ "editable": true,+ "max_value": 131072.0,+ "min_value": 512.0,+ "name": "Local Provider Context Window Size",+ "options": null,+ "step": 512.0,+ "type": "LLM",+ "ui_element": "number",+ "value": 4096,+ "visible": true+ },"llm.supports_max_tokens": {"category": "llm_parameters","description": "Whether the LLM API supports the 'max_tokens' option.",@@ -4129,5 +4157,61 @@"ui_element": "text","value": "http://localhost:8000","visible": true+ },+ "app.warnings.dismiss_high_context": {+ "category": "warnings",+ "description": "Dismiss warnings about high context window sizes that may cause memory issues",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss High Context Warnings",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "app.warnings.dismiss_low_context_focused": {+ "category": "warnings",+ "description": "Dismiss warnings about using focused iteration with low context window sizes",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss Low Context + Focused Strategy Warnings",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "app.warnings.dismiss_model_mismatch": {+ "category": "warnings",+ "description": "Dismiss warnings about context size vs model size mismatches",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss Model Mismatch Warnings",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "app.warnings.dismiss_searxng_recommendation": {+ "category": "warnings",+ "description": "Dismiss recommendations about using more questions instead of iterations with SearXNG",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Dismiss SearXNG Optimization Tips",+ "options": null,+ "step": null,+ "type": "APP",+ "ui_element": "checkbox",+ "value": false,+ "visible": true}}diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 2a22364a90..c692407eed 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -33,6 +33,96 @@ from ..utils.templates import render_template_with_defaultssettings_bp = Blueprint("settings", __name__, url_prefix="/research/settings")+def calculate_warnings():+ """Calculate current warning conditions based on settings"""+ warnings = []++ try:+ # Get database session if in Flask context+ db_session = None+ try:+ from flask import current_app++ if hasattr(current_app, "db_session"):+ db_session = current_app.db_session+ except:+ pass++ # Get current settings+ provider = get_setting("llm.provider", "ollama", db_session).lower()+ local_context = get_setting(+ "llm.local_context_window_size", 4096, db_session+ )++ logger.info(f"Starting warning calculation - provider={provider}")++ # Get dismissal settings+ dismiss_high_context = get_setting(+ "app.warnings.dismiss_high_context", False, db_session+ )++ # Check warning conditions+ is_local_provider = provider in [+ "ollama",+ "llamacpp",+ "lmstudio",+ "vllm",+ ]++ # High context warning for local providers+ if (+ is_local_provider+ and local_context > 8192+ and not dismiss_high_context+ ):+ warnings.append(+ {+ "type": "high_context",+ "icon": "⚠️",+ "title": "High Context Warning",+ "message": f"Context size ({local_context:,} tokens) may cause memory issues with {provider}. Increase VRAM or reduce context size if you experience slowdowns.",+ "dismissKey": "app.warnings.dismiss_high_context",+ }+ )++ # SearXNG recommendation: more questions instead of more iterations+ search_engine = get_setting(+ "search.tool", "duckduckgo", db_session+ ).lower()+ iterations = int(get_setting("search.iterations", 2, db_session))+ questions_per_iteration = int(+ get_setting("search.questions_per_iteration", 3, db_session)+ )+ dismiss_searxng_recommendation = get_setting(+ "app.warnings.dismiss_searxng_recommendation", False, db_session+ )++ logger.info(+ f"SearXNG warning check: engine={search_engine}, iterations={iterations}, dismissed={dismiss_searxng_recommendation}"+ )++ if (+ search_engine == "searxng"+ and iterations > 2+ and not dismiss_searxng_recommendation+ ):+ logger.info("Adding SearXNG optimization warning")+ warnings.append(+ {+ "type": "searxng_recommendation",+ "icon": "💡",+ "title": "SearXNG Optimization Tip",+ "message": f"For SearXNG, we recommend using more questions per iteration ({questions_per_iteration} → 10) instead of more iterations ({iterations}). SearXNG handles multiple questions efficiently in a single iteration.",+ "dismissKey": "app.warnings.dismiss_searxng_recommendation",+ }+ )++ except Exception as e:+ logger.warning(f"Error calculating warnings: {e}")++ return warnings++def get_db_session() -> Session:"""Get the database session from the app context"""if hasattr(current_app, "db_session"):@@ -340,15 +430,37 @@ def save_all_settings():# Multiple settings or generic messagesuccess_message = f"Settings saved successfully ({len(updated_settings)} updated, {len(created_settings)} created)"- return jsonify(- {- "status": "success",- "message": success_message,- "updated": updated_settings,- "created": created_settings,- "settings": all_settings,- }- )+ # Check if any warning-affecting settings were changed and include warnings+ response_data = {+ "status": "success",+ "message": success_message,+ "updated": updated_settings,+ "created": created_settings,+ "settings": all_settings,+ }++ warning_affecting_keys = [+ "llm.provider",+ "search.tool",+ "search.iterations",+ "search.questions_per_iteration",+ "llm.local_context_window_size",+ "llm.context_window_unrestricted",+ "llm.context_window_size",+ ]++ # Check if any warning-affecting settings were changed+ if any(+ key in warning_affecting_keys+ for key in updated_settings + created_settings+ ):+ warnings = calculate_warnings()+ response_data["warnings"] = warnings+ logger.info(+ f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings"+ )++ return jsonify(response_data)except Exception:logger.exception("Error saving settings")@@ -511,9 +623,29 @@ def api_update_setting(key):# Update settingsuccess = set_setting(key, value)if success:- return jsonify(- {"message": f"Setting {key} updated successfully"}- )+ response_data = {+ "message": f"Setting {key} updated successfully"+ }++ # If this is a key that affects warnings, include warning calculations+ warning_affecting_keys = [+ "llm.provider",+ "search.tool",+ "search.iterations",+ "search.questions_per_iteration",+ "llm.local_context_window_size",+ "llm.context_window_unrestricted",+ "llm.context_window_size",+ ]++ if key in warning_affecting_keys:+ warnings = calculate_warnings()+ response_data["warnings"] = warnings+ logger.debug(+ f"Setting {key} changed to {value}, calculated {len(warnings)} warnings"+ )++ return jsonify(response_data)else:return jsonify({"error": f"Failed to update setting {key}"}diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.pyindex 2625576cff..23da45c37e 100644--- a/src/local_deep_research/web/services/settings_manager.py+++ b/src/local_deep_research/web/services/settings_manager.py@@ -229,6 +229,8 @@ class SettingsManager:if commit:self.db_session.commit()+ # Emit WebSocket event for settings change+ self._emit_settings_changed([key])return Trueexcept SQLAlchemyError as e:@@ -365,6 +367,8 @@ class SettingsManager:if commit:self.db_session.commit()+ # Emit WebSocket event for settings change+ self._emit_settings_changed([setting_obj.key])return db_setting@@ -522,6 +526,8 @@ class SettingsManager:if commit:self.db_session.commit()+ # Emit WebSocket event for all imported settings+ self._emit_settings_changed(list(settings_data.keys()))def _create_setting(self, key, value, setting_type):"""Create a setting with appropriate metadata"""@@ -578,3 +584,44 @@ class SettingsManager:# Create the setting in the databaseself.create_or_update_setting(setting_dict, commit=False)++ def _emit_settings_changed(self, changed_keys: list = None):+ """+ Emit WebSocket event when settings change++ Args:+ changed_keys: List of setting keys that changed+ """+ try:+ # Import here to avoid circular imports+ from .socket_service import SocketIOService++ socket_service = SocketIOService()++ # Get the changed settings+ settings_data = {}+ if changed_keys:+ for key in changed_keys:+ setting_value = self.get_setting(key)+ if setting_value is not None:+ settings_data[key] = {"value": setting_value}++ # Emit the settings change event+ from datetime import datetime++ socket_service.emit_socket_event(+ "settings_changed",+ {+ "changed_keys": changed_keys or [],+ "settings": settings_data,+ "timestamp": datetime.utcnow().isoformat(),+ },+ )++ logger.debug(+ f"Emitted settings_changed event for keys: {changed_keys}"+ )++ except Exception as e:+ logger.warning(f"Failed to emit settings change event: {e}")+ # Don't let WebSocket emission failures break settings savingdiff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.pyindex 9853e75ce5..d54c47e524 100644--- a/src/local_deep_research/web/services/settings_service.py+++ b/src/local_deep_research/web/services/settings_service.py@@ -112,6 +112,8 @@ def bulk_update_settings(if commit and success and manager.db_session:try:manager.db_session.commit()+ # Emit WebSocket event for all changed settings+ manager._emit_settings_changed(list(settings_dict.keys()))except Exception:logger.exception("Error committing bulk settings update")manager.db_session.rollback()diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex eb9a677e33..74909c0553 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -575,6 +575,33 @@});}+ // Search engine change - save to settings manager+ if (searchEngineInput) {+ searchEngineInput.addEventListener('change', function() {+ const searchEngine = this.value;+ console.log('Search engine changed to:', searchEngine);+ saveSearchSetting('search.tool', searchEngine);+ });+ }++ // Iterations change - save to settings manager+ if (iterationsInput) {+ iterationsInput.addEventListener('change', function() {+ const iterations = parseInt(this.value);+ console.log('Iterations changed to:', iterations);+ saveSearchSetting('search.iterations', iterations);+ });+ }++ // Questions per iteration change - save to settings manager+ if (questionsPerIterationInput) {+ questionsPerIterationInput.addEventListener('change', function() {+ const questions = parseInt(this.value);+ console.log('Questions per iteration changed to:', questions);+ saveSearchSetting('search.questions_per_iteration', questions);+ });+ }+// Load options data from APIsPromise.all([loadModelOptions(false),@@ -1817,6 +1844,14 @@.then(data => {console.log('Provider setting saved to database:', data);+ // If the response includes warnings, display them directly+ if (data.warnings && typeof window.displayWarnings === 'function') {+ window.displayWarnings(data.warnings);+ } else if (typeof window.refetchSettingsAndUpdateWarnings === 'function') {+ // Fallback: trigger warning system update+ window.refetchSettingsAndUpdateWarnings();+ }+// Optionally show a notificationif (window.ui && window.ui.showMessage) {window.ui.showMessage(`Provider updated to: ${providerValue}`, 'success', 2000);@@ -1832,6 +1867,41 @@});}+ // Save search setting to database+ function saveSearchSetting(settingKey, value) {+ // Save to the database using the settings API+ fetch(`/research/settings/api/${settingKey}`, {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').getAttribute('content')+ },+ body: JSON.stringify({ value: value })+ })+ .then(response => response.json())+ .then(data => {+ console.log(`Search setting ${settingKey} saved to database:`, data);++ // If the response includes warnings, display them directly+ if (data.warnings && typeof window.displayWarnings === 'function') {+ window.displayWarnings(data.warnings);+ }++ // Optionally show a notification+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(`${settingKey.split('.').pop()} updated to: ${value}`, 'success', 2000);+ }+ })+ .catch(error => {+ console.error(`Error saving search setting ${settingKey} to database:`, error);++ // Show error notification if available+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(`Error updating ${settingKey}: ${error.message}`, 'error', 3000);+ }+ });+ }+// Research form submission handlerfunction handleResearchSubmit(event) {event.preventDefault();diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 45a58fda7f..1ea59b43a7 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -1054,6 +1054,7 @@if (category === 'report_parameters') return 'Report Parameters';if (category === 'search_general') return 'Search General';if (category === 'search_parameters') return 'Search Parameters';+ if (category === 'warnings') return 'Warnings';// Remove any underscores and capitalize each wordlet formattedCategory = category.replace(/_/g, ' ');@@ -1128,13 +1129,14 @@'enable_web','dark_mode','default_theme',- 'theme'+ 'theme',+ 'warnings']};// Priority settings that should appear at the top of each tabconst prioritySettings = {- 'app': ['enable_web', 'enable_notifications', 'web_interface', 'theme', 'default_theme', 'dark_mode', 'debug', 'host', 'port'],+ 'app': ['enable_web', 'enable_notifications', 'web_interface', 'theme', 'default_theme', 'dark_mode', 'debug', 'host', 'port', 'warnings'],'llm': ['provider', 'model', 'temperature', 'max_tokens', 'api_key', 'openai_endpoint_url', 'lmstudio_url', 'llamacpp_model_path'],'search': ['tool', 'iterations', 'questions_per_iteration', 'max_results', 'region', 'search_engine'],'report': ['enable_fact_checking', 'knowledge_accumulation', 'output_dir', 'detailed_citations']diff --git a/src/local_deep_research/web/static/js/components/settings_sync.js b/src/local_deep_research/web/static/js/components/settings_sync.jsindex aa37a8a2b0..b1c8e3428c 100644--- a/src/local_deep_research/web/static/js/components/settings_sync.js+++ b/src/local_deep_research/web/static/js/components/settings_sync.js@@ -1,45 +1,46 @@-// Function to save settings using the settings page endpoint+// Function to save settings using the individual settings manager APIfunction saveMenuSettings(settingKey, settingValue) {- // Create payload with the single setting being changed- const payload = {};- payload[settingKey] = settingValue;-console.log('Saving setting:', settingKey, '=', settingValue);// Get CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');- // Use fetch to send to the same endpoint as the settings page- fetch('/research/settings/save_all_settings', {- method: 'POST',+ // Use the individual settings API endpoint that uses the settings manager+ fetch(`/research/settings/api/${settingKey}`, {+ method: 'PUT',headers: {'Content-Type': 'application/json','X-CSRFToken': csrfToken},- body: JSON.stringify(payload)+ body: JSON.stringify({ value: settingValue })}).then(response => response.json()).then(data => {- if (data.status === 'success') {- // Show success notification if UI module is available- if (window.ui && window.ui.showMessage) {- window.ui.showMessage('Setting saved successfully', 'success');- } else {- console.log('Setting saved successfully:', data);+ console.log(`Setting ${settingKey} saved via settings manager:`, data);++ // If the response includes warnings, display them directly+ if (data.warnings && typeof window.displayWarnings === 'function') {+ window.displayWarnings(data.warnings);+ }++ // Also trigger client-side warning recalculation for search settings+ if (settingKey.startsWith('search.') || settingKey === 'llm.provider') {+ if (typeof window.refetchSettingsAndUpdateWarnings === 'function') {+ window.refetchSettingsAndUpdateWarnings();}+ }++ // Show success notification if UI module is available+ if (window.ui && window.ui.showMessage) {+ window.ui.showMessage(`${settingKey.split('.').pop()} updated successfully`, 'success');} else {- // Show error notification- if (window.ui && window.ui.showMessage) {- window.ui.showMessage('Failed to save setting: ' + (data.message || 'Unknown error'), 'error');- } else {- console.error('Failed to save setting:', data);- }+ console.log('Setting saved successfully:', data);}}).catch(error => {- console.error('Error saving setting:', error);+ console.error(`Error saving setting ${settingKey}:`, error);if (window.ui && window.ui.showMessage) {- window.ui.showMessage('Error saving setting', 'error');+ window.ui.showMessage(`Error updating ${settingKey}: ${error.message}`, 'error');}});}diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.jsindex eb02545e30..680d24c923 100644--- a/src/local_deep_research/web/static/js/research_form.js+++ b/src/local_deep_research/web/static/js/research_form.js@@ -1,7 +1,10 @@/**- * Research form handling with settings management+ * Research form handling with settings management and warnings*/+// Global settings cache for warning logic+let globalSettings = {};+document.addEventListener('DOMContentLoaded', function() {// Initialize the research formconsole.log('DOM loaded, initializing research form');@@ -31,6 +34,9 @@ function initResearchForm() {// Find our specific settingsconst settings = data.settings;+ // Cache settings globally for warning logic+ globalSettings = settings;+// Look for the iterations settingfor (const key in settings) {const setting = settings[key];@@ -44,6 +50,9 @@ function initResearchForm() {questionsInput.value = setting.value;}}++ // Initialize warnings after settings are loaded+ initializeWarnings();}}).catch(error => {@@ -104,3 +113,328 @@ function saveResearchSettings() {console.warn('Error saving research settings:', error);});}++/**+ * Initialize warning system+ */+function initializeWarnings() {+ console.log('Initializing warning system...');++ // Check warnings on form load+ checkAndDisplayWarnings();++ // Monitor form changes for dynamic warnings+ setupWarningListeners();+}++/**+ * Setup event listeners for settings changes+ */+function setupWarningListeners() {+ // Monitor provider changes directly and refetch settings+ const providerSelect = document.getElementById('model_provider');+ if (providerSelect) {+ providerSelect.addEventListener('change', function() {+ console.log('Provider changed to:', providerSelect.value);+ // Wait a bit longer for the saveProviderSetting API call to complete+ setTimeout(refetchSettingsAndUpdateWarnings, 500);+ });+ }++ // Hook into the existing saveProviderSetting function if it exists+ // This will trigger when the research.js calls saveProviderSetting+ if (typeof window.saveProviderSetting === 'function') {+ const originalSaveProviderSetting = window.saveProviderSetting;+ window.saveProviderSetting = function(providerValue) {+ console.log('Intercepted saveProviderSetting call:', providerValue);+ // Call the original function+ const result = originalSaveProviderSetting.apply(this, arguments);+ // After it completes, refetch settings and update warnings+ setTimeout(refetchSettingsAndUpdateWarnings, 200);+ return result;+ };+ }++ const strategySelect = document.getElementById('strategy');+ if (strategySelect) {+ strategySelect.addEventListener('change', function() {+ console.log('Strategy changed to:', strategySelect.value);+ setTimeout(checkAndDisplayWarnings, 100);+ });+ }++ // Use Socket.IO to listen for settings changes if available (backup)+ if (typeof io !== 'undefined') {+ const socket = io();+ socket.on('settings_changed', function(data) {+ console.log('Settings changed via WebSocket:', data);+ // Update global settings cache+ if (data.settings) {+ Object.assign(globalSettings, data.settings);+ }+ // Recheck warnings with new settings+ setTimeout(checkAndDisplayWarnings, 100);+ });++ socket.on('connect', function() {+ console.log('Connected to settings WebSocket');+ });+ }+}++/**+ * Refetch settings from the server and update warnings+ */+function refetchSettingsAndUpdateWarnings() {+ console.log('Refetching settings from server...');++ fetch('/research/settings/api')+ .then(response => {+ if (!response.ok) {+ throw new Error('Failed to fetch settings');+ }+ return response.json();+ })+ .then(data => {+ console.log('Refetched settings:', data);+ if (data && data.status === 'success' && data.settings) {+ // Update global settings cache+ globalSettings = data.settings;+ // Recheck warnings with fresh settings+ setTimeout(checkAndDisplayWarnings, 100);+ }+ })+ .catch(error => {+ console.warn('Error refetching settings:', error);+ // Fallback to checking warnings with current settings+ setTimeout(checkAndDisplayWarnings, 100);+ });+}++// Make functions globally available for other scripts+window.refetchSettingsAndUpdateWarnings = refetchSettingsAndUpdateWarnings;+window.displayWarnings = displayWarnings;++/**+ * Check warning conditions and display warnings+ */+function checkAndDisplayWarnings() {+ console.log('Checking warning conditions...');++ // Get provider from database settings (source of truth)+ const provider = getSetting('llm.provider', 'ollama').toLowerCase();+ const strategy = getCurrentStrategy();+ const model = getCurrentModel();++ // Debug logging+ console.log('Current values:', { provider, strategy, model });++ // Get context settings+ const localContext = getSetting('llm.local_context_window_size', 4096);+ const cloudUnrestricted = getSetting('llm.context_window_unrestricted', true);+ const cloudContext = getSetting('llm.context_window_size', 128000);++ console.log('Context settings:', { localContext, cloudUnrestricted, cloudContext });++ // Get dismissal settings+ const dismissHighContext = getSetting('app.warnings.dismiss_high_context', false);+ const dismissLowContextFocused = getSetting('app.warnings.dismiss_low_context_focused', false);+ const dismissModelMismatch = getSetting('app.warnings.dismiss_model_mismatch', false);++ const warnings = [];++ // Check warning conditions+ const isLocalProvider = provider === 'ollama' || provider === 'llamacpp' || provider === 'lmstudio' || provider === 'vllm';++ console.log('Provider analysis:', {+ rawProvider: provider,+ isLocal: isLocalProvider,+ cloudUnrestricted,+ allSettings: Object.keys(globalSettings).filter(k => k.includes('context') || k.includes('warning'))+ });++ // Get effective context size based on provider type+ let effectiveContext;+ if (isLocalProvider) {+ effectiveContext = localContext;+ } else {+ // Cloud provider: check if unrestricted or has limit+ if (cloudUnrestricted) {+ effectiveContext = 200000; // Assume high context for unrestricted cloud+ } else {+ effectiveContext = cloudContext;+ }+ }++ console.log('Effective context for warnings:', effectiveContext, 'Provider type:', isLocalProvider ? 'local' : 'cloud');++ if (isLocalProvider && localContext > 8192 && !dismissHighContext) {+ warnings.push({+ type: 'high_context',+ icon: '⚠️',+ title: 'High Context Warning',+ message: `Context size (${localContext.toLocaleString()} tokens) may cause memory issues with ${provider}. Increase VRAM or reduce context size if you experience slowdowns.`,+ dismissKey: 'app.warnings.dismiss_high_context'+ });+ }++ if (strategy === 'focused-iteration' && effectiveContext < 32000 && !dismissLowContextFocused) {+ const providerType = isLocalProvider ? 'local' : 'cloud';+ const contextSource = isLocalProvider ? 'local context setting' : (cloudUnrestricted ? 'unrestricted cloud context' : 'cloud context setting');++ warnings.push({+ type: 'low_context_focused',+ icon: '💡',+ title: 'Strategy Recommendation',+ message: `Focused iteration works best with 32k+ context tokens. Current ${providerType} provider has ${effectiveContext.toLocaleString()} tokens (${contextSource}). Consider increasing context size or using source-based strategy.`,+ dismissKey: 'app.warnings.dismiss_low_context_focused'+ });+ }++ if (model && model.includes('70b') && isLocalProvider && localContext > 8192 && !dismissModelMismatch) {+ warnings.push({+ type: 'model_mismatch',+ icon: '🧠',+ title: 'Model & Context Warning',+ message: `Large model (${model}) with high context (${localContext.toLocaleString()}) may exceed VRAM. Consider reducing context size or upgrading GPU memory.`,+ dismissKey: 'app.warnings.dismiss_model_mismatch'+ });+ }++ // SearXNG recommendation: more questions instead of more iterations+ const searchEngine = getSetting('search.tool', 'duckduckgo').toLowerCase();+ const iterations = parseInt(getSetting('search.iterations', 2));+ const questionsPerIteration = parseInt(getSetting('search.questions_per_iteration', 3));+ const dismissSearxngRecommendation = getSetting('app.warnings.dismiss_searxng_recommendation', false);++ console.log('SearXNG check:', { searchEngine, iterations, questionsPerIteration, dismissSearxngRecommendation });++ if (searchEngine === 'searxng' && iterations > 2 && !dismissSearxngRecommendation) {+ warnings.push({+ type: 'searxng_recommendation',+ icon: '💡',+ title: 'SearXNG Optimization Tip',+ message: `For SearXNG, we recommend using more questions per iteration (${questionsPerIteration} → 10) instead of more iterations (${iterations}). SearXNG handles multiple questions efficiently in a single iteration.`,+ dismissKey: 'app.warnings.dismiss_searxng_recommendation'+ });+ }++ // Display warnings+ displayWarnings(warnings);+}++/**+ * Display warnings in the alert container+ */+function displayWarnings(warnings) {+ const alertContainer = document.getElementById('research-alert');+ if (!alertContainer) return;++ if (warnings.length === 0) {+ alertContainer.style.display = 'none';+ alertContainer.innerHTML = '';+ return;+ }++ const warningsHtml = warnings.map(warning => {+ // Use green styling for recommendations/tips+ const isRecommendation = warning.type === 'searxng_recommendation';+ const bgColor = isRecommendation ? '#d4edda' : '#fff3cd';+ const borderColor = isRecommendation ? '#c3e6cb' : '#ffeaa7';+ const textColor = isRecommendation ? '#155724' : '#856404';++ return `+ <div class="warning-banner warning-${warning.type}" style="+ background: ${bgColor};+ border: 1px solid ${borderColor};+ border-radius: 6px;+ padding: 12px 16px;+ margin-bottom: 8px;+ display: flex;+ align-items: flex-start;+ gap: 12px;+ ">+ <span style="font-size: 16px; flex-shrink: 0;">${warning.icon}</span>+ <div style="flex: 1;">+ <div style="font-weight: 600; color: ${textColor}; margin-bottom: 4px;">+ ${warning.title}+ </div>+ <div style="color: ${textColor}; font-size: 14px; line-height: 1.4;">+ ${warning.message}+ </div>+ </div>+ <button onclick="dismissWarning('${warning.dismissKey}')" style="+ background: none;+ border: none;+ color: ${textColor};+ cursor: pointer;+ padding: 4px;+ font-size: 16px;+ flex-shrink: 0;+ ">×</button>+ </div>+ `;+ }).join('');++ alertContainer.innerHTML = warningsHtml;+ alertContainer.style.display = 'block';+}++/**+ * Dismiss a warning by updating the setting+ */+function dismissWarning(dismissKey) {+ console.log('Dismissing warning:', dismissKey);++ // Get CSRF token+ const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');++ // Update dismissal setting+ fetch('/research/settings/save_all_settings', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({+ [dismissKey]: true+ })+ })+ .then(response => response.json())+ .then(data => {+ console.log('Warning dismissed:', data);+ // Update global settings cache+ globalSettings[dismissKey] = { value: true };+ // Recheck warnings+ checkAndDisplayWarnings();+ })+ .catch(error => {+ console.warn('Error dismissing warning:', error);+ });+}++/**+ * Helper functions to get current form values+ */+function getCurrentProvider() {+ const providerSelect = document.getElementById('model_provider');+ if (providerSelect && providerSelect.value) {+ return providerSelect.value.toLowerCase();+ }+ return 'ollama';+}++function getCurrentStrategy() {+ const strategySelect = document.getElementById('strategy');+ return strategySelect ? strategySelect.value : 'source-based';+}++function getCurrentModel() {+ // Try to get from model dropdown display+ const modelDisplay = document.querySelector('.model-dropdown .dropdown-display');+ return modelDisplay ? modelDisplay.textContent.trim() : '';+}++function getSetting(key, defaultValue) {+ return globalSettings[key] ? globalSettings[key].value : defaultValue;+}