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.

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.py
index 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 logging
from typing import Dict
+from loguru import logger
+
from ...citation_handler import CitationHandler
from ...config.llm_config import get_llm
from ...config.search_config import get_search
from ...utilities.db_utils import get_db_setting
+from ...utilities.threading_utils import thread_context, thread_with_app_context
from ..filters.cross_engine_filter import CrossEngineFilter
from ..findings.repository import FindingsRepository
from ..questions.standard_question import StandardQuestionGenerator
from .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_context
def 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.py
index 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 os
from typing import Any, Dict
-from threading import Lock
-from cachetools import cached, LRUCache
+from cachetools import LRUCache
from loguru import logger
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
+from ..utilities.threading_utils import thread_specific_cache
from ..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.py
index 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 annotations
import inspect
import logging
import sys
+from functools import wraps
from pathlib import Path
-from functools import cache, wraps
-from typing import Callable, Any
+from typing import Any, Callable
import loguru
+from flask import g, has_app_context
from loguru import logger
from ..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.py
new file mode 100644
index 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 context
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 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.catch
def 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 needed
if check_migration_needed():
logger.info(
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 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.py
index 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 hashlib
import json
import threading
from datetime import datetime
-from typing import Any
from pathlib import Path
from loguru import logger
-from flask import current_app
-from flask.ctx import AppContext
from ...config.llm_config import get_llm
from ...config.search_config import get_search
from ...metrics.search_tracker import set_search_context
from ...report_generator import IntegratedReportGenerator
from ...search_system import AdvancedSearchSystem
-from ...utilities.search_utilities import extract_links_from_search_results
from ...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_context
from ..models.database import calculate_duration, get_db_connection
from .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 thread
thread = 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 mode
adjusted_progress = progress_percent
if mode == "detailed" and metadata.get("phase") == "output_generation":
@@ -264,7 +265,7 @@ def run_research_process(
# Basic event data
event_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.py
index 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_app
from flask_socketio import SocketIO
from loguru import logger
-from cachetools import cached, LRUCache
-from flask import current_app, Flask
+
+from ...utilities.threading_utils import thread_specific_cache
# Socket subscription tracking
socket_subscriptions = {}
-@cached(LRUCache(maxsize=1), lock=Lock())
+# @thread_specific_cache(LRUCache(maxsize=1))
+@cache
def 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 client
global socket_subscriptions
for research_id, subscribers in list(socket_subscriptions.items()):