~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 journal quality filter (#662)
Daniel Pettid02c2a76ba60
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 fd12d9ef39..4e2083c0ea 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@@ -8,6 +8,8 @@ from typing import Dict, List, Set, Tuplefrom loguru import logger+from ...utilities.thread_context import preserve_research_context+@dataclassclass SearchProgress:@@ -235,11 +237,6 @@ 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)@@ -249,7 +246,7 @@ class ProgressiveExplorer:return (query, [])# Create context-preserving wrapper for the search function- context_aware_search = create_context_preserving_wrapper(search_query)+ context_aware_search = preserve_research_context(search_query)# Run searches in parallelwith concurrent.futures.ThreadPoolExecutor(diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.pyindex 96e86a189a..b7154c3b64 100644--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py@@ -6,11 +6,13 @@ from typing import Any, Dict, List, Optionalfrom langchain_core.language_models.chat_models import BaseChatModelfrom loguru import loggerfrom methodtools import lru_cache+from sqlalchemy.orm import Sessionfrom ...config.llm_config import get_llmfrom ...database.models import Journalfrom ...database.session_context import get_user_db_sessionfrom ...search_system import AdvancedSearchSystem+from ...utilities.thread_context import get_search_contextfrom ...web_search_engines.search_engine_factory import create_search_enginefrom .base_filter import BaseFilter@@ -157,6 +159,19 @@ class JournalReputationFilter(BaseFilter):)return None+ @staticmethod+ def __db_session() -> Session:+ """+ Returns:+ The database session to use.++ """+ context = get_search_context()+ username = context.get("username")+ password = context.get("user_password")++ return get_user_db_session(username=username, password=password)+def __make_search_system(self) -> AdvancedSearchSystem:"""Creates a new `AdvancedSearchSystem` instance.@@ -169,7 +184,7 @@ class JournalReputationFilter(BaseFilter):llm=self.model,search=self.__engine,# We clamp down on the default iterations and questions for speed.- max_iterations=2,+ max_iterations=1,questions_per_iteration=3,settings_snapshot=self.__settings_snapshot,)@@ -245,7 +260,7 @@ class JournalReputationFilter(BaseFilter):quality: The quality assessment for the journal."""- with get_user_db_session() as db_session:+ with self.__db_session() as db_session:journal = db_session.query(Journal).filter_by(name=name).first()if journal is not None:journal.quality = quality@@ -311,7 +326,7 @@ class JournalReputationFilter(BaseFilter):journal_name = self.__clean_journal_name(journal_name)# Check the database first.- with get_user_db_session() as session:+ with self.__db_session() as session:journal = (session.query(Journal).filter_by(name=journal_name).first())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 358376a037..ae2696dbe1 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@@ -27,6 +27,10 @@ from loguru import loggerfrom ...citation_handler import CitationHandler# Model and search should be provided by AdvancedSearchSystem+from ...utilities.thread_context import (+ preserve_research_context,+ get_search_context,+)from ..candidate_exploration import ProgressiveExplorerfrom ..findings.repository import FindingsRepositoryfrom ..questions import BrowseCompQuestionGenerator@@ -365,17 +369,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:# Get the current research context to pass explicitly- from ...metrics.search_tracker import get_search_tracker- current_context = get_search_tracker()._get_research_context()+ current_context = get_search_context()result = self.search.run(q, research_context=current_context)return {"question": q, "results": result or []}except Exception as e:@@ -383,9 +381,7 @@ class FocusedIterationStrategy(BaseSearchStrategy):return {"question": q, "results": [], "error": str(e)}# Create context-preserving wrapper for the search function- context_aware_search = create_context_preserving_wrapper(- search_question- )+ context_aware_search = preserve_research_context(search_question)# Run searches in parallelwith concurrent.futures.ThreadPoolExecutor(@@ -409,11 +405,6 @@ 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:@@ -429,9 +420,8 @@ class FocusedIterationStrategy(BaseSearchStrategy):)# Get the current research context to pass explicitly- from ...metrics.search_tracker import get_search_tracker- current_context = get_search_tracker()._get_research_context()+ current_context = get_search_context()result = self.search.run(q, research_context=current_context)completed_searches += 1@@ -474,7 +464,7 @@ class FocusedIterationStrategy(BaseSearchStrategy):}# Create context-preserving wrapper for the search function- context_aware_search_with_progress = create_context_preserving_wrapper(+ context_aware_search_with_progress = preserve_research_context(search_question_with_progress)diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.pyindex 9f4205d40d..57de68bff5 100644--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py@@ -7,7 +7,10 @@ from ...citation_handler import CitationHandler# LLM and search instances should be passed via constructor, not imported# Removed get_db_setting import - using settings_snapshot instead-from ...utilities.thread_context import preserve_research_context+from ...utilities.thread_context import (+ preserve_research_context,+ get_search_context,+)from ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..filters.cross_engine_filter import CrossEngineFilterfrom ..findings.repository import FindingsRepository@@ -225,12 +228,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):@preserve_research_contextdef search_question(q):try:- # Get the current research context to pass explicitly- from ...metrics.search_tracker import get_search_tracker-- current_context = (- get_search_tracker()._get_research_context()- )+ current_context = get_search_context()result = self.search.run(q, research_context=current_context)diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex a6d31ec817..893a7997bd 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -14,6 +14,7 @@ from ..config.search_config import get_searchfrom ..report_generator import IntegratedReportGeneratorfrom ..search_system import AdvancedSearchSystemfrom ..utilities.db_utils import no_db_settings+from ..utilities.thread_context import set_search_contextfrom ..utilities.search_utilities import remove_think_tagsfrom .settings_utils import create_settings_snapshot@@ -245,9 +246,6 @@ def quick_summary(register_llm(name, llm_instance)logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")- # Set search context with research_id- from ..metrics.search_tracker import set_search_context-search_context = {"research_id": research_id, # Pass UUID or integer directly"research_query": query,@@ -462,9 +460,6 @@ def detailed_research(register_llm(name, llm_instance)logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")- # Set search context- from ..metrics.search_tracker import set_search_context-search_context = {"research_id": research_id,"research_query": query,diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.pyindex 49b3ae0904..c34df86586 100644--- a/src/local_deep_research/metrics/search_tracker.py+++ b/src/local_deep_research/metrics/search_tracker.py@@ -3,12 +3,12 @@ Search call tracking system for metrics collection.Similar to token_counter.py but tracks search engine usage."""-import threadingfrom typing import Any, Dict, List, Optionalfrom loguru import loggerfrom sqlalchemy import case, func+from ..utilities.thread_context import get_search_contextfrom ..database.models import SearchCallfrom .database import MetricsDatabasefrom .query_utils import get_research_mode_condition, get_time_filter_condition@@ -20,23 +20,9 @@ class SearchTracker:def __init__(self, db: Optional[MetricsDatabase] = None):"""Initialize the search tracker."""self.db = db or MetricsDatabase()- self._local = threading.local()-- def set_research_context(self, context: Dict[str, Any]) -> None:- """Set the current research context for search tracking (thread-safe)."""- self._local.research_context = context or {}- logger.debug(- f"Search tracker context updated (thread {threading.current_thread().ident}): {self._local.research_context}"- )-- def _get_research_context(self) -> Dict[str, Any]:- """Get the research context for the current thread."""- if not hasattr(self._local, "research_context"):- self._local.research_context = {}- return self._local.research_context+ @staticmethoddef record_search(- self,engine_name: str,query: str,results_count: int = 0,@@ -47,7 +33,7 @@ class SearchTracker:"""Record a completed search operation directly to database."""# Extract research context (thread-safe)- context = self._get_research_context()+ context = get_search_context()research_id = context.get("research_id")# Convert research_id to string if it's an integer (for backward compatibility)@@ -419,9 +405,3 @@ def get_search_tracker() -> SearchTracker:if _search_tracker is None:_search_tracker = SearchTracker()return _search_tracker---def set_search_context(context: Dict[str, Any]) -> None:- """Set search context for the global tracker."""- tracker = get_search_tracker()- tracker.set_research_context(context)diff --git a/src/local_deep_research/utilities/thread_context.py b/src/local_deep_research/utilities/thread_context.pyindex 496b182558..44dabca6ee 100644--- a/src/local_deep_research/utilities/thread_context.py+++ b/src/local_deep_research/utilities/thread_context.py@@ -6,11 +6,49 @@ which is necessary when strategies use ThreadPoolExecutor for parallel searches."""import functools+from threading import localfrom typing import Any, Callable, Dict+from loguru import logger+# Lazy import to avoid database initialization for programmatic access_search_tracker = None+_g_thread_data = local()+"""+Thread-local storage for research context data.+"""+++def set_search_context(context: Dict[str, Any]) -> None:+ """+ Sets the research context for this entire thread.++ Args:+ context: The context to set.++ """+ global _g_thread_data+ if hasattr(_g_thread_data, "context"):+ logger.warning(+ "Context already set for this thread. It will be overwritten."+ )+ _g_thread_data.context = context.copy()+++def get_search_context() -> Dict[str, Any] | None:+ """+ Gets the current research context for this thread.++ Returns:+ The context dictionary, or None if no context is set.++ """+ context = getattr(_g_thread_data, "context", None)+ if context is not None:+ context = context.copy()+ return context+def _get_search_tracker_if_needed():"""Get search tracker only if metrics are enabled."""@@ -46,90 +84,16 @@ def preserve_research_context(func: Callable) -> Callable:def search_task(query):return search_engine.run(query)"""+ # Try to capture current context, but don't fail if it's not set. There+ # are legitimate cases where it might not be set, such as for+ # programmatic access.+ context = get_search_context()@functools.wraps(func)def wrapper(*args, **kwargs):- # Try to get search tracker - will be None if metrics are disabled- tracker = _get_search_tracker_if_needed()-- if tracker is not None:- # Only preserve context if metrics are enabled- if hasattr(wrapper, "_research_context"):- tracker.set_research_context(wrapper._research_context)+ if context is not None:+ set_search_context(context)return func(*args, **kwargs)- # Try to capture current context, but don't fail if metrics are disabled- tracker = _get_search_tracker_if_needed()- if tracker is not None:- wrapper._research_context = 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- tracker = _get_search_tracker_if_needed()- if context is None and tracker is not None:- context = tracker._get_research_context()-- @functools.wraps(func)- def wrapper(*args, **kwargs):- # Set the captured context in the new thread- tracker = _get_search_tracker_if_needed()- if tracker is not None and context is not None:- 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_if_needed()-- if tracker is None:- # No metrics tracking - just run the function- return func(*args, **kwargs)-- # 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/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 3793e090ed..0fa1d3c830 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -16,7 +16,7 @@ from ...config.search_config import get_searchfrom ...database.models import ResearchHistory, ResearchStrategyfrom ...database.session_context import get_user_db_sessionfrom ...error_handling.report_generator import ErrorReportGenerator-from ...metrics.search_tracker import set_search_context+from ...utilities.thread_context import set_search_contextfrom ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystemfrom ...text_optimization import CitationFormatter, CitationModediff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.pyindex 900227fb29..c06f78c2d5 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py@@ -10,7 +10,7 @@ from typing import Dict, List, Optional, Tuplefrom loguru import loggerfrom ...settings.env_registry import use_fallback_llm, is_ci_environment-+from ...utilities.thread_context import get_search_contextfrom ...config.thread_settings import (get_settings_context,get_setting_from_snapshot,@@ -176,10 +176,8 @@ class AdaptiveRateLimitTracker:return# Try to get research context from search tracker- from ...metrics.search_tracker import get_search_tracker- tracker = get_search_tracker()- context = tracker._get_research_context()+ context = get_search_context()username = context.get("username")password = context.get("user_password")@@ -311,13 +309,13 @@ class AdaptiveRateLimitTracker:)# Skip database operations in fallback modeelif not use_fallback_llm():- # Try to get research context from search tracker (for username/password)- from ...metrics.search_tracker import get_search_tracker-- tracker = get_search_tracker()- context = tracker._get_research_context()- username = context.get("username")- password = context.get("user_password")+ # Try to get research context (for username/password)+ context = get_search_context()+ username = None+ password = None+ if context:+ username = context.get("username")+ password = context.get("user_password")if username and password:try:@@ -456,12 +454,13 @@ class AdaptiveRateLimitTracker:)elif not use_fallback_llm():# Try to get research context from search tracker- from ...metrics.search_tracker import get_search_tracker- tracker = get_search_tracker()- context = tracker._get_research_context()- username = context.get("username")- password = context.get("user_password")+ context = get_search_context()+ username = None+ password = None+ if context is not None:+ username = context.get("username")+ password = context.get("user_password")if username and password:try: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 bc5561322d..759d57cb39 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@@ -15,6 +15,7 @@ from tenacity import (from tenacity.wait import wait_basefrom ..advanced_search_system.filters.base_filter import BaseFilter+from ..utilities.thread_context import set_search_context# Lazy import for metrics to avoid database dependencies in programmatic mode# from ..metrics.search_tracker import get_search_tracker@@ -174,25 +175,19 @@ class BaseSearchEngine(ABC):# Track search call for metrics (if available and not in programmatic mode)tracker = Noneif not self.programmatic_mode:- try:- from ..metrics.search_tracker import get_search_tracker-- tracker = 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- except (ImportError, RuntimeError) as e:- # Metrics tracking not available- logger.debug(f"Search metrics tracking disabled: {e}")+ from ..metrics.search_tracker import get_search_tracker++ tracker = 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+ if research_context:+ # Explicit context provided - use it and set it for this thread+ set_search_context(research_context)+ else:+ # Search tracker will not work without research context.+ logger.debug("Search metrics tracking disabled: no context.")tracker = Noneelse:logger.debug(diff --git a/tests/test_llm/test_api_llm_integration.py b/tests/test_llm/test_api_llm_integration.pyindex 414bb8ac33..886f65af82 100644--- a/tests/test_llm/test_api_llm_integration.py+++ b/tests/test_llm/test_api_llm_integration.py@@ -143,7 +143,7 @@ def test_detailed_research_with_custom_llm(mock_search_system):# Verify research context was setwith patch(- "local_deep_research.metrics.search_tracker.set_search_context"+ "local_deep_research.utilities.thread_context.set_search_context") as mock_context:detailed_research(query="Context test",