~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
Fix benchmark search tracking and UI issues
LearningCircuit75afe044e4fb
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.pyindex 0907ab40ff..3e786775ad 100644--- a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py@@ -236,6 +236,11 @@ class ProgressiveExplorer:"""Execute searches in parallel and return results."""results = []+ # Import context preservation utility+ from ...utilities.thread_context import (+ create_context_preserving_wrapper,+ )+def search_query(query):try:search_results = self.search_engine.run(query)@@ -244,11 +249,16 @@ class ProgressiveExplorer:logger.error(f"Error searching '{query}': {str(e)}")return (query, [])+ # Create context-preserving wrapper for the search function+ context_aware_search = create_context_preserving_wrapper(search_query)+# Run searches in parallelwith concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:- futures = [executor.submit(search_query, q) for q in queries]+ futures = [+ executor.submit(context_aware_search, q) for q in queries+ ]for future in concurrent.futures.as_completed(futures):results.append(future.result())diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.pyindex e24c6f0d30..c990fd5642 100644--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py@@ -358,6 +358,11 @@ class FocusedIterationStrategy(BaseSearchStrategy):"""Execute searches in parallel (like source-based strategy)."""all_results = []+ # Import context preservation utility+ from ...utilities.thread_context import (+ create_context_preserving_wrapper,+ )+def search_question(q):try:result = self.search.run(q)@@ -366,11 +371,18 @@ class FocusedIterationStrategy(BaseSearchStrategy):logger.error(f"Error searching '{q}': {str(e)}")return {"question": q, "results": [], "error": str(e)}+ # Create context-preserving wrapper for the search function+ context_aware_search = create_context_preserving_wrapper(+ search_question+ )+# Run searches in parallelwith concurrent.futures.ThreadPoolExecutor(max_workers=len(queries)) as executor:- futures = [executor.submit(search_question, q) for q in queries]+ futures = [+ executor.submit(context_aware_search, q) for q in queries+ ]for future in concurrent.futures.as_completed(futures):result_dict = future.result()@@ -386,6 +398,11 @@ class FocusedIterationStrategy(BaseSearchStrategy):completed_searches = 0total_searches = len(queries)+ # Import context preservation utility+ from ...utilities.thread_context import (+ create_context_preserving_wrapper,+ )+def search_question_with_progress(q):nonlocal completed_searchestry:@@ -441,12 +458,17 @@ class FocusedIterationStrategy(BaseSearchStrategy):"result_count": 0,}+ # Create context-preserving wrapper for the search function+ context_aware_search_with_progress = create_context_preserving_wrapper(+ search_question_with_progress+ )+# Run searches in parallelwith concurrent.futures.ThreadPoolExecutor(max_workers=min(len(queries), 5)) as executor:futures = [- executor.submit(search_question_with_progress, q)+ executor.submit(context_aware_search_with_progress, q)for q in queries]diff --git a/src/local_deep_research/utilities/thread_context.py b/src/local_deep_research/utilities/thread_context.pynew file mode 100644index 0000000000..99b9c5af1b--- /dev/null+++ b/src/local_deep_research/utilities/thread_context.py@@ -0,0 +1,99 @@+"""+Utility functions for handling thread-local context propagation.++This module provides helpers for propagating research context across thread boundaries,+which is necessary when strategies use ThreadPoolExecutor for parallel searches.+"""++import functools+from typing import Any, Callable, Dict++from ..metrics.search_tracker import get_search_tracker+++def preserve_research_context(func: Callable) -> Callable:+ """+ Decorator that preserves research context across thread boundaries.++ Use this decorator on functions that will be executed in ThreadPoolExecutor+ to ensure the research context (including research_id) is properly propagated.++ Example:+ @preserve_research_context+ def search_task(query):+ return search_engine.run(query)+ """++ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ # The context should already be captured in the closure when the decorator runs+ # Set it in the new thread+ tracker = get_search_tracker()+ if hasattr(wrapper, "_research_context"):+ tracker.set_research_context(wrapper._research_context)+ return func(*args, **kwargs)++ # Capture the current context when the decorator is applied+ wrapper._research_context = get_search_tracker()._get_research_context()+ return wrapper+++def create_context_preserving_wrapper(+ func: Callable, context: Dict[str, Any] = None+) -> Callable:+ """+ Create a wrapper function that preserves research context.++ This is useful when you need to create the wrapper dynamically and can't use a decorator.++ Args:+ func: The function to wrap+ context: Optional explicit context to use. If None, captures current context.++ Returns:+ A wrapped function that sets the research context before executing+ """+ # Capture context at wrapper creation time if not provided+ if context is None:+ context = get_search_tracker()._get_research_context()++ @functools.wraps(func)+ def wrapper(*args, **kwargs):+ # Set the captured context in the new thread+ get_search_tracker().set_research_context(context)+ return func(*args, **kwargs)++ return wrapper+++def run_with_context(+ func: Callable, *args, context: Dict[str, Any] = None, **kwargs+) -> Any:+ """+ Run a function with a specific research context.++ Args:+ func: The function to run+ *args: Positional arguments for the function+ context: Optional explicit context. If None, uses current context.+ **kwargs: Keyword arguments for the function++ Returns:+ The result of the function call+ """+ tracker = get_search_tracker()++ # Save current context+ original_context = tracker._get_research_context()++ try:+ # Set new context+ if context is None:+ context = original_context+ tracker.set_research_context(context)++ # Run the function+ return func(*args, **kwargs)+ finally:+ # Restore original context+ tracker.set_research_context(original_context)diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.htmlindex b679022c3f..4ded272281 100644--- a/src/local_deep_research/web/templates/pages/benchmark.html+++ b/src/local_deep_research/web/templates/pages/benchmark.html@@ -193,8 +193,8 @@}.processing-status.processing {- background: #e3f2fd;- color: #1976d2;+ background: #ff9800;+ color: #ffffff;}.processing-status.completed {@@ -781,7 +781,7 @@<div class="alert" style="background: rgba(33, 150, 243, 0.1); border: 1px solid rgba(33, 150, 243, 0.3); color: #ffffff; padding: 15px; border-radius: 6px; margin-top: 15px;"><i class="fas fa-info-circle" style="color: #2196f3; margin-right: 8px;"></i><strong style="color: #2196f3;">Evaluation Model Selection:</strong>- For accurate benchmark grading, use high-performance models like Claude 3.5 Sonnet, GPT-4, or similar flagship models.+ For accurate benchmark grading, use flagship models from major providers like Claude Sonnet series or GPT-4 class models.Local models and smaller cloud models may produce inconsistent evaluations, affecting benchmark accuracy scores.</div></div>@@ -1027,7 +1027,17 @@ function initializeBenchmarkForm() {updateConfigSummary();});- // BrowseComp is disabled, so no event listener needed+ // BrowseComp toggle - enable/disable count input when checkbox is toggled+ document.getElementById('browsecomp_enabled').addEventListener('change', function() {+ const countInput = document.getElementById('browsecomp_count');+ countInput.disabled = !this.checked;+ if (!this.checked) {+ countInput.value = 0; // Reset to 0 when disabled+ } else {+ countInput.value = 5; // Set a reasonable default when enabled+ }+ updateConfigSummary();+ });}@@ -1394,8 +1404,11 @@ function checkForRunningBenchmark() {// Load current settings from database and display themasync 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'),@@ -1408,6 +1421,10 @@ async function loadCurrentSettings() {fetch('/research/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();@@ -1420,14 +1437,25 @@ async function loadCurrentSettings() {console.log('Loaded settings:', { llmData, searchToolData, iterationsData, questionsData, strategyData, evalProviderData, evalModelData, evalTempData, evalEndpointData });- // Display LLM settings- if (llmData && llmData.settings && llmData.settings.value) {- const settings = llmData.settings.value;-- document.getElementById('current-provider').textContent =- settings.provider ? settings.provider.toUpperCase() : 'Not set';- document.getElementById('current-model').textContent =- settings.model || 'Not set';+ // 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');++ if (providerEl) providerEl.textContent = settings.provider ? settings.provider.toUpperCase() : 'Not set';+ if (modelEl) modelEl.textContent = settings.model || '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';+ if (modelEl) modelEl.textContent = 'Not set';+ }+ } catch (e) {+ console.error('Error setting LLM display:', e);}// Display search tool and check for warnings@@ -1437,6 +1465,8 @@ async function loadCurrentSettings() {// Check for search engine warningscheckSearchEngineWarnings(searchTool);+ } else {+ document.getElementById('current-search-tool').textContent = 'Not set';}// Display search iterations@@ -1463,48 +1493,28 @@ async function loadCurrentSettings() {document.getElementById('current-strategy').textContent = 'focused_iteration'; // default}- // Display evaluation settings- if (evalProviderData && evalProviderData.settings && evalProviderData.settings.value) {- const providerValue = evalProviderData.settings.value;- const providerLabels = {- 'openai_endpoint': 'OpenRouter',- 'openai': 'OpenAI',- 'anthropic': 'Anthropic',- 'ollama': 'Ollama'- };- document.getElementById('current-evaluation-provider').textContent =- providerLabels[providerValue] || providerValue || 'OpenRouter';- } else {- document.getElementById('current-evaluation-provider').textContent = 'OpenRouter'; // default- }-- if (evalModelData && evalModelData.settings && evalModelData.settings.value) {- document.getElementById('current-evaluation-model').textContent =- evalModelData.settings.value || 'anthropic/claude-3.7-sonnet';- } else {- document.getElementById('current-evaluation-model').textContent = 'anthropic/claude-3.7-sonnet'; // default- }+ // Display evaluation settings (commented out as these elements don't exist)+ // TODO: Add evaluation settings display section if needed- if (evalTempData && evalTempData.settings && evalTempData.settings.value !== undefined) {- document.getElementById('current-evaluation-temperature').textContent =- evalTempData.settings.value.toString() || '0';- } else {- document.getElementById('current-evaluation-temperature').textContent = '0'; // default- }-- if (evalEndpointData && evalEndpointData.settings && evalEndpointData.settings.value) {- document.getElementById('current-evaluation-endpoint').textContent =- evalEndpointData.settings.value || 'https://openrouter.ai/api/v1';- } else {- document.getElementById('current-evaluation-endpoint').textContent = 'https://openrouter.ai/api/v1'; // default- }+ // For now, just log the evaluation settings+ console.log('Evaluation settings loaded:', {+ provider: evalProviderData?.settings?.value || 'openai_endpoint',+ model: evalModelData?.settings?.value || 'anthropic/claude-3.7-sonnet',+ temperature: evalTempData?.settings?.value || 0,+ endpoint: evalEndpointData?.settings?.value || 'https://openrouter.ai/api/v1'+ });} catch (error) {console.error('Error loading current settings:', error);- document.querySelectorAll('#current-settings-display .metric-value, #current-evaluation-settings-display .metric-value').forEach(el => {+ console.error('Error details:', error.message);+ console.error('Error stack:', error.stack);++ // Set error text on all metric values+ document.querySelectorAll('#current-settings-display .metric-value').forEach(el => {el.textContent = 'Error loading';});- showAlert('Could not load current settings. Using defaults.', 'warning');++ showAlert('Could not load current settings. Check console for details.', 'warning');}}@@ -2084,12 +2094,21 @@ let evaluationEndpointInput = null;let evaluationTemperatureInput = null;function initializeEvaluationSettings() {+ console.log('Initializing evaluation settings...');+// Get DOM elementsevaluationProviderSelect = document.getElementById('evaluation_provider');evaluationModelInput = document.getElementById('evaluation_model');evaluationEndpointInput = document.getElementById('evaluation_endpoint_url');evaluationTemperatureInput = document.getElementById('evaluation_temperature');+ console.log('DOM elements found:', {+ provider: !!evaluationProviderSelect,+ model: !!evaluationModelInput,+ endpoint: !!evaluationEndpointInput,+ temperature: !!evaluationTemperatureInput+ });+// Setup evaluation model dropdown using existing custom dropdownsetupEvaluationModelDropdown();@@ -2102,8 +2121,10 @@ function initializeEvaluationSettings() {loadEvaluationModelsFromAPI();}- // Load settings- loadEvaluationSettings();+ // Load settings with a small delay to ensure DOM is ready+ setTimeout(() => {+ loadEvaluationSettings();+ }, 100);}function setupEvaluationModelDropdown() {@@ -2339,6 +2360,14 @@ function setupEvaluationEventHandlers() {}function loadEvaluationSettings() {+ console.log('Loading evaluation settings...');+ console.log('Current DOM elements state:', {+ provider: !!evaluationProviderSelect,+ model: !!evaluationModelInput,+ endpoint: !!evaluationEndpointInput,+ temperature: !!evaluationTemperatureInput+ });+fetch('/research/settings/api', {method: 'GET',headers: {@@ -2347,48 +2376,88 @@ function loadEvaluationSettings() {}).then(response => response.json()).then(data => {+ console.log('Evaluation settings API response:', data);+if (data && data.settings) {// Set providerconst providerSetting = data.settings["benchmark.evaluation.provider"];- if (providerSetting && evaluationProviderSelect) {- evaluationProviderSelect.value = providerSetting.value || 'openai_endpoint';+ 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 fieldif (evaluationEndpointInput && evaluationEndpointInput.parentNode) {evaluationEndpointInput.parentNode.style.display =- providerSetting.value === 'openai_endpoint' ? 'block' : 'none';+ providerValue === 'openai_endpoint' ? 'block' : 'none';+ console.log('Endpoint field visibility:', evaluationEndpointInput.parentNode.style.display);}+ } else {+ console.warn('evaluationProviderSelect is null');}// Set modelconst modelSetting = data.settings["benchmark.evaluation.model"];- if (modelSetting && evaluationModelInput) {- evaluationModelInput.value = modelSetting.value || 'anthropic/claude-3.7-sonnet';+ console.log('Model setting:', modelSetting);++ 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);+ } else {+ console.warn('evaluationModelInput is null');}// Set endpoint URLconst endpointSetting = data.settings["benchmark.evaluation.endpoint_url"];- if (endpointSetting && evaluationEndpointInput) {- evaluationEndpointInput.value = endpointSetting.value || 'https://openrouter.ai/api/v1';+ 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');}// Set temperatureconst temperatureSetting = data.settings["benchmark.evaluation.temperature"];- if (temperatureSetting && evaluationTemperatureInput) {- evaluationTemperatureInput.value = temperatureSetting.value || 0;+ 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');}+ } else {+ console.log('No settings found in response, using defaults');+ setEvaluationDefaults();}}).catch(error => {console.error('Error loading evaluation settings:', error);- // Set defaults- if (evaluationProviderSelect) evaluationProviderSelect.value = 'openai_endpoint';- if (evaluationModelInput) evaluationModelInput.value = 'anthropic/claude-3.7-sonnet';- if (evaluationEndpointInput) evaluationEndpointInput.value = 'https://openrouter.ai/api/v1';- if (evaluationTemperatureInput) evaluationTemperatureInput.value = 0;+ setEvaluationDefaults();});}+function setEvaluationDefaults() {+ console.log('Setting evaluation defaults');+ if (evaluationProviderSelect) {+ evaluationProviderSelect.value = 'openai_endpoint';+ // Show endpoint field for default provider+ if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {+ evaluationEndpointInput.parentNode.style.display = 'block';+ }+ }+ if (evaluationModelInput) evaluationModelInput.value = 'anthropic/claude-3.7-sonnet';+ if (evaluationEndpointInput) evaluationEndpointInput.value = 'https://openrouter.ai/api/v1';+ if (evaluationTemperatureInput) evaluationTemperatureInput.value = 0;+}+function saveEvaluationSetting(key, value) {fetch('/research/settings/api', {method: 'POST',diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex 16dd70ec36..af1a99356e 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -131,7 +131,9 @@ class BaseSearchEngine(ABC):search_result_count=self._last_results_count if success else 0,)- def run(self, query: str) -> List[Dict[str, Any]]:+ def run(+ self, query: str, research_context: Dict[str, Any] = None+ ) -> List[Dict[str, Any]]:"""Run the search engine with a given query, retrieving and filtering results.This implements a two-phase retrieval approach:@@ -147,6 +149,19 @@ class BaseSearchEngine(ABC):"""# Track search call for metricstracker = get_search_tracker()++ # For thread-safe context propagation: if we have research_context parameter, use it+ # Otherwise, try to inherit from current thread context (normal case)+ # This allows strategies running in threads to explicitly pass context when needed+ current_context = tracker._get_research_context()+ if research_context:+ # Explicit context provided - use it and set it for this thread+ tracker.set_research_context(research_context)+ elif not current_context.get("research_id"):+ # No context in current thread and none provided - try to get from main thread+ # This handles the case where we're in a worker thread without context+ pass # Will use empty context, research_id will be None+engine_name = self.__class__.__name__.replace("SearchEngine", "").lower()