~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
WIP on improved logging.
Daniel Petti5b6ab31410a8
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 1206723758..6750338eb1 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@@ -1,18 +1,18 @@import concurrent.futures-import loggingfrom typing import Dict+from loguru import logger+from ...citation_handler import CitationHandlerfrom ...config.llm_config import get_llmfrom ...config.search_config import get_searchfrom ...utilities.db_utils import get_db_setting+from ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..filters.cross_engine_filter import CrossEngineFilterfrom ..findings.repository import FindingsRepositoryfrom ..questions.standard_question import StandardQuestionGeneratorfrom .base_strategy import BaseSearchStrategy-logger = logging.getLogger(__name__)-class SourceBasedSearchStrategy(BaseSearchStrategy):"""@@ -199,6 +199,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):)# Function for thread pool+ @thread_with_app_contextdef search_question(q):try:result = self.search.run(q)@@ -212,7 +213,8 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):max_workers=len(all_questions)) as executor:futures = [- executor.submit(search_question, q) for q in all_questions+ executor.submit(search_question, thread_context(), q)+ for q in all_questions]iteration_search_dict = {}iteration_search_results = []diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex 544ee752e5..6ce388aa97 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -1,12 +1,12 @@import osfrom typing import Any, Dict-from threading import Lock-from cachetools import cached, LRUCache+from cachetools import LRUCachefrom loguru import loggerfrom sqlalchemy import create_enginefrom sqlalchemy.orm import Session, sessionmaker+from ..utilities.threading_utils import thread_specific_cachefrom ..web.services.settings_manager import SettingsManager# Database path.@@ -14,7 +14,7 @@ DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "DB_PATH = os.path.join(DATA_DIR, "ldr.db")-@cached(cache=LRUCache(maxsize=1), lock=Lock())+@thread_specific_cache(cache=LRUCache(maxsize=1))def get_db_session() -> Session:"""Returns:@@ -25,7 +25,7 @@ def get_db_session() -> Session:return session_class()-@cached(cache=LRUCache(maxsize=1), lock=Lock())+@thread_specific_cache(cache=LRUCache(maxsize=1))def get_settings_manager() -> SettingsManager:"""Returns:diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 38de5f0fb7..49627db8cf 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -8,11 +8,12 @@ from __future__ import annotationsimport inspectimport loggingimport sys+from functools import wrapsfrom pathlib import Path-from functools import cache, wraps-from typing import Callable, Any+from typing import Any, Callableimport loguru+from flask import g, has_app_contextfrom loguru import loggerfrom ..web.database.models import ResearchLog@@ -57,8 +58,8 @@ class InterceptHandler(logging.Handler):def log_for_research(to_wrap: Callable[[int, ...], Any]) -> Callable[[int, ...], Any]:"""Decorator for a function that's part of the research process. It expects the function to- take the research ID as the first parameter, and configures the core logger to inject- the research ID into log messages.+ take the research ID as the first parameter, and configures all log+ messages made during this request to include the research ID.Args:to_wrap: The function to wrap. Should take the research ID as the first parameter.@@ -70,22 +71,37 @@ def log_for_research(to_wrap: Callable[[int, ...], Any]) -> Callable[[int, ...],@wraps(to_wrap)def wrapped(research_id: int, *args: Any, **kwargs: Any) -> Any:- with logger.contextualize(research_id=research_id):- to_wrap(research_id, *args, **kwargs)+ g.research_id = research_id+ to_wrap(research_id, *args, **kwargs)+ g.pop("research_id")return wrapped+def _get_research_id() -> int | None:+ """+ Gets the current research ID, if present.++ Returns:+ The current research ID, or None if it does not exist.++ """+ research_id = None+ if has_app_context():+ research_id = g.get("research_id")+ return research_id++def database_sink(message: loguru.Message) -> None:"""- Handles configuring Loguru to save log messages to the database.+ Sink that saves messages to the database.Args:message: The log message to save."""record = message.record- research_id = record["extra"].get("research_id")+ research_id = _get_research_id()# Create a new database entry.db_log = ResearchLog(@@ -95,7 +111,7 @@ def database_sink(message: loguru.Message) -> None:function=record["function"],line_no=int(record["line"]),level=record["level"].name,- research_id=research_id+ research_id=research_id,)# Save the entry to the database.@@ -103,10 +119,29 @@ def database_sink(message: loguru.Message) -> None:db_session.add(db_log)db_session.commit()- if research_id is not None:- # If we are running research, all send out this log on the websocket.- frontend_log = dict(message=record["message"], type=db_log.level, time=db_log.timestamp.isoformat())- emit_to_subscribers("research_progress", research_id, frontend_log)++def frontend_progress_sink(message: loguru.Message) -> None:+ """+ Sink that sends messages to the frontend.++ Args:+ message: The log message to send.++ """+ research_id = _get_research_id()+ if research_id is None:+ # If we don't have a research ID, don't send anything.+ return++ record = message.record+ frontend_log = dict(+ log_entry=dict(+ message=record["message"],+ type=record["level"].name,+ time=record["time"].isoformat(),+ ),+ )+ emit_to_subscribers("progress", research_id, frontend_log)def config_logger(name: str) -> None:@@ -131,6 +166,7 @@ def config_logger(name: str) -> None:compression="zip",)logger.add(database_sink)+ logger.add(frontend_progress_sink)# Add a special log level for milestones.logger.level("milestone", no=26, color="#69348a")diff --git a/src/local_deep_research/utilities/threading_utils.py b/src/local_deep_research/utilities/threading_utils.pynew file mode 100644index 0000000000..9b9c1be14e--- /dev/null+++ b/src/local_deep_research/utilities/threading_utils.py@@ -0,0 +1,75 @@+import threading+from functools import wraps+from typing import Any, Callable, Tuple++from cachetools import cached, keys+from flask import current_app, g+from flask.ctx import AppContext+++def thread_specific_cache(*args: Any, **kwargs: Any) -> Callable:+ """+ A version of `cached()` that is local to a single thread. In other words,+ cache entries will only be valid in the thread where they were created.++ Args:+ *args: Will be forwarded to `cached()`.+ **kwargs: Will be forwarded to `cached()`.++ Returns:+ The wrapped function.++ """++ def _key_func(*args_: Any, **kwargs_: Any) -> Tuple[int, ...]:+ base_hash = keys.hashkey(*args_, **kwargs_)+ return (threading.get_ident(),) + base_hash++ return cached(*args, **kwargs, key=_key_func)+++def thread_with_app_context(to_wrap: Callable) -> Callable:+ """+ Decorator that wraps the entry point to a thread and injects the current+ app context from Flask. This is useful when we want to use multiple+ threads to handle a single request.++ When using this wrapped function, `current_app.app_context()` should be+ passed as the first argument when initializing the thread.++ Args:+ to_wrap: The function to wrap.++ Returns:+ The wrapped function.++ """++ @wraps(to_wrap)+ def _run_with_context(app_context: AppContext, *args: Any, **kwargs: Any) -> Any:+ with app_context:+ return to_wrap(*args, **kwargs)++ return _run_with_context+++def thread_context() -> AppContext:+ """+ Pushes a new app context for a thread that is being spawned to handle the+ current request. Will copy all the global data from the current context.++ Returns:+ The new context.++ """+ # Copy global data.+ global_data = {}+ for key in g:+ global_data[key] = g.get(key)++ context = current_app.app_context()+ with context:+ for key, value in global_data.items():+ setattr(g, key, value)++ return contextdiff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.pyindex 9a9d980fcb..7f23594fd6 100644--- a/src/local_deep_research/web/app.py+++ b/src/local_deep_research/web/app.py@@ -45,16 +45,15 @@ def check_migration_needed():return False-# Create the Flask app and SocketIO instance-app, socketio = create_app()--@logger.catchdef main():"""Entry point for the web application when run as a command.This function is needed for the package's entry point to work properly."""+ # Create the Flask app and SocketIO instance+ app, socketio = create_app()+# Check if migration is neededif check_migration_needed():logger.info(diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex a1731eb6bc..c7b9336bb6 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -195,8 +195,8 @@ def register_socket_events(socketio):handle_connect(request)@socketio.on("disconnect")- def on_disconnect():- handle_disconnect(request)+ def on_disconnect(reason: str):+ handle_disconnect(request, reason)@socketio.on("subscribe_to_research")def on_subscribe(data):diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex c68cfe3412..1445288d30 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -2,20 +2,18 @@ import hashlibimport jsonimport threadingfrom datetime import datetime-from typing import Anyfrom pathlib import Pathfrom loguru import logger-from flask import current_app-from flask.ctx import AppContextfrom ...config.llm_config import get_llmfrom ...config.search_config import get_searchfrom ...metrics.search_tracker import set_search_contextfrom ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystem-from ...utilities.search_utilities import extract_links_from_search_resultsfrom ...utilities.log_utils import log_for_research+from ...utilities.search_utilities import extract_links_from_search_results+from ...utilities.threading_utils import thread_context, thread_with_app_contextfrom ..models.database import calculate_duration, get_db_connectionfrom .socket_service import emit_to_subscribers@@ -48,15 +46,20 @@ def start_research_process(Returns:threading.Thread: The thread running the research"""- def _run_with_app_context(context: AppContext, *args: Any, **kwargs: Any) -> Any:- # Pass the current app context into the new thread so we can use it there.- with context:- return run_research_callback(*args, **kwargs)+ # Pass the app context to the thread.+ run_research_callback = thread_with_app_context(run_research_callback)# Start research process in a background threadthread = threading.Thread(- target=_run_with_app_context,- args=(current_app.app_context(), research_id, query, mode, active_research, termination_flags),+ target=run_research_callback,+ args=(+ thread_context(),+ research_id,+ query,+ mode,+ active_research,+ termination_flags,+ ),kwargs=kwargs,)thread.daemon = True@@ -197,8 +200,6 @@ def run_research_process(if "iteration" in metadata:shared_research_context["search_iteration"] = metadata["iteration"]- timestamp = datetime.utcnow().isoformat()-# Adjust progress based on research modeadjusted_progress = progress_percentif mode == "detailed" and metadata.get("phase") == "output_generation":@@ -264,7 +265,7 @@ def run_research_process(# Basic event dataevent_data = {"message": message, "progress": adjusted_progress}- emit_to_subscribers("research_progress", research_id, event_data)+ emit_to_subscribers("progress", research_id, event_data)except Exception:logger.exception("Socket emit error (non-critical)")diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex 8e283e962a..abb89e88a5 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -1,15 +1,18 @@-from threading import Lock+from functools import cache+from cachetools import LRUCache+from flask import Flask, current_appfrom flask_socketio import SocketIOfrom loguru import logger-from cachetools import cached, LRUCache-from flask import current_app, Flask++from ...utilities.threading_utils import thread_specific_cache# Socket subscription trackingsocket_subscriptions = {}-@cached(LRUCache(maxsize=1), lock=Lock())+# @thread_specific_cache(LRUCache(maxsize=1))+@cachedef get_socketio(app: Flask | None = None) -> SocketIO:"""Get the Socket.IO instance for the service.@@ -97,10 +100,10 @@ def handle_connect(request):logger.info(f"Client connected: {request.sid}")-def handle_disconnect(request):+def handle_disconnect(request, reason: str):"""Handle client disconnection"""try:- logger.info(f"Client disconnected: {request.sid}")+ logger.info(f"Client {request.sid} disconnected because: {reason}")# Clean up subscriptions for this clientglobal socket_subscriptionsfor research_id, subscribers in list(socket_subscriptions.items()):