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.

Refactor the websocket handling code.

Daniel Petti33f17514964c
diff --git a/app.py b/app.py
index 4bd358a594..6fc0ce44fa 100644
--- a/app.py
+++ b/app.py
@@ -3,7 +3,9 @@
Main entry point for the Local Deep Research application.
"""
-import local_deep_research
+import local_deep_research # noqa
+from local_deep_research.utilities.log_utils import config_logger # noqa
if __name__ == "__main__":
+ config_logger("ldr_web")
local_deep_research.main()
diff --git a/pyproject.toml b/pyproject.toml
index af01cfb38c..6e68eba1b6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -59,6 +59,7 @@ dependencies = [
"elasticsearch==8.14.0",
"methodtools>=0.4.7",
"loguru>=0.7.3",
+ "cachetools>=5.5.2",
"matplotlib>=3.10.3",
"pandas>=2.2.3",
"plotly>=6.0.1",
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.py
index da8d61eae9..d260662e5e 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
@@ -85,8 +85,6 @@ class JournalReputationFilter(BaseFilter):
if self.__engine is None:
raise JournalFilterError("SearXNG initialization failed.")
- self.__db_session = get_db_session()
-
@classmethod
def create_default(
cls, model: BaseChatModel | None = None, *, engine_name: str
@@ -203,7 +201,8 @@ class JournalReputationFilter(BaseFilter):
quality: The quality assessment for the journal.
"""
- journal = self.__db_session.query(Journal).filter_by(name=name).first()
+ db_session = get_db_session()
+ journal = db_session.query(Journal).filter_by(name=name).first()
if journal is not None:
journal.quality = quality
journal.quality_model = self.model.name
@@ -215,9 +214,9 @@ class JournalReputationFilter(BaseFilter):
quality_model=self.model.name,
quality_analysis_time=int(time.time()),
)
- self.__db_session.add(journal)
+ db_session.add(journal)
- self.__db_session.commit()
+ db_session.commit()
def __clean_journal_name(self, journal_name: str) -> str:
"""
@@ -268,7 +267,7 @@ class JournalReputationFilter(BaseFilter):
journal_name = self.__clean_journal_name(journal_name)
# Check the database first.
- journal = self.__db_session.query(Journal).filter_by(name=journal_name).first()
+ journal = get_db_session().query(Journal).filter_by(name=journal_name).first()
if (
journal is not None
and (time.time() - journal.quality_analysis_time)
diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.py
index 5f660809ff..544ee752e5 100644
--- a/src/local_deep_research/utilities/db_utils.py
+++ b/src/local_deep_research/utilities/db_utils.py
@@ -1,6 +1,7 @@
import os
-from functools import cache
from typing import Any, Dict
+from threading import Lock
+from cachetools import cached, LRUCache
from loguru import logger
from sqlalchemy import create_engine
@@ -13,7 +14,7 @@ DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "
DB_PATH = os.path.join(DATA_DIR, "ldr.db")
-@cache
+@cached(cache=LRUCache(maxsize=1), lock=Lock())
def get_db_session() -> Session:
"""
Returns:
@@ -24,7 +25,7 @@ def get_db_session() -> Session:
return session_class()
-@cache
+@cached(cache=LRUCache(maxsize=1), lock=Lock())
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 3a4e007a89..38de5f0fb7 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -2,13 +2,23 @@
Utilities for logging.
"""
+# Needed for loguru annotations
+from __future__ import annotations
+
import inspect
import logging
import sys
from pathlib import Path
+from functools import cache, wraps
+from typing import Callable, Any
+import loguru
from loguru import logger
+from ..web.database.models import ResearchLog
+from ..web.services.socket_service import emit_to_subscribers
+from .db_utils import get_db_session
+
_LOG_DIR = Path(__file__).parents[2] / "data" / "logs"
_LOG_DIR.mkdir(exist_ok=True)
"""
@@ -44,6 +54,61 @@ 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.
+
+ Args:
+ to_wrap: The function to wrap. Should take the research ID as the first parameter.
+
+ Returns:
+ The wrapped function.
+
+ """
+
+ @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)
+
+ return wrapped
+
+
+def database_sink(message: loguru.Message) -> None:
+ """
+ Handles configuring Loguru to save log messages to the database.
+
+ Args:
+ message: The log message to save.
+
+ """
+ record = message.record
+ research_id = record["extra"].get("research_id")
+
+ # Create a new database entry.
+ db_log = ResearchLog(
+ timestamp=record["time"],
+ message=str(message),
+ module=record["module"],
+ function=record["function"],
+ line_no=int(record["line"]),
+ level=record["level"].name,
+ research_id=research_id
+ )
+
+ # Save the entry to the database.
+ db_session = get_db_session()
+ 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 config_logger(name: str) -> None:
"""
Configures the default logger.
@@ -65,3 +130,7 @@ def config_logger(name: str) -> None:
retention="30 days",
compression="zip",
)
+ logger.add(database_sink)
+
+ # Add a special log level for milestones.
+ logger.level("milestone", no=26, color="#69348a")
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index cb42ee615a..9a9d980fcb 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -3,13 +3,6 @@ import sys
from loguru import logger
-from ..utilities.log_utils import config_logger
-
-if __name__ == "__main__":
- # Configure logging. Do this at the top to ensure we don't lose logs from
- # imports.
- config_logger("ldr_web")
-
from ..setup_data_dir import setup_data_dir
from ..utilities.db_utils import get_db_setting
from .app_factory import create_app
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index de44dfcfb2..a1731eb6bc 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -11,12 +11,12 @@ from flask import (
send_from_directory,
url_for,
)
-from flask_socketio import SocketIO
from flask_wtf.csrf import CSRFProtect
from loguru import logger
from ..utilities.log_utils import InterceptHandler
from .models.database import DB_PATH, init_db
+from .services.socket_service import get_socketio
def create_app():
@@ -65,26 +65,12 @@ def create_app():
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = False
- # Initialize extensions
- socketio = SocketIO(
- app,
- cors_allowed_origins="*",
- async_mode="threading",
- path="/research/socket.io",
- logger=False,
- engineio_logger=False,
- ping_timeout=20,
- ping_interval=5,
- )
-
# Initialize the database
create_database(app)
init_db()
# Register socket service
- from .services.socket_service import set_socketio
-
- set_socketio(socketio)
+ socketio = get_socketio(app)
# Apply middleware
apply_middleware(app)
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 74e039e8bc..2df2ee3cf3 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -2,7 +2,7 @@ from loguru import logger
from sqlalchemy import inspect
from ..services.settings_manager import SettingsManager
-from .models import Base, Journal, Setting
+from .models import Base, Journal, Setting, ResearchLog
def import_default_settings_file(db_session):
@@ -50,6 +50,10 @@ def run_migrations(engine, db_session=None):
logger.info("Creating journals table.")
Base.metadata.create_all(engine, tables=[Journal.__table__])
+ if not inspector.has_table(ResearchLog.__tablename__):
+ logger.info("Creating research logs table.")
+ Base.metadata.create_all(engine, tables=[ResearchLog.__table__])
+
# Import existing settings from files
if db_session:
import_default_settings_file(db_session)
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.py
index c151a68926..4b0fe9da1e 100644
--- a/src/local_deep_research/web/database/models.py
+++ b/src/local_deep_research/web/database/models.py
@@ -61,6 +61,28 @@ class Research(Base):
)
+class ResearchLog(Base):
+ __tablename__ = "app_logs"
+
+ id = Column(Integer, Sequence("reseach_log_id_seq"), primary_key=True, index=True)
+
+ timestamp = Column(DateTime, server_default=func.now(), nullable=False)
+ message = Column(Text, nullable=False)
+ # Module that the log message came from.
+ module = Column(Text, nullable=False)
+ # Function that the log message came from.
+ function = Column(Text, nullable=False)
+ # Line number that the log message came from.
+ line_no = Column(Integer, nullable=False)
+ # Log level.
+ level = Column(String(32), nullable=False)
+ research_id = Column(
+ Integer,
+ ForeignKey("research.id", ondelete="CASCADE"),
+ nullable=True,
+ )
+
+
class ResearchReport(Base):
__tablename__ = "research_report"
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index cc31f375a7..e32f171604 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -212,36 +212,6 @@ def calculate_duration(created_at_str, completed_at_str=None):
return None
-def add_log_to_db(research_id, message, log_type="info", progress=None, metadata=None):
- """
- Store a log entry in the database
-
- Args:
- research_id: ID of the research
- message: Log message text
- log_type: Type of log (info, error, milestone)
- progress: Progress percentage (0-100)
- metadata: Additional metadata as dictionary (will be stored as JSON)
- """
- try:
- timestamp = datetime.utcnow().isoformat()
- metadata_json = json.dumps(metadata) if metadata else None
-
- conn = get_db_connection()
- cursor = conn.cursor()
- cursor.execute(
- "INSERT INTO research_logs (research_id, timestamp, message, log_type, progress, metadata) "
- "VALUES (?, ?, ?, ?, ?, ?)",
- (research_id, timestamp, message, log_type, progress, metadata_json),
- )
- conn.commit()
- conn.close()
- return True
- except Exception:
- logger.exception("Error adding log to database")
- return False
-
-
def get_logs_for_research(research_id):
"""
Retrieve all logs for a specific research ID
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 75f33da80e..ff1b351741 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -15,7 +15,7 @@ from flask import (
)
from loguru import logger
-from ..models.database import add_log_to_db, calculate_duration, get_db_connection
+from ..models.database import calculate_duration, get_db_connection
from ..services.research_service import run_research_process, start_research_process
from ..utils.templates import render_template_with_defaults
@@ -324,13 +324,7 @@ def terminate_research(research_id):
active_research[research_id]["log"].append(log_entry)
# Add to database log
- add_log_to_db(
- research_id,
- termination_message,
- log_type="milestone",
- progress=current_progress,
- metadata={"phase": "termination"},
- )
+ logger.log("milestone", "Research ended: {}", termination_message)
# Update the log in the database (old way for backward compatibility)
cursor.execute(
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 9e62fb4abb..d891cffb7b 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -680,7 +680,9 @@ def api_get_available_models():
# Try to parse the response even if status code is not 200 to help with debugging
response_text = ollama_response.text
- logger.debug(f"Ollama API raw response: {response_text[:500]}...")
+ logger.debug(
+ f"Ollama API raw response: {response_text[:500]}..."
+ )
if ollama_response.status_code == 200:
try:
@@ -759,7 +761,9 @@ def api_get_available_models():
except requests.exceptions.RequestException as e:
logger.warning(f"Could not connect to Ollama API: {str(e)}")
# Fallback to default models if Ollama is not running
- logger.info("Using fallback Ollama models due to connection error")
+ logger.info(
+ "Using fallback Ollama models due to connection error"
+ )
ollama_models = [
{
"value": "llama3",
@@ -785,7 +789,9 @@ def api_get_available_models():
# Log some model names for debugging
if ollama_models:
model_names = [m["value"] for m in ollama_models[:5]]
- logger.info(f"Sample Ollama models: {', '.join(model_names)}")
+ logger.info(
+ f"Sample Ollama models: {', '.join(model_names)}"
+ )
except Exception:
logger.exception("Error getting Ollama models")
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index ab88f317d0..c68cfe3412 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -2,9 +2,12 @@ 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
@@ -12,7 +15,8 @@ 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 ..models.database import add_log_to_db, calculate_duration, get_db_connection
+from ...utilities.log_utils import log_for_research
+from ..models.database import calculate_duration, get_db_connection
from .socket_service import emit_to_subscribers
# Output directory for research results
@@ -44,10 +48,15 @@ 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)
+
# Start research process in a background thread
thread = threading.Thread(
- target=run_research_callback,
- args=(research_id, query, mode, active_research, termination_flags),
+ target=_run_with_app_context,
+ args=(current_app.app_context(), research_id, query, mode, active_research, termination_flags),
kwargs=kwargs,
)
thread.daemon = True
@@ -89,6 +98,7 @@ def _generate_report_path(query: str) -> Path:
)
+@log_for_research
def run_research_process(
research_id, query, mode, active_research, termination_flags, **kwargs
):
@@ -212,37 +222,11 @@ def run_research_process(
current_progress = active_research[research_id].get("progress", 0)
adjusted_progress = max(current_progress, adjusted_progress)
- log_entry = {
- "time": timestamp,
- "message": message,
- "progress": adjusted_progress,
- "metadata": metadata,
- }
-
# Update active research record
if research_id in active_research:
- active_research[research_id]["log"].append(log_entry)
if adjusted_progress is not None:
active_research[research_id]["progress"] = adjusted_progress
- # Determine log type for database storage
- log_type = "info"
- if metadata and metadata.get("phase"):
- phase = metadata.get("phase")
- if phase in ["complete", "iteration_complete"]:
- log_type = "milestone"
- elif phase == "error" or "error" in message.lower():
- log_type = "error"
-
- # Save logs to the database
- add_log_to_db(
- research_id,
- message,
- log_type=log_type,
- progress=adjusted_progress,
- metadata=metadata,
- )
-
# Update progress in the research_history table (for backward compatibility)
conn = get_db_connection()
cursor = conn.cursor()
@@ -267,7 +251,6 @@ def run_research_process(
except Exception:
current_log = []
- current_log.append(log_entry)
cursor.execute(
"UPDATE research_history SET progress_log = ? WHERE id = ?",
(json.dumps(current_log), research_id),
@@ -281,10 +264,6 @@ def run_research_process(
# Basic event data
event_data = {"message": message, "progress": adjusted_progress}
- # Add log entry in full format for detailed logging on client
- if metadata:
- event_data["log_entry"] = log_entry
-
emit_to_subscribers("research_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 10a2136573..8e283e962a 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -1,19 +1,34 @@
-import logging
+from threading import Lock
-# Initialize logger
-logger = logging.getLogger(__name__)
+from flask_socketio import SocketIO
+from loguru import logger
+from cachetools import cached, LRUCache
+from flask import current_app, Flask
-# Make this a module variable to be set by the Flask app on initialization
-socketio = None
# Socket subscription tracking
socket_subscriptions = {}
-def set_socketio(socket_instance):
- """Set the Socket.IO instance for the service."""
- global socketio
- socketio = socket_instance
- logger.info("Socket.IO instance attached to socket service")
+@cached(LRUCache(maxsize=1), lock=Lock())
+def get_socketio(app: Flask | None = None) -> SocketIO:
+ """
+ Get the Socket.IO instance for the service.
+
+ Args:
+ app: The flask app to use. If not specified, it will
+ default to the current app from the request context.
+
+ """
+ return SocketIO(
+ app if app is not None else current_app,
+ cors_allowed_origins="*",
+ async_mode="threading",
+ path="/research/socket.io",
+ logger=False,
+ engineio_logger=False,
+ ping_timeout=20,
+ ping_interval=5,
+ )
def emit_socket_event(event, data, room=None):
@@ -28,12 +43,7 @@ def emit_socket_event(event, data, room=None):
Returns:
bool: True if emission was successful, False otherwise
"""
- global socketio
-
- if not socketio:
- logger.error("Socket.IO not initialized when attempting to emit event")
- return False
-
+ socketio = get_socketio()
try:
# If room is specified, only emit to that room
if room:
@@ -59,12 +69,7 @@ def emit_to_subscribers(event_base, research_id, data):
Returns:
bool: True if emission was successful, False otherwise
"""
- global socketio
-
- if not socketio:
- logger.error("Socket.IO not initialized when attempting to emit to subscribers")
- return False
-
+ socketio = get_socketio()
try:
# Emit to the general channel for the research
full_event = f"{event_base}_{research_id}"
@@ -80,7 +85,7 @@ def emit_to_subscribers(event_base, research_id, data):
return True
except Exception as e:
- logger.error(
+ logger.exception(
f"Error emitting to subscribers for research {research_id}: {str(e)}"
)
return False