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 PR review issues: centralize warnings, improve defaults, and enhance safety

LearningCircuite482690548e3
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 3eaa5b9966..1a1a3baacb 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -265,13 +265,13 @@ def get_llm(
# Use 80% of context window to leave room for prompts
if context_window_size is not None:
max_tokens = min(
- int(get_db_setting("llm.max_tokens", 30000)),
+ int(get_db_setting("llm.max_tokens", 100000)),
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))
+ max_tokens = int(get_db_setting("llm.max_tokens", 100000))
common_params["max_tokens"] = max_tokens
# Handle different providers
@@ -500,7 +500,7 @@ def get_llm(
llm = LlamaCppClient(
server_url=server_url,
temperature=temperature,
- max_tokens=get_db_setting("llm.max_tokens", 30000),
+ max_tokens=get_db_setting("llm.max_tokens", 8192),
)
else:
# Use direct model loading (existing code)
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index c692407eed..f2ec96afee 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -38,15 +38,8 @@ def calculate_warnings():
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 a fresh database session for safety
+ db_session = get_db_session()
# Get current settings
provider = get_setting("llm.provider", "ollama", db_session).lower()
@@ -54,7 +47,7 @@ def calculate_warnings():
"llm.local_context_window_size", 4096, db_session
)
- logger.info(f"Starting warning calculation - provider={provider}")
+ logger.debug(f"Starting warning calculation - provider={provider}")
# Get dismissal settings
dismiss_high_context = get_setting(
@@ -85,9 +78,36 @@ def calculate_warnings():
}
)
+ # Get additional warning settings
+ dismiss_model_mismatch = get_setting(
+ "app.warnings.dismiss_model_mismatch", False, db_session
+ )
+
+ # Get current strategy and model (these need to be passed from the frontend or retrieved differently)
+ # For now, we'll implement basic warnings that don't require form state
+
+ # Model mismatch warning (simplified - checking setting instead of form value)
+ current_model = get_setting("llm.model", "", db_session)
+ if (
+ current_model
+ and "70b" in current_model.lower()
+ and is_local_provider
+ and local_context > 8192
+ and not dismiss_model_mismatch
+ ):
+ warnings.append(
+ {
+ "type": "model_mismatch",
+ "icon": "🧠",
+ "title": "Model & Context Warning",
+ "message": f"Large model ({current_model}) with high context ({local_context:,}) 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
search_engine = get_setting(
- "search.tool", "duckduckgo", db_session
+ "search.tool", "wikipedia", db_session
).lower()
iterations = int(get_setting("search.iterations", 2, db_session))
questions_per_iteration = int(
@@ -1697,6 +1717,17 @@ def fix_corrupted_settings():
)
+@settings_bp.route("/api/warnings", methods=["GET"])
+def api_get_warnings():
+ """Get current warnings based on settings"""
+ try:
+ warnings = calculate_warnings()
+ return jsonify({"warnings": warnings})
+ except Exception as e:
+ logger.exception("Error getting warnings")
+ return jsonify({"error": str(e)}), 500
+
+
@settings_bp.route("/api/ollama-status", methods=["GET"])
def check_ollama_status():
"""Check if Ollama is running and available"""
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index 23da45c37e..540d83123a 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -623,5 +623,5 @@ class SettingsManager:
)
except Exception as e:
- logger.warning(f"Failed to emit settings change event: {e}")
+ logger.exception(f"Failed to emit settings change event: {e}")
# Don't let WebSocket emission failures break settings saving
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index 680d24c923..217c7235bf 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -200,13 +200,13 @@ function refetchSettingsAndUpdateWarnings() {
if (data && data.status === 'success' && data.settings) {
// Update global settings cache
globalSettings = data.settings;
- // Recheck warnings with fresh settings
- setTimeout(checkAndDisplayWarnings, 100);
}
+ // Recheck warnings from backend (not from cached settings)
+ setTimeout(checkAndDisplayWarnings, 100);
})
.catch(error => {
console.warn('Error refetching settings:', error);
- // Fallback to checking warnings with current settings
+ // Still try to check warnings from backend
setTimeout(checkAndDisplayWarnings, 100);
});
}
@@ -216,111 +216,31 @@ window.refetchSettingsAndUpdateWarnings = refetchSettingsAndUpdateWarnings;
window.displayWarnings = displayWarnings;
/**
- * Check warning conditions and display warnings
+ * Check warning conditions by fetching from backend
*/
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');
+ console.log('Checking warning conditions from backend...');
- 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'
+ // Get warnings from backend API instead of calculating locally
+ fetch('/research/settings/api/warnings')
+ .then(response => {
+ if (!response.ok) {
+ throw new Error('Failed to fetch warnings');
+ }
+ return response.json();
+ })
+ .then(data => {
+ if (data && data.warnings) {
+ displayWarnings(data.warnings);
+ } else {
+ displayWarnings([]);
+ }
+ })
+ .catch(error => {
+ console.warn('Error fetching warnings from backend:', error);
+ // Clear warnings on error
+ displayWarnings([]);
});
- }
-
- // Display warnings
- displayWarnings(warnings);
}
/**
@@ -414,27 +334,8 @@ function dismissWarning(dismissKey) {
}
/**
- * Helper functions to get current form values
+ * Helper function to get settings
*/
-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;
}