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.

style: format code and update gitignore

hashedviking4df57b48c514
diff --git a/.gitignore b/.gitignore
index 0f7129ce9d..51782775ea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,7 @@ __pycache__/
*$py.class
*.so
.Python
+.python-version
build/
develop-eggs/
dist/
@@ -26,6 +27,7 @@ venv/
ENV/
env/
.env
+.pdm*
# IDE
.idea/
diff --git a/src/local_deep_research/__init__.py b/src/local_deep_research/__init__.py
index a8fb6fc4e2..80d922c0f0 100644
--- a/src/local_deep_research/__init__.py
+++ b/src/local_deep_research/__init__.py
@@ -10,28 +10,37 @@ __version__ = "0.1.0"
# Initialize configuration on module import
from .utilties.setup_utils import setup_user_directories
+
# Create reexport functions to avoid circular imports
def get_llm(*args, **kwargs):
"""Get a language model instance based on settings."""
from .config.llm_config import get_llm as _get_llm
+
return _get_llm(*args, **kwargs)
+
def get_search(*args, **kwargs):
"""Get a search engine instance based on settings."""
from .config.search_config import get_search as _get_search
+
return _get_search(*args, **kwargs)
+
def get_report_generator(*args, **kwargs):
"""Get a report generator instance."""
from .report_generator import IntegratedReportGenerator
+
return IntegratedReportGenerator(*args, **kwargs)
+
# Define a function to import AdvancedSearchSystem to avoid circular imports
def get_advanced_search_system(*args, **kwargs):
"""Get an AdvancedSearchSystem instance."""
from .search_system import AdvancedSearchSystem
+
return AdvancedSearchSystem(*args, **kwargs)
+
# Lazy import API functions to avoid circular imports
def _import_api():
from .api import (
@@ -41,6 +50,7 @@ def _import_api():
get_available_search_engines,
quick_summary,
)
+
return {
"analyze_documents": analyze_documents,
"generate_report": generate_report,
@@ -49,6 +59,7 @@ def _import_api():
"quick_summary": quick_summary,
}
+
# Export it
__all__ = [
"get_advanced_search_system",
diff --git a/src/local_deep_research/__main__.py b/src/local_deep_research/__main__.py
index 10520ce408..727be2b18a 100644
--- a/src/local_deep_research/__main__.py
+++ b/src/local_deep_research/__main__.py
@@ -4,10 +4,13 @@ This avoids circular imports by directly importing the main function after
the package is fully loaded.
"""
+
def main():
# Only import main after the whole package has been initialized
from .main import main as main_func
+
main_func()
+
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/src/local_deep_research/api/__init__.py b/src/local_deep_research/api/__init__.py
index f02b6a34b7..14c04fefb9 100644
--- a/src/local_deep_research/api/__init__.py
+++ b/src/local_deep_research/api/__init__.py
@@ -4,11 +4,11 @@ API module for programmatic access to Local Deep Research functionality.
"""
from .research_functions import (
- quick_summary,
- generate_report,
analyze_documents,
+ generate_report,
+ get_available_collections,
get_available_search_engines,
- get_available_collections
+ quick_summary,
)
__all__ = [
@@ -16,5 +16,5 @@ __all__ = [
"generate_report",
"analyze_documents",
"get_available_search_engines",
- "get_available_collections"
-]
\ No newline at end of file
+ "get_available_collections",
+]
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.py
index 01575516d3..668284c670 100644
--- a/src/local_deep_research/api/research_functions.py
+++ b/src/local_deep_research/api/research_functions.py
@@ -9,9 +9,9 @@ from typing import Any, Callable, Dict, Optional
import toml
+from .. import get_report_generator # Use the lazy import function
from ..config.llm_config import get_llm
from ..config.search_config import get_search
-from .. import get_report_generator # Use the lazy import function
from ..search_system import AdvancedSearchSystem
from ..utilties.search_utilities import remove_think_tags
@@ -178,9 +178,7 @@ def generate_report(
initial_findings = system.analyze_topic(query)
# Generate the structured report
- report_generator = get_report_generator(
- searches_per_section=searches_per_section
- )
+ report_generator = get_report_generator(searches_per_section=searches_per_section)
report_generator.model = llm # Ensure the model is set on the report generator too
report = report_generator.generate_report(initial_findings, query)
diff --git a/src/local_deep_research/app.py b/src/local_deep_research/app.py
index a44000dc57..4f0f7d992c 100644
--- a/src/local_deep_research/app.py
+++ b/src/local_deep_research/app.py
@@ -5,4 +5,4 @@ Main entry point for the Local Deep Research application.
from src.local_deep_research.web.app import main
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index 9fd2f66b4a..d9732ddc6b 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -19,7 +19,7 @@ SEARCH_SNIPPETS_ONLY = settings.search.snippets_only
def get_search(search_tool=None, llm_instance=None):
"""
Helper function to get search engine
-
+
Args:
search_tool: Override the search tool setting (e.g. searxng, wikipedia)
llm_instance: Override the LLM instance
@@ -44,17 +44,21 @@ def get_search(search_tool=None, llm_instance=None):
"search_language": settings.search.search_language,
"max_filtered_results": settings.search.max_filtered_results,
}
-
+
# Log parameters for debugging
- logger.info(f"Search config: tool={tool}, max_results={params['max_results']}, time_period={params['time_period']}")
+ logger.info(
+ f"Search config: tool={tool}, max_results={params['max_results']}, time_period={params['time_period']}"
+ )
# Create search engine
search_engine = factory_get_search(**params)
-
+
# Log the created engine type
if search_engine:
- logger.info(f"Successfully created search engine of type: {type(search_engine).__name__}")
+ logger.info(
+ f"Successfully created search engine of type: {type(search_engine).__name__}"
+ )
else:
logger.error(f"Failed to create search engine for tool: {tool}")
-
+
return search_engine
diff --git a/src/local_deep_research/main.py b/src/local_deep_research/main.py
index e9f1d5b998..7acc707d26 100644
--- a/src/local_deep_research/main.py
+++ b/src/local_deep_research/main.py
@@ -1,8 +1,8 @@
from typing import Dict
-from .config.config_files import settings
# from .report_generator import IntegratedReportGenerator
-from . import get_report_generator, get_advanced_search_system
+from . import get_advanced_search_system, get_report_generator
+from .config.config_files import settings
def print_report(report: Dict):
@@ -32,6 +32,7 @@ def print_report(report: Dict):
def get_report_generator_instance():
return get_report_generator()
+
# report_generator = IntegratedReportGenerator()
report_generator = None # Will be initialized when needed
@@ -106,7 +107,7 @@ def main():
global report_generator
if report_generator is None:
report_generator = get_report_generator()
-
+
final_report = report_generator.generate_report(results, query)
print("\n=== RESEARCH REPORT ===")
print_report(final_report)
diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.py
index 928fd1c610..8399034ce4 100644
--- a/src/local_deep_research/report_generator.py
+++ b/src/local_deep_research/report_generator.py
@@ -1,11 +1,12 @@
+import importlib
from typing import Dict, List
# Fix circular import by importing directly from source modules
from .config.llm_config import get_llm
+from .search_system import AdvancedSearchSystem
+
# from . import utilties
from .utilties import search_utilities
-from .search_system import AdvancedSearchSystem
-import importlib
class IntegratedReportGenerator:
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index eb21fa8da2..d06d07424c 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -3,10 +3,11 @@ import os
from datetime import datetime
from typing import Callable, Dict, List
-# Fix circular import - import directly from the config module, not from parent package
-from .config.llm_config import get_llm
from .citation_handler import CitationHandler
from .config.config_files import get_config_dir, settings
+
+# Fix circular import - import directly from the config module, not from parent package
+from .config.llm_config import get_llm
from .config.search_config import get_search
from .utilties.enums import KnowledgeAccumulationApproach
from .utilties.search_utilities import (
@@ -34,18 +35,20 @@ class AdvancedSearchSystem:
self.citation_handler = CitationHandler(self.model)
self.progress_callback = None
self.all_links_of_system = list()
-
+
# Log the specific model and search engine for debugging
- model_name = getattr(settings.llm, 'model', 'unknown')
- search_tool = getattr(settings.search, 'tool', 'unknown')
+ model_name = getattr(settings.llm, "model", "unknown")
+ search_tool = getattr(settings.search, "tool", "unknown")
logger.info(f"AdvancedSearchSystem initialized with LLM model: {model_name}")
-
+
# Get search engine type for better logging
search_engine_type = "None"
if self.search is not None:
search_engine_type = type(self.search).__name__
-
- logger.info(f"AdvancedSearchSystem using search engine: {search_tool} (Type: {search_engine_type})")
+
+ logger.info(
+ f"AdvancedSearchSystem using search engine: {search_tool} (Type: {search_engine_type})"
+ )
# Check if search is available, log warning if not
if self.search is None:
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 8a213c5136..6b3de24371 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -1,49 +1,52 @@
import logging
import os
+
from sqlalchemy import create_engine, inspect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
-from .models import Base, Setting, SettingType
from ..services.settings_manager import SettingsManager
+from .models import Base, Setting, SettingType
# Setup logging
logger = logging.getLogger(__name__)
+
def run_migrations(engine, db_session=None):
"""
Run any necessary database migrations
-
+
Args:
engine: SQLAlchemy engine
db_session: Optional SQLAlchemy session
"""
# Create all tables if they don't exist
inspector = inspect(engine)
- if not inspector.has_table('settings'):
+ if not inspector.has_table("settings"):
logger.info("Creating settings table")
Base.metadata.create_all(engine, tables=[Setting.__table__])
-
+
# Import existing settings from files
if db_session:
migrate_settings_from_files(db_session)
+
def migrate_settings_from_files(db_session):
"""
Migrate settings from config files to database
-
+
Args:
db_session: SQLAlchemy session
"""
# Check if settings table is empty
settings_count = db_session.query(Setting).count()
-
+
if settings_count == 0:
logger.info("Settings table is empty, importing from files")
-
+
# Create settings manager
settings_manager = SettingsManager(db_session)
-
+
# Import all settings from files
try:
success = settings_manager.import_from_file()
@@ -54,17 +57,20 @@ def migrate_settings_from_files(db_session):
except Exception as e:
logger.error(f"Error importing settings from files: {e}")
else:
- logger.info(f"Settings table already has {settings_count} rows, skipping import")
+ logger.info(
+ f"Settings table already has {settings_count} rows, skipping import"
+ )
+
def setup_predefined_settings(db_session):
"""
Set up predefined settings with UI metadata
-
+
Args:
db_session: SQLAlchemy session
"""
settings_manager = SettingsManager(db_session)
-
+
# Define standard UI settings for LLM
llm_settings = [
{
@@ -76,13 +82,19 @@ def setup_predefined_settings(db_session):
"options": [
{"value": "gpt-4o", "label": "GPT-4o (OpenAI)"},
{"value": "gpt-3.5-turbo", "label": "GPT-3.5 Turbo (OpenAI)"},
- {"value": "claude-3-5-sonnet-latest", "label": "Claude 3.5 Sonnet (Anthropic)"},
- {"value": "claude-3-opus-20240229", "label": "Claude 3 Opus (Anthropic)"},
+ {
+ "value": "claude-3-5-sonnet-latest",
+ "label": "Claude 3.5 Sonnet (Anthropic)",
+ },
+ {
+ "value": "claude-3-opus-20240229",
+ "label": "Claude 3 Opus (Anthropic)",
+ },
{"value": "llama3", "label": "Llama 3 (Meta)"},
{"value": "mistral", "label": "Mistral (Mistral AI)"},
- {"value": "mixtral", "label": "Mixtral (Mistral AI)"}
+ {"value": "mixtral", "label": "Mixtral (Mistral AI)"},
],
- "value": "gpt-3.5-turbo"
+ "value": "gpt-3.5-turbo",
},
{
"key": "llm.provider",
@@ -96,9 +108,9 @@ def setup_predefined_settings(db_session):
{"value": "ollama", "label": "Ollama (Local)"},
{"value": "lmstudio", "label": "LM Studio (Local)"},
{"value": "vllm", "label": "vLLM (Local)"},
- {"value": "openai_endpoint", "label": "Custom OpenAI-compatible API"}
+ {"value": "openai_endpoint", "label": "Custom OpenAI-compatible API"},
],
- "value": "openai"
+ "value": "openai",
},
{
"key": "llm.temperature",
@@ -109,7 +121,7 @@ def setup_predefined_settings(db_session):
"min_value": 0.0,
"max_value": 1.0,
"step": 0.05,
- "value": 0.7
+ "value": 0.7,
},
{
"key": "llm.max_tokens",
@@ -119,10 +131,10 @@ def setup_predefined_settings(db_session):
"ui_element": "number",
"min_value": 100,
"max_value": 4096,
- "value": 1024
- }
+ "value": 1024,
+ },
]
-
+
# Define standard UI settings for Search
search_settings = [
{
@@ -136,9 +148,9 @@ def setup_predefined_settings(db_session):
{"value": "google_pse", "label": "Google Programmable Search Engine"},
{"value": "searxng", "label": "SearXNG (Self-hosted)"},
{"value": "serpapi", "label": "SerpAPI (Google)"},
- {"value": "duckduckgo", "label": "DuckDuckGo"}
+ {"value": "duckduckgo", "label": "DuckDuckGo"},
],
- "value": "auto"
+ "value": "auto",
},
{
"key": "search.max_results",
@@ -148,7 +160,7 @@ def setup_predefined_settings(db_session):
"ui_element": "number",
"min_value": 3,
"max_value": 50,
- "value": 10
+ "value": 10,
},
{
"key": "search.region",
@@ -162,9 +174,9 @@ def setup_predefined_settings(db_session):
{"value": "fr", "label": "France"},
{"value": "de", "label": "Germany"},
{"value": "jp", "label": "Japan"},
- {"value": "wt-wt", "label": "No Region (Worldwide)"}
+ {"value": "wt-wt", "label": "No Region (Worldwide)"},
],
- "value": "us"
+ "value": "us",
},
{
"key": "search.time_period",
@@ -177,9 +189,9 @@ def setup_predefined_settings(db_session):
{"value": "w", "label": "Past week"},
{"value": "m", "label": "Past month"},
{"value": "y", "label": "Past year"},
- {"value": "all", "label": "All time"}
+ {"value": "all", "label": "All time"},
],
- "value": "all"
+ "value": "all",
},
{
"key": "search.snippets_only",
@@ -187,10 +199,10 @@ def setup_predefined_settings(db_session):
"description": "Only retrieve snippets instead of full search results",
"category": "search_parameters",
"ui_element": "checkbox",
- "value": True
- }
+ "value": True,
+ },
]
-
+
# Define standard UI settings for Report generation
report_settings = [
{
@@ -201,7 +213,7 @@ def setup_predefined_settings(db_session):
"ui_element": "number",
"min_value": 1,
"max_value": 5,
- "value": 2
+ "value": 2,
},
{
"key": "report.enable_fact_checking",
@@ -209,7 +221,7 @@ def setup_predefined_settings(db_session):
"description": "Enable fact checking for report contents",
"category": "report_parameters",
"ui_element": "checkbox",
- "value": True
+ "value": True,
},
{
"key": "report.detailed_citations",
@@ -217,10 +229,10 @@ def setup_predefined_settings(db_session):
"description": "Include detailed citations in reports",
"category": "report_parameters",
"ui_element": "checkbox",
- "value": True
- }
+ "value": True,
+ },
]
-
+
# Define standard UI settings for App
app_settings = [
{
@@ -231,7 +243,7 @@ def setup_predefined_settings(db_session):
"ui_element": "number",
"min_value": 1,
"max_value": 5,
- "value": 2
+ "value": 2,
},
{
"key": "app.questions_per_iteration",
@@ -241,7 +253,7 @@ def setup_predefined_settings(db_session):
"ui_element": "number",
"min_value": 1,
"max_value": 10,
- "value": 3
+ "value": 3,
},
{
"key": "app.enable_notifications",
@@ -249,7 +261,7 @@ def setup_predefined_settings(db_session):
"description": "Enable browser notifications for research events",
"category": "app_parameters",
"ui_element": "checkbox",
- "value": True
+ "value": True,
},
{
"key": "app.theme",
@@ -260,23 +272,23 @@ def setup_predefined_settings(db_session):
"options": [
{"value": "dark", "label": "Dark"},
{"value": "light", "label": "Light"},
- {"value": "system", "label": "System Default"}
+ {"value": "system", "label": "System Default"},
],
- "value": "dark"
- }
+ "value": "dark",
+ },
]
-
+
# Ensure these predefined settings exist in the database
# This will update existing settings with the same key
all_settings = llm_settings + search_settings + report_settings + app_settings
-
+
# Add/update each setting
for setting_dict in all_settings:
try:
# Convert to correct type based on key prefix
setting_type = None
key = setting_dict.get("key", "")
-
+
if key.startswith("llm."):
setting_type = SettingType.LLM
elif key.startswith("search."):
@@ -285,29 +297,33 @@ def setup_predefined_settings(db_session):
setting_type = SettingType.REPORT
elif key.startswith("app."):
setting_type = SettingType.APP
-
+
# Skip if no valid type
if not setting_type:
logger.warning(f"Skipping setting {key} - unknown type")
continue
-
+
# Check if setting exists
existing = db_session.query(Setting).filter(Setting.key == key).first()
-
+
if existing:
# Update existing setting
logger.debug(f"Updating existing setting: {key}")
-
+
# Only update metadata, not the value (to preserve user settings)
existing.name = setting_dict.get("name", existing.name)
- existing.description = setting_dict.get("description", existing.description)
+ existing.description = setting_dict.get(
+ "description", existing.description
+ )
existing.category = setting_dict.get("category", existing.category)
- existing.ui_element = setting_dict.get("ui_element", existing.ui_element)
+ existing.ui_element = setting_dict.get(
+ "ui_element", existing.ui_element
+ )
existing.options = setting_dict.get("options", existing.options)
existing.min_value = setting_dict.get("min_value", existing.min_value)
existing.max_value = setting_dict.get("max_value", existing.max_value)
existing.step = setting_dict.get("step", existing.step)
-
+
# Only set value if it's not already set
if existing.value is None and "value" in setting_dict:
existing.value = setting_dict["value"]
@@ -318,7 +334,9 @@ def setup_predefined_settings(db_session):
key=key,
value=setting_dict.get("value"),
type=setting_type,
- name=setting_dict.get("name", key.split('.')[-1].replace('_', ' ').title()),
+ name=setting_dict.get(
+ "name", key.split(".")[-1].replace("_", " ").title()
+ ),
description=setting_dict.get("description", f"Setting for {key}"),
category=setting_dict.get("category"),
ui_element=setting_dict.get("ui_element", "text"),
@@ -327,16 +345,16 @@ def setup_predefined_settings(db_session):
max_value=setting_dict.get("max_value"),
step=setting_dict.get("step"),
visible=setting_dict.get("visible", True),
- editable=setting_dict.get("editable", True)
+ editable=setting_dict.get("editable", True),
)
db_session.add(setting)
-
+
# Commit after each successful setting
db_session.commit()
-
+
except Exception as e:
logger.error(f"Error ensuring setting {setting_dict.get('key')}: {e}")
db_session.rollback()
-
+
# Log completion
- logger.info("Predefined settings setup complete")
\ No newline at end of file
+ logger.info("Predefined settings setup complete")
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.py
index 773d0c8486..9cc227a48a 100644
--- a/src/local_deep_research/web/database/models.py
+++ b/src/local_deep_research/web/database/models.py
@@ -1,11 +1,20 @@
import datetime
import enum
import uuid
-from typing import Dict, Any, Optional
+from typing import Any, Dict, Optional
from sqlalchemy import (
- Boolean, Column, DateTime, Enum, Float, ForeignKey,
- Integer, String, Text, JSON, UniqueConstraint
+ JSON,
+ Boolean,
+ Column,
+ DateTime,
+ Enum,
+ Float,
+ ForeignKey,
+ Integer,
+ String,
+ Text,
+ UniqueConstraint,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
@@ -13,10 +22,12 @@ from sqlalchemy.sql import func
Base = declarative_base()
+
class ResearchMode(enum.Enum):
QUICK = "quick"
DETAILED = "detailed"
+
class ResearchStatus(enum.Enum):
PENDING = "pending"
IN_PROGRESS = "in_progress"
@@ -24,30 +35,44 @@ class ResearchStatus(enum.Enum):
FAILED = "failed"
CANCELLED = "cancelled"
+
class Research(Base):
__tablename__ = "research"
id = Column(Integer, primary_key=True, index=True)
query = Column(String, nullable=False)
- status = Column(Enum(ResearchStatus), default=ResearchStatus.PENDING, nullable=False)
+ status = Column(
+ Enum(ResearchStatus), default=ResearchStatus.PENDING, nullable=False
+ )
mode = Column(Enum(ResearchMode), default=ResearchMode.QUICK, nullable=False)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
- updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
+ updated_at = Column(
+ DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
+ )
progress = Column(Float, default=0.0, nullable=False)
start_time = Column(DateTime, nullable=True)
end_time = Column(DateTime, nullable=True)
error_message = Column(Text, nullable=True)
-
# Relationships
- logs = relationship("ResearchLog", back_populates="research", cascade="all, delete-orphan")
- report = relationship("ResearchReport", back_populates="research", uselist=False, cascade="all, delete-orphan")
+ logs = relationship(
+ "ResearchLog", back_populates="research", cascade="all, delete-orphan"
+ )
+ report = relationship(
+ "ResearchReport",
+ back_populates="research",
+ uselist=False,
+ cascade="all, delete-orphan",
+ )
+
class ResearchLog(Base):
__tablename__ = "research_log"
id = Column(Integer, primary_key=True, index=True)
- research_id = Column(Integer, ForeignKey("research.id", ondelete="CASCADE"), nullable=False)
+ research_id = Column(
+ Integer, ForeignKey("research.id", ondelete="CASCADE"), nullable=False
+ )
message = Column(Text, nullable=False)
timestamp = Column(DateTime, server_default=func.now(), nullable=False)
level = Column(String, default="info", nullable=False) # info, warning, error
@@ -56,29 +81,42 @@ class ResearchLog(Base):
# Relationships
research = relationship("Research", back_populates="logs")
+
class ResearchReport(Base):
__tablename__ = "research_report"
id = Column(Integer, primary_key=True, index=True)
- research_id = Column(Integer, ForeignKey("research.id", ondelete="CASCADE"), nullable=False, unique=True)
+ research_id = Column(
+ Integer,
+ ForeignKey("research.id", ondelete="CASCADE"),
+ nullable=False,
+ unique=True,
+ )
content = Column(Text, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
- updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
- report_metadata = Column(JSON, nullable=True) # Additional metadata about the report
+ updated_at = Column(
+ DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
+ )
+ report_metadata = Column(
+ JSON, nullable=True
+ ) # Additional metadata about the report
# Relationships
research = relationship("Research", back_populates="report")
+
class SettingType(enum.Enum):
APP = "app"
LLM = "llm"
SEARCH = "search"
REPORT = "report"
+
class Setting(Base):
"""Database model for storing settings"""
+
__tablename__ = "settings"
-
+
id = Column(Integer, primary_key=True, index=True)
key = Column(String(255), nullable=False, unique=True, index=True)
value = Column(JSON, nullable=True)
@@ -94,8 +132,8 @@ class Setting(Base):
visible = Column(Boolean, default=True, nullable=False)
editable = Column(Boolean, default=True, nullable=False)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
- updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
-
- __table_args__ = (
- UniqueConstraint('key', name='uix_settings_key'),
- )
\ No newline at end of file
+ updated_at = Column(
+ DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
+ )
+
+ __table_args__ = (UniqueConstraint("key", name="uix_settings_key"),)
diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.py
index 6c22ad42c5..dbe664214f 100644
--- a/src/local_deep_research/web/models/database.py
+++ b/src/local_deep_research/web/models/database.py
@@ -1,9 +1,9 @@
import json
import logging
+import os
import sqlite3
import traceback
from datetime import datetime
-import os
# Initialize logger
logger = logging.getLogger(__name__)
@@ -11,6 +11,7 @@ logger = logging.getLogger(__name__)
# Database path
DB_PATH = "research_history.db"
+
def get_db_connection():
"""
Get a connection to the SQLite database.
@@ -19,6 +20,7 @@ def get_db_connection():
conn = sqlite3.connect(DB_PATH)
return conn
+
def init_db():
"""Initialize the database with necessary tables."""
conn = get_db_connection()
@@ -74,7 +76,7 @@ def init_db():
if "progress" not in columns:
print("Adding missing 'progress' column to research_history table")
cursor.execute("ALTER TABLE research_history ADD COLUMN progress INTEGER")
-
+
# Check if the title column exists, add it if missing
if "title" not in columns:
print("Adding missing 'title' column to research_history table")
@@ -86,15 +88,16 @@ def init_db():
conn.commit()
conn.close()
+
def calculate_duration(created_at_str, completed_at_str=None):
"""
Calculate duration in seconds between created_at timestamp and completed_at or now.
Handles various timestamp formats and returns None if calculation fails.
-
+
Args:
created_at_str: The start timestamp
completed_at_str: Optional end timestamp, defaults to current time if None
-
+
Returns:
Duration in seconds or None if calculation fails
"""
@@ -110,10 +113,14 @@ def calculate_duration(created_at_str, completed_at_str=None):
else: # Older format without T
# Try different formats
try:
- end_time = datetime.strptime(completed_at_str, "%Y-%m-%d %H:%M:%S.%f")
+ end_time = datetime.strptime(
+ completed_at_str, "%Y-%m-%d %H:%M:%S.%f"
+ )
except ValueError:
try:
- end_time = datetime.strptime(completed_at_str, "%Y-%m-%d %H:%M:%S")
+ end_time = datetime.strptime(
+ completed_at_str, "%Y-%m-%d %H:%M:%S"
+ )
except ValueError:
# Last resort fallback
end_time = datetime.fromisoformat(
@@ -123,9 +130,12 @@ def calculate_duration(created_at_str, completed_at_str=None):
print(f"Error parsing completed_at timestamp: {str(e)}")
try:
from dateutil import parser
+
end_time = parser.parse(completed_at_str)
except Exception:
- print(f"Fallback parsing also failed for completed_at: {completed_at_str}")
+ print(
+ f"Fallback parsing also failed for completed_at: {completed_at_str}"
+ )
# Fall back to current time
end_time = datetime.utcnow()
else:
@@ -154,6 +164,7 @@ def calculate_duration(created_at_str, completed_at_str=None):
# Fallback method if parsing fails
try:
from dateutil import parser
+
start_time = parser.parse(created_at_str)
except Exception:
print(f"Fallback parsing also failed for created_at: {created_at_str}")
@@ -165,9 +176,10 @@ def calculate_duration(created_at_str, completed_at_str=None):
return int((end_time - start_time).total_seconds())
except Exception as e:
print(f"Error calculating duration: {str(e)}")
-
+
return None
+
def add_log_to_db(research_id, message, log_type="info", progress=None, metadata=None):
"""
Store a log entry in the database
@@ -198,6 +210,7 @@ def add_log_to_db(research_id, message, log_type="info", progress=None, metadata
print(traceback.format_exc())
return False
+
def get_logs_for_research(research_id):
"""
Retrieve all logs for a specific research ID
@@ -245,4 +258,4 @@ def get_logs_for_research(research_id):
except Exception as e:
print(f"Error retrieving logs from database: {str(e)}")
print(traceback.format_exc())
- return []
\ No newline at end of file
+ return []
diff --git a/src/local_deep_research/web/models/settings.py b/src/local_deep_research/web/models/settings.py
index eda18b154b..2292f63994 100644
--- a/src/local_deep_research/web/models/settings.py
+++ b/src/local_deep_research/web/models/settings.py
@@ -3,15 +3,19 @@ from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field, field_validator
+
class SettingType(str, Enum):
"""Types of settings in the system"""
+
APP = "app"
LLM = "llm"
SEARCH = "search"
REPORT = "report"
+
class BaseSetting(BaseModel):
"""Base model for all settings"""
+
key: str
value: Any
type: SettingType
@@ -25,56 +29,66 @@ class BaseSetting(BaseModel):
step: Optional[float] = None # For sliders
visible: bool = True
editable: bool = True
-
+
class Config:
from_attributes = True
+
class LLMSetting(BaseSetting):
"""LLM-specific settings"""
+
type: SettingType = SettingType.LLM
-
- @field_validator('key')
+
+ @field_validator("key")
def validate_llm_key(cls, v):
# Ensure LLM settings follow a convention
- if not v.startswith('llm.'):
- return f'llm.{v}'
+ if not v.startswith("llm."):
+ return f"llm.{v}"
return v
+
class SearchSetting(BaseSetting):
"""Search-specific settings"""
+
type: SettingType = SettingType.SEARCH
-
- @field_validator('key')
+
+ @field_validator("key")
def validate_search_key(cls, v):
# Ensure search settings follow a convention
- if not v.startswith('search.'):
- return f'search.{v}'
+ if not v.startswith("search."):
+ return f"search.{v}"
return v
+
class ReportSetting(BaseSetting):
"""Report generation settings"""
+
type: SettingType = SettingType.REPORT
-
- @field_validator('key')
+
+ @field_validator("key")
def validate_report_key(cls, v):
# Ensure report settings follow a convention
- if not v.startswith('report.'):
- return f'report.{v}'
+ if not v.startswith("report."):
+ return f"report.{v}"
return v
+
class AppSetting(BaseSetting):
"""Application-wide settings"""
+
type: SettingType = SettingType.APP
-
- @field_validator('key')
+
+ @field_validator("key")
def validate_app_key(cls, v):
# Ensure app settings follow a convention
- if not v.startswith('app.'):
- return f'app.{v}'
+ if not v.startswith("app."):
+ return f"app.{v}"
return v
+
class SettingsGroup(BaseModel):
"""A group of related settings"""
+
name: str
description: Optional[str] = None
- settings: List[BaseSetting]
\ No newline at end of file
+ settings: List[BaseSetting]
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 249b6e91fb..33358e7c79 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -1,52 +1,56 @@
-import os
+import importlib
import json
-from flask import Blueprint, jsonify, request, current_app, send_from_directory
-from ..services.research_service import start_research, get_research_status, cancel_research
-from ..services.resource_service import get_resources_for_research
+import logging
+import os
+from pathlib import Path
+
+import requests
+from flask import Blueprint, current_app, jsonify, request, send_from_directory
+
+from ..models.database import get_db
from ..models.research import Research
from ..models.task import Task
-from ..models.database import get_db
-import requests
-import importlib
-from pathlib import Path
-import logging
+from ..services.research_service import (
+ cancel_research,
+ get_research_status,
+ start_research,
+)
+from ..services.resource_service import get_resources_for_research
# Create blueprint
-api_bp = Blueprint('api', __name__)
+api_bp = Blueprint("api", __name__)
logger = logging.getLogger(__name__)
+
# API Routes
-@api_bp.route('/start', methods=['POST'])
+@api_bp.route("/start", methods=["POST"])
def api_start_research():
"""
Start a new research process
"""
data = request.json
- query = data.get('query', '')
- mode = data.get('mode', 'quick')
-
+ query = data.get("query", "")
+ mode = data.get("mode", "quick")
+
if not query:
- return jsonify({
- 'status': 'error',
- 'message': 'Query is required'
- }), 400
-
+ return jsonify({"status": "error", "message": "Query is required"}), 400
+
try:
# Start research process and get ID
research_id = start_research(query, mode)
-
- return jsonify({
- 'status': 'success',
- 'message': 'Research started successfully',
- 'research_id': research_id
- })
+
+ return jsonify(
+ {
+ "status": "success",
+ "message": "Research started successfully",
+ "research_id": research_id,
+ }
+ )
except Exception as e:
- return jsonify({
- 'status': 'error',
- 'message': str(e)
- }), 500
+ return jsonify({"status": "error", "message": str(e)}), 500
+
-@api_bp.route('/status/<int:research_id>', methods=['GET'])
+@api_bp.route("/status/<int:research_id>", methods=["GET"])
def api_research_status(research_id):
"""
Get the status of a research process
@@ -55,157 +59,161 @@ def api_research_status(research_id):
status = get_research_status(research_id)
return jsonify(status)
except Exception as e:
- return jsonify({
- 'status': 'error',
- 'message': str(e)
- }), 500
+ return jsonify({"status": "error", "message": str(e)}), 500
+
-@api_bp.route('/terminate/<int:research_id>', methods=['POST'])
+@api_bp.route("/terminate/<int:research_id>", methods=["POST"])
def api_terminate_research(research_id):
"""
Terminate a research process
"""
try:
result = cancel_research(research_id)
- return jsonify({
- 'status': 'success',
- 'message': 'Research terminated',
- 'result': result
- })
+ return jsonify(
+ {"status": "success", "message": "Research terminated", "result": result}
+ )
except Exception as e:
- return jsonify({
- 'status': 'error',
- 'message': str(e)
- }), 500
+ return jsonify({"status": "error", "message": str(e)}), 500
-@api_bp.route('/resources/<int:research_id>', methods=['GET'])
+
+@api_bp.route("/resources/<int:research_id>", methods=["GET"])
def api_get_resources(research_id):
"""
Get resources for a specific research
"""
try:
resources = get_resources_for_research(research_id)
- return jsonify({
- 'status': 'success',
- 'resources': resources
- })
+ return jsonify({"status": "success", "resources": resources})
except Exception as e:
- return jsonify({
- 'status': 'error',
- 'message': str(e)
- }), 500
+ return jsonify({"status": "error", "message": str(e)}), 500
+
-@api_bp.route('/check/ollama_status', methods=['GET'])
+@api_bp.route("/check/ollama_status", methods=["GET"])
def check_ollama_status():
"""
Check if Ollama API is running
"""
try:
# Get Ollama URL from config
- llm_config = current_app.config.get('LLM_CONFIG', {})
- provider = llm_config.get('provider', 'ollama')
-
- if provider.lower() != 'ollama':
- return jsonify({
- 'running': True,
- 'message': f'Using provider: {provider}, not Ollama'
- })
-
+ llm_config = current_app.config.get("LLM_CONFIG", {})
+ provider = llm_config.get("provider", "ollama")
+
+ if provider.lower() != "ollama":
+ return jsonify(
+ {"running": True, "message": f"Using provider: {provider}, not Ollama"}
+ )
+
# Get Ollama API URL
- ollama_base_url = llm_config.get('ollama_base_url', 'http://localhost:11434')
-
+ ollama_base_url = llm_config.get("ollama_base_url", "http://localhost:11434")
+
# Check if Ollama is running
response = requests.get(f"{ollama_base_url}/api/tags", timeout=3)
-
+
if response.status_code == 200:
- return jsonify({
- 'running': True,
- 'message': 'Ollama service is running'
- })
+ return jsonify({"running": True, "message": "Ollama service is running"})
else:
- return jsonify({
- 'running': False,
- 'message': f'Ollama service returned status code: {response.status_code}'
- })
+ return jsonify(
+ {
+ "running": False,
+ "message": f"Ollama service returned status code: {response.status_code}",
+ }
+ )
except requests.exceptions.ConnectionError:
- return jsonify({
- 'running': False,
- 'message': 'Ollama service is not running or not accessible'
- })
+ return jsonify(
+ {
+ "running": False,
+ "message": "Ollama service is not running or not accessible",
+ }
+ )
except Exception as e:
logger.error(f"Error checking Ollama status: {str(e)}")
- return jsonify({
- 'running': False,
- 'message': f'Error checking Ollama: {str(e)}'
- })
+ return jsonify(
+ {"running": False, "message": f"Error checking Ollama: {str(e)}"}
+ )
-@api_bp.route('/check/ollama_model', methods=['GET'])
+
+@api_bp.route("/check/ollama_model", methods=["GET"])
def check_ollama_model():
"""
Check if the configured Ollama model is available
"""
try:
# Get Ollama configuration
- llm_config = current_app.config.get('LLM_CONFIG', {})
- provider = llm_config.get('provider', 'ollama')
-
- if provider.lower() != 'ollama':
- return jsonify({
- 'available': True,
- 'message': f'Using provider: {provider}, not Ollama'
- })
-
+ llm_config = current_app.config.get("LLM_CONFIG", {})
+ provider = llm_config.get("provider", "ollama")
+
+ if provider.lower() != "ollama":
+ return jsonify(
+ {
+ "available": True,
+ "message": f"Using provider: {provider}, not Ollama",
+ }
+ )
+
# Get model name and Ollama API URL
- model_name = llm_config.get('model', 'gemma3:12b')
- ollama_base_url = llm_config.get('ollama_base_url', 'http://localhost:11434')
-
+ model_name = llm_config.get("model", "gemma3:12b")
+ ollama_base_url = llm_config.get("ollama_base_url", "http://localhost:11434")
+
# Check if the model is available
response = requests.get(f"{ollama_base_url}/api/tags", timeout=5)
-
+
if response.status_code != 200:
- return jsonify({
- 'available': False,
- 'model': model_name,
- 'message': 'Could not access Ollama service'
- })
-
- models = response.json().get('models', [])
- model_exists = any(m.get('name') == model_name for m in models)
-
+ return jsonify(
+ {
+ "available": False,
+ "model": model_name,
+ "message": "Could not access Ollama service",
+ }
+ )
+
+ models = response.json().get("models", [])
+ model_exists = any(m.get("name") == model_name for m in models)
+
if model_exists:
- return jsonify({
- 'available': True,
- 'model': model_name,
- 'message': f'Model {model_name} is available'
- })
+ return jsonify(
+ {
+ "available": True,
+ "model": model_name,
+ "message": f"Model {model_name} is available",
+ }
+ )
else:
- return jsonify({
- 'available': False,
- 'model': model_name,
- 'message': f'Model {model_name} is not available'
- })
+ return jsonify(
+ {
+ "available": False,
+ "model": model_name,
+ "message": f"Model {model_name} is not available",
+ }
+ )
except Exception as e:
logger.error(f"Error checking Ollama model: {str(e)}")
- return jsonify({
- 'available': False,
- 'model': llm_config.get('model', 'gemma3:12b'),
- 'message': f'Error checking model: {str(e)}'
- })
+ return jsonify(
+ {
+ "available": False,
+ "model": llm_config.get("model", "gemma3:12b"),
+ "message": f"Error checking model: {str(e)}",
+ }
+ )
+
# Helper route to get system configuration
-@api_bp.route('/config', methods=['GET'])
+@api_bp.route("/config", methods=["GET"])
def api_get_config():
"""
Get public system configuration
"""
# Only return public configuration
public_config = {
- 'version': current_app.config.get('VERSION', '0.1.0'),
- 'llm_provider': current_app.config.get('LLM_CONFIG', {}).get('provider', 'ollama'),
- 'search_tool': current_app.config.get('SEARCH_CONFIG', {}).get('search_tool', 'auto'),
- 'features': {
- 'notifications': current_app.config.get('ENABLE_NOTIFICATIONS', False)
- }
+ "version": current_app.config.get("VERSION", "0.1.0"),
+ "llm_provider": current_app.config.get("LLM_CONFIG", {}).get(
+ "provider", "ollama"
+ ),
+ "search_tool": current_app.config.get("SEARCH_CONFIG", {}).get(
+ "search_tool", "auto"
+ ),
+ "features": {
+ "notifications": current_app.config.get("ENABLE_NOTIFICATIONS", False)
+ },
}
-
- return jsonify(public_config)
\ No newline at end of file
+
+ return jsonify(public_config)
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index f6189beb29..b5d821f1ff 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -1,6 +1,7 @@
import json
import logging
import traceback
+
from flask import Blueprint, jsonify, make_response, request
from ..models.database import get_db_connection, get_logs_for_research
@@ -11,6 +12,7 @@ logger = logging.getLogger(__name__)
# Create a Blueprint for the history routes
history_bp = Blueprint("history", __name__)
+
@history_bp.route("/history", methods=["GET"])
def get_history():
"""Get the research history"""
@@ -58,6 +60,7 @@ def get_history():
try:
# Convert to ISO format if it's not already
from dateutil import parser
+
dt = parser.parse(item["created_at"])
item["created_at"] = dt.isoformat()
except Exception:
@@ -67,6 +70,7 @@ def get_history():
try:
# Convert to ISO format if it's not already
from dateutil import parser
+
dt = parser.parse(item["completed_at"])
item["completed_at"] = dt.isoformat()
except Exception:
@@ -80,6 +84,7 @@ def get_history():
):
try:
from dateutil import parser
+
start_time = parser.parse(item["created_at"])
end_time = parser.parse(item["completed_at"])
item["duration_seconds"] = int(
@@ -93,7 +98,7 @@ def get_history():
# Format response to match what client expects
response_data = {
"status": "success",
- "items": history # Use 'items' key as expected by client
+ "items": history, # Use 'items' key as expected by client
}
# Add CORS headers
@@ -110,7 +115,9 @@ def get_history():
print(f"Error getting history: {str(e)}")
print(traceback.format_exc())
# Return empty array with CORS headers
- response = make_response(jsonify({"status": "error", "items": [], "message": str(e)}))
+ response = make_response(
+ jsonify({"status": "error", "items": [], "message": str(e)})
+ )
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add(
"Access-Control-Allow-Headers", "Content-Type,Authorization"
@@ -120,6 +127,7 @@ def get_history():
)
return response
+
@history_bp.route("/status/<int:research_id>")
def get_research_status(research_id):
conn = get_db_connection()
@@ -136,8 +144,9 @@ def get_research_status(research_id):
# Import globals from research routes
from .research_routes import get_globals
+
globals_dict = get_globals()
- active_research = globals_dict['active_research']
+ active_research = globals_dict["active_research"]
# Add progress information
if research_id in active_research:
@@ -158,6 +167,7 @@ def get_research_status(research_id):
return jsonify(result)
+
@history_bp.route("/details/<int:research_id>")
def get_research_details(research_id):
"""Get detailed progress log for a specific research"""
@@ -178,8 +188,9 @@ def get_research_details(research_id):
# Import globals from research routes
from .research_routes import get_globals
+
globals_dict = get_globals()
- active_research = globals_dict['active_research']
+ active_research = globals_dict["active_research"]
# If this is an active research, merge with any in-memory logs
if research_id in active_research:
@@ -213,6 +224,7 @@ def get_research_details(research_id):
}
)
+
@history_bp.route("/report/<int:research_id>")
def get_report(research_id):
conn = get_db_connection()
@@ -230,33 +242,36 @@ def get_report(research_id):
try:
with open(result["report_path"], "r", encoding="utf-8") as f:
content = f.read()
-
+
# Create an enhanced metadata dictionary with database fields
enhanced_metadata = {
"query": result.get("query", "Unknown query"),
"mode": result.get("mode", "quick"),
"created_at": result.get("created_at"),
"completed_at": result.get("completed_at"),
- "duration": result.get("duration_seconds")
+ "duration": result.get("duration_seconds"),
}
-
+
# Also include any stored metadata
stored_metadata = json.loads(result.get("metadata", "{}"))
if stored_metadata and isinstance(stored_metadata, dict):
enhanced_metadata.update(stored_metadata)
-
- return jsonify({
- "status": "success",
- "content": content,
- "query": result.get("query"),
- "mode": result.get("mode"),
- "created_at": result.get("created_at"),
- "completed_at": result.get("completed_at"),
- "metadata": enhanced_metadata
- })
+
+ return jsonify(
+ {
+ "status": "success",
+ "content": content,
+ "query": result.get("query"),
+ "mode": result.get("mode"),
+ "created_at": result.get("created_at"),
+ "completed_at": result.get("completed_at"),
+ "metadata": enhanced_metadata,
+ }
+ )
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
+
@history_bp.route("/markdown/<int:research_id>")
def get_markdown(research_id):
"""Get markdown export for a specific research"""
@@ -275,15 +290,11 @@ def get_markdown(research_id):
try:
with open(result["report_path"], "r", encoding="utf-8") as f:
content = f.read()
- return jsonify(
- {
- "status": "success",
- "content": content
- }
- )
+ return jsonify({"status": "success", "content": content})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
+
@history_bp.route("/logs/<int:research_id>")
def get_research_logs(research_id):
"""Get logs for a specific research ID"""
@@ -302,7 +313,7 @@ def get_research_logs(research_id):
# Retrieve logs from the database
logs = get_logs_for_research(research_id)
-
+
# Format logs correctly if needed
formatted_logs = []
for log in logs:
@@ -310,15 +321,16 @@ def get_research_logs(research_id):
log_entry = {
"time": log.get("time", ""),
"message": log.get("message", "No message"),
- "type": log.get("type", "info")
+ "type": log.get("type", "info"),
}
formatted_logs.append(log_entry)
# Import globals from research routes
from .research_routes import get_globals
+
globals_dict = get_globals()
- active_research = globals_dict['active_research']
-
+ active_research = globals_dict["active_research"]
+
# Add any current logs from memory if this is an active research
if research_id in active_research and active_research[research_id].get("log"):
# Use the logs from memory temporarily until they're saved to the database
@@ -329,9 +341,9 @@ def get_research_logs(research_id):
log_entry = {
"time": log.get("time", ""),
"message": log.get("message", "No message"),
- "type": log.get("type", "info")
+ "type": log.get("type", "info"),
}
-
+
# Check if this log is already in our formatted logs by timestamp
if not any(flog["time"] == log_entry["time"] for flog in formatted_logs):
formatted_logs.append(log_entry)
@@ -339,4 +351,4 @@ def get_research_logs(research_id):
# Sort logs by timestamp
formatted_logs.sort(key=lambda x: x["time"])
- return jsonify({"status": "success", "logs": formatted_logs})
\ No newline at end of file
+ return jsonify({"status": "success", "logs": formatted_logs})
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 91fce975f5..f1dd07d5a4 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -1,17 +1,35 @@
-import logging
-import traceback
-from datetime import datetime
import json
+import logging
import os
import platform
import subprocess
+import traceback
+from datetime import datetime
from importlib import resources as importlib_resources
-from flask import Blueprint, render_template, request, jsonify, make_response, redirect, url_for, send_from_directory
+from flask import (
+ Blueprint,
+ jsonify,
+ make_response,
+ redirect,
+ render_template,
+ request,
+ send_from_directory,
+ url_for,
+)
from flask_socketio import emit
-from ..models.database import init_db, add_log_to_db, get_logs_for_research, calculate_duration
-from ..services.research_service import start_research_process, run_research_process, cleanup_research_resources
+from ..models.database import (
+ add_log_to_db,
+ calculate_duration,
+ get_logs_for_research,
+ init_db,
+)
+from ..services.research_service import (
+ cleanup_research_resources,
+ run_research_process,
+ start_research_process,
+)
# Initialize logger
logger = logging.getLogger(__name__)
@@ -29,88 +47,105 @@ termination_flags = {}
# Output directory for research results
OUTPUT_DIR = "research_outputs"
+
# Return reference to globals for other modules to access
def get_globals():
return {
- 'active_research': active_research,
- 'socket_subscriptions': socket_subscriptions,
- 'termination_flags': termination_flags
+ "active_research": active_research,
+ "socket_subscriptions": socket_subscriptions,
+ "termination_flags": termination_flags,
}
+
# Route for index page - redirection
@research_bp.route("/")
def index():
return render_template("pages/research.html")
+
# Add the missing static file serving route
@research_bp.route("/static/<path:path>")
def serve_static(path):
"""Serve static files"""
- return send_from_directory(os.path.join(os.path.dirname(os.path.dirname(__file__)), "static"), path)
+ return send_from_directory(
+ os.path.join(os.path.dirname(os.path.dirname(__file__)), "static"), path
+ )
+
# Add static route at the root level
@research_bp.route("/redirect-static/<path:path>")
def redirect_static(path):
"""Redirect old static URLs to new static URLs"""
- return redirect(url_for('static', filename=path))
+ return redirect(url_for("static", filename=path))
+
@research_bp.route("/progress/<int:research_id>")
def progress_page(research_id):
"""Render the research progress page"""
return render_template("pages/progress.html")
+
@research_bp.route("/details/<int:research_id>")
def research_details_page(research_id):
"""Render the research details page"""
return render_template("pages/details.html")
+
@research_bp.route("/results/<int:research_id>")
def results_page(research_id):
"""Render the research results page"""
return render_template("pages/results.html")
+
@research_bp.route("/history")
def history_page():
"""Render the history page"""
return render_template("pages/history.html")
+
# Add missing settings routes
@research_bp.route("/settings", methods=["GET"])
def settings_page():
"""Render the settings page"""
return render_template("settings_dashboard.html")
+
@research_bp.route("/settings/main", methods=["GET"])
def main_config_page():
"""Render the main settings config page"""
return render_template("main_config.html")
+
@research_bp.route("/settings/collections", methods=["GET"])
def collections_config_page():
"""Render the collections config page"""
return render_template("collections_config.html")
+
@research_bp.route("/settings/api_keys", methods=["GET"])
def api_keys_config_page():
"""Render the API keys config page"""
return render_template("api_keys_config.html")
+
@research_bp.route("/settings/search_engines", methods=["GET"])
def search_engines_config_page():
"""Render the search engines config page"""
return render_template("search_engines_config.html")
+
@research_bp.route("/settings/llm", methods=["GET"])
def llm_config_page():
"""Render the LLM config page"""
return render_template("llm_config.html")
+
@research_bp.route("/api/start_research", methods=["POST"])
def start_research():
data = request.json
query = data.get("query")
mode = data.get("mode", "quick")
-
+
# Get search engine and model selections
model = data.get("model")
search_engine = data.get("search_engine") or data.get("search_tool")
@@ -118,10 +153,14 @@ def start_research():
time_period = data.get("time_period")
iterations = data.get("iterations")
questions_per_iteration = data.get("questions_per_iteration")
-
+
# Log the selections for troubleshooting
- logger.info(f"Starting research with model: {model}, search engine: {search_engine}")
- logger.info(f"Additional parameters: max_results={max_results}, time_period={time_period}, iterations={iterations}, questions={questions_per_iteration}")
+ logger.info(
+ f"Starting research with model: {model}, search engine: {search_engine}"
+ )
+ logger.info(
+ f"Additional parameters: max_results={max_results}, time_period={time_period}, iterations={iterations}, questions={questions_per_iteration}"
+ )
if not query:
return jsonify({"status": "error", "message": "Query is required"}), 400
@@ -133,6 +172,7 @@ def start_research():
for research_id, research_data in list(active_research.items()):
# Check database status
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
@@ -174,9 +214,10 @@ def start_research():
# Create a record in the database with explicit UTC timestamp
created_at = datetime.utcnow().isoformat()
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
-
+
# Save research settings in the metadata field
research_settings = {
"model": model,
@@ -184,9 +225,9 @@ def start_research():
"max_results": max_results,
"time_period": time_period,
"iterations": iterations,
- "questions_per_iteration": questions_per_iteration
+ "questions_per_iteration": questions_per_iteration,
}
-
+
cursor.execute(
"INSERT INTO research_history (query, mode, status, created_at, progress_log, metadata) VALUES (?, ?, ?, ?, ?, ?)",
(
@@ -197,7 +238,7 @@ def start_research():
json.dumps(
[{"time": created_at, "message": "Research started", "progress": 0}]
),
- json.dumps(research_settings)
+ json.dumps(research_settings),
),
)
research_id = cursor.lastrowid
@@ -205,20 +246,31 @@ def start_research():
conn.close()
# Start the research process with the selected parameters
- research_thread = start_research_process(research_id, query, mode,
- active_research, termination_flags, run_research_process,
- model=model, search_engine=search_engine,
- max_results=max_results, time_period=time_period,
- iterations=iterations, questions_per_iteration=questions_per_iteration)
+ research_thread = start_research_process(
+ research_id,
+ query,
+ mode,
+ active_research,
+ termination_flags,
+ run_research_process,
+ model=model,
+ search_engine=search_engine,
+ max_results=max_results,
+ time_period=time_period,
+ iterations=iterations,
+ questions_per_iteration=questions_per_iteration,
+ )
return jsonify({"status": "success", "research_id": research_id})
+
@research_bp.route("/api/terminate/<int:research_id>", methods=["POST"])
def terminate_research(research_id):
"""Terminate an in-progress research process"""
# Check if the research exists and is in progress
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT status FROM research_history WHERE id = ?", (research_id,))
@@ -309,6 +361,7 @@ def terminate_research(research_id):
}
from ..services.socket_service import emit_socket_event
+
emit_socket_event(f"research_progress_{research_id}", event_data)
except Exception as socket_error:
@@ -316,10 +369,12 @@ def terminate_research(research_id):
return jsonify({"status": "success", "message": "Research termination requested"})
+
@research_bp.route("/api/delete/<int:research_id>", methods=["DELETE"])
def delete_research(research_id):
"""Delete a research record"""
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
@@ -362,65 +417,68 @@ def delete_research(research_id):
return jsonify({"status": "success"})
+
@research_bp.route("/api/clear_history", methods=["POST"])
def clear_history():
"""Clear all research history"""
try:
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
-
+
# Get all research IDs first to clean up files
cursor.execute("SELECT id, report_path FROM research_history")
research_records = cursor.fetchall()
-
+
# Clean up report files
for research_id, report_path in research_records:
# Skip active research
if research_id in active_research:
continue
-
+
# Delete report file if it exists
if report_path and os.path.exists(report_path):
try:
os.remove(report_path)
except Exception as e:
print(f"Error removing report file: {str(e)}")
-
+
# Delete records from the database, except active research
- placeholders = ', '.join(['?'] * len(active_research))
+ placeholders = ", ".join(["?"] * len(active_research))
if active_research:
cursor.execute(
f"DELETE FROM research_history WHERE id NOT IN ({placeholders})",
- list(active_research.keys())
+ list(active_research.keys()),
)
else:
cursor.execute("DELETE FROM research_history")
-
+
conn.commit()
conn.close()
-
+
return jsonify({"status": "success"})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
+
@research_bp.route("/open_file_location", methods=["POST"])
def open_file_location():
"""Open a file location in the system file explorer"""
data = request.json
file_path = data.get("path")
-
+
if not file_path:
return jsonify({"status": "error", "message": "Path is required"}), 400
-
+
# Convert to absolute path if needed
if not os.path.isabs(file_path):
file_path = os.path.abspath(file_path)
-
+
# Check if path exists
if not os.path.exists(file_path):
return jsonify({"status": "error", "message": "Path does not exist"}), 404
-
+
try:
if platform.system() == "Windows":
# On Windows, open the folder and select the file
@@ -433,67 +491,73 @@ def open_file_location():
subprocess.run(["open", file_path], check=True)
else: # Linux and others
subprocess.run(["xdg-open", os.path.dirname(file_path)], check=True)
-
+
return jsonify({"status": "success"})
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
+
@research_bp.route("/api/save_raw_config", methods=["POST"])
def save_raw_config():
"""Save raw configuration"""
data = request.json
raw_config = data.get("raw_config")
-
+
if not raw_config:
- return jsonify({"success": False, "error": "Raw configuration is required"}), 400
-
+ return (
+ jsonify({"success": False, "error": "Raw configuration is required"}),
+ 400,
+ )
+
try:
# Get the config file path
config_dir = os.path.join(os.path.expanduser("~"), ".local_deep_research")
os.makedirs(config_dir, exist_ok=True)
config_path = os.path.join(config_dir, "config.toml")
-
+
# Write the configuration to file
with open(config_path, "w", encoding="utf-8") as f:
f.write(raw_config)
-
+
return jsonify({"success": True})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
+
@research_bp.route("/api/history", methods=["GET"])
def get_history():
"""Get research history"""
try:
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
-
+
# Check if title column exists in the database
cursor.execute("PRAGMA table_info(research_history)")
columns = [column[1] for column in cursor.fetchall()]
-
+
# Build query based on existing columns
select_columns = [
- "id",
- "query",
- "mode",
- "status",
- "created_at",
+ "id",
+ "query",
+ "mode",
+ "status",
+ "created_at",
"completed_at",
- "report_path"
+ "report_path",
]
-
+
# Optionally include title if it exists
if "title" in columns:
select_columns.append("title")
-
+
# Construct query
select_query = f"SELECT {', '.join(select_columns)} FROM research_history ORDER BY created_at DESC"
-
+
# Execute query
cursor.execute(select_query)
-
+
history_items = []
for row in cursor.fetchall():
# Extract values
@@ -505,8 +569,10 @@ def get_history():
created_at = row_data["created_at"]
completed_at = row_data["completed_at"]
report_path = row_data["report_path"]
- title = row_data.get("title", None) # Use get to handle title not being present
-
+ title = row_data.get(
+ "title", None
+ ) # Use get to handle title not being present
+
# Calculate duration if completed
duration_seconds = None
if completed_at and created_at:
@@ -514,7 +580,7 @@ def get_history():
duration_seconds = calculate_duration(created_at, completed_at)
except Exception as e:
print(f"Error calculating duration: {e}")
-
+
# Create a history item
item = {
"id": research_id,
@@ -524,19 +590,20 @@ def get_history():
"created_at": created_at,
"completed_at": completed_at,
"duration_seconds": duration_seconds,
- "report_path": report_path
+ "report_path": report_path,
}
-
+
# Add title if not None
if title is not None:
item["title"] = title
-
+
history_items.append(item)
-
+
conn.close()
return jsonify({"status": "success", "items": history_items})
except Exception as e:
import traceback
+
print(f"Error getting history: {e}")
print(traceback.format_exc())
- return jsonify({"status": "error", "message": str(e)}), 500
\ No newline at end of file
+ return jsonify({"status": "error", "message": str(e)}), 500
diff --git a/src/local_deep_research/web/routes/settings_api.py b/src/local_deep_research/web/routes/settings_api.py
index ed3600d891..782d341168 100644
--- a/src/local_deep_research/web/routes/settings_api.py
+++ b/src/local_deep_research/web/routes/settings_api.py
@@ -1,12 +1,12 @@
import logging
-from typing import Dict, List, Optional, Any, Union
+from typing import Any, Dict, List, Optional, Union
-from flask import Blueprint, jsonify, request, current_app
+from flask import Blueprint, current_app, jsonify, request
from sqlalchemy.orm import Session
from ..database.models import Setting, SettingType
-from ..services.settings_manager import SettingsManager
from ..models.settings import BaseSetting, SettingsGroup
+from ..services.settings_manager import SettingsManager
# Initialize logger
logger = logging.getLogger(__name__)
@@ -14,25 +14,27 @@ logger = logging.getLogger(__name__)
# Create a Blueprint for settings API
settings_api_bp = Blueprint("settings_api", __name__, url_prefix="/")
+
def get_db_session() -> Session:
"""Get the database session from the app context"""
- if hasattr(current_app, 'db_session'):
+ if hasattr(current_app, "db_session"):
return current_app.db_session
else:
- return current_app.extensions['sqlalchemy'].session()
+ return current_app.extensions["sqlalchemy"].session()
+
@settings_api_bp.route("/", methods=["GET"])
def get_all_settings():
"""Get all settings"""
try:
# Get query parameters
- setting_type = request.args.get('type')
- category = request.args.get('category')
-
+ setting_type = request.args.get("type")
+ category = request.args.get("category")
+
# Create settings manager
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Get settings
if setting_type:
try:
@@ -42,41 +44,42 @@ def get_all_settings():
return jsonify({"error": f"Invalid setting type: {setting_type}"}), 400
else:
settings = settings_manager.get_all_settings()
-
+
# Filter by category if requested
if category:
filtered_settings = {}
# Need to get all setting details to check category
db_settings = db_session.query(Setting).all()
category_keys = [s.key for s in db_settings if s.category == category]
-
+
# Filter settings by keys
for key, value in settings.items():
if key in category_keys:
filtered_settings[key] = value
-
+
settings = filtered_settings
-
+
return jsonify({"settings": settings})
except Exception as e:
logger.error(f"Error getting settings: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/<path:key>", methods=["GET"])
def get_setting(key):
"""Get a specific setting by key"""
try:
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Get setting
value = settings_manager.get_setting(key)
if value is None:
return jsonify({"error": f"Setting not found: {key}"}), 404
-
+
# Get additional metadata from database
db_setting = db_session.query(Setting).filter(Setting.key == key).first()
-
+
if db_setting:
# Return full setting details
setting_data = {
@@ -92,20 +95,18 @@ def get_setting(key):
"max_value": db_setting.max_value,
"step": db_setting.step,
"visible": db_setting.visible,
- "editable": db_setting.editable
+ "editable": db_setting.editable,
}
else:
# Return minimal info
- setting_data = {
- "key": key,
- "value": value
- }
-
+ setting_data = {"key": key, "value": value}
+
return jsonify({"setting": setting_data})
except Exception as e:
logger.error(f"Error getting setting {key}: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/<path:key>", methods=["PUT"])
def update_setting(key):
"""Update a setting"""
@@ -114,23 +115,23 @@ def update_setting(key):
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
-
+
value = data.get("value")
if value is None:
return jsonify({"error": "No value provided"}), 400
-
+
# Get DB session and settings manager
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Check if setting exists
db_setting = db_session.query(Setting).filter(Setting.key == key).first()
-
+
if db_setting:
# Check if setting is editable
if not db_setting.editable:
return jsonify({"error": f"Setting {key} is not editable"}), 403
-
+
# Update setting
success = settings_manager.set_setting(key, value)
if success:
@@ -142,47 +143,64 @@ def update_setting(key):
setting_dict = {
"key": key,
"value": value,
- "name": key.split('.')[-1].replace('_', ' ').title(),
- "description": f"Setting for {key}"
+ "name": key.split(".")[-1].replace("_", " ").title(),
+ "description": f"Setting for {key}",
}
-
+
# Add additional metadata if provided
- for field in ["type", "name", "description", "category", "ui_element",
- "options", "min_value", "max_value", "step", "visible", "editable"]:
+ for field in [
+ "type",
+ "name",
+ "description",
+ "category",
+ "ui_element",
+ "options",
+ "min_value",
+ "max_value",
+ "step",
+ "visible",
+ "editable",
+ ]:
if field in data:
setting_dict[field] = data[field]
-
+
# Create setting
db_setting = settings_manager.create_or_update_setting(setting_dict)
-
+
if db_setting:
- return jsonify({
- "message": f"Setting {key} created successfully",
- "setting": {
- "key": db_setting.key,
- "value": db_setting.value,
- "type": db_setting.type.value,
- "name": db_setting.name
- }
- }), 201
+ return (
+ jsonify(
+ {
+ "message": f"Setting {key} created successfully",
+ "setting": {
+ "key": db_setting.key,
+ "value": db_setting.value,
+ "type": db_setting.type.value,
+ "name": db_setting.name,
+ },
+ }
+ ),
+ 201,
+ )
else:
return jsonify({"error": f"Failed to create setting {key}"}), 500
except Exception as e:
logger.error(f"Error updating setting {key}: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/<path:key>", methods=["DELETE"])
def delete_setting(key):
"""Delete a setting"""
try:
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Check if setting exists
db_setting = db_session.query(Setting).filter(Setting.key == key).first()
if not db_setting:
return jsonify({"error": f"Setting not found: {key}"}), 404
-
+
# Delete setting
success = settings_manager.delete_setting(key)
if success:
@@ -193,26 +211,30 @@ def delete_setting(key):
logger.error(f"Error deleting setting {key}: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/export", methods=["POST"])
def export_settings():
"""Export settings to file"""
try:
data = request.get_json() or {}
setting_type_str = data.get("type")
-
+
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Export settings
if setting_type_str:
try:
setting_type = SettingType[setting_type_str.upper()]
success = settings_manager.export_to_file(setting_type)
except KeyError:
- return jsonify({"error": f"Invalid setting type: {setting_type_str}"}), 400
+ return (
+ jsonify({"error": f"Invalid setting type: {setting_type_str}"}),
+ 400,
+ )
else:
success = settings_manager.export_to_file()
-
+
if success:
return jsonify({"message": "Settings exported successfully"})
else:
@@ -221,26 +243,30 @@ def export_settings():
logger.error(f"Error exporting settings: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/import", methods=["POST"])
def import_settings():
"""Import settings from file"""
try:
data = request.get_json() or {}
setting_type_str = data.get("type")
-
+
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
# Import settings
if setting_type_str:
try:
setting_type = SettingType[setting_type_str.upper()]
success = settings_manager.import_from_file(setting_type)
except KeyError:
- return jsonify({"error": f"Invalid setting type: {setting_type_str}"}), 400
+ return (
+ jsonify({"error": f"Invalid setting type: {setting_type_str}"}),
+ 400,
+ )
else:
success = settings_manager.import_from_file()
-
+
if success:
return jsonify({"message": "Settings imported successfully"})
else:
@@ -249,21 +275,23 @@ def import_settings():
logger.error(f"Error importing settings: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/categories", methods=["GET"])
def get_categories():
"""Get all setting categories"""
try:
db_session = get_db_session()
-
+
# Get all distinct categories
categories = db_session.query(Setting.category).distinct().all()
category_list = [c[0] for c in categories if c[0] is not None]
-
+
return jsonify({"categories": category_list})
except Exception as e:
logger.error(f"Error getting categories: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/types", methods=["GET"])
def get_types():
"""Get all setting types"""
@@ -275,222 +303,247 @@ def get_types():
logger.error(f"Error getting types: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/ui_elements", methods=["GET"])
def get_ui_elements():
"""Get all UI element types"""
try:
# Define supported UI element types
ui_elements = [
- "text", "select", "checkbox", "slider", "number",
- "textarea", "color", "date", "file", "password"
+ "text",
+ "select",
+ "checkbox",
+ "slider",
+ "number",
+ "textarea",
+ "color",
+ "date",
+ "file",
+ "password",
]
-
+
return jsonify({"ui_elements": ui_elements})
except Exception as e:
logger.error(f"Error getting UI elements: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/available-models", methods=["GET"])
def get_available_models():
"""Get available language models"""
try:
# Import needed modules
- from ...config.llm_config import get_available_providers, VALID_PROVIDERS, is_ollama_available
-
+ from ...config.llm_config import (
+ VALID_PROVIDERS,
+ get_available_providers,
+ is_ollama_available,
+ )
+
# Get available providers
providers = get_available_providers()
-
+
# Add more Ollama models if available
- if 'ollama' in providers:
+ if "ollama" in providers:
# Try to get Ollama models directly from Ollama API
try:
import requests
+
from ...config.llm_config import settings
-
+
# Get the Ollama base URL from settings
base_url = settings.get(
- "OLLAMA_BASE_URL",
- settings.llm.get("ollama_base_url", "http://localhost:11434")
+ "OLLAMA_BASE_URL",
+ settings.llm.get("ollama_base_url", "http://localhost:11434"),
)
-
+
# Try to fetch available models from Ollama
response = requests.get(f"{base_url}/api/tags", timeout=3.0)
if response.status_code == 200:
ollama_data = response.json()
- if 'models' in ollama_data:
- ollama_models = ollama_data['models']
+ if "models" in ollama_data:
+ ollama_models = ollama_data["models"]
else:
# Older Ollama API versions might return a simpler structure
- ollama_models = [{"name": m} for m in ollama_data.get('models', [])]
-
+ ollama_models = [
+ {"name": m} for m in ollama_data.get("models", [])
+ ]
+
# Create a list of Ollama model options
ollama_model_options = []
for model in ollama_models:
- model_name = model.get('name')
+ model_name = model.get("name")
if model_name:
# Format label to be more readable
- if ':' in model_name:
- base_name, variant = model_name.split(':', 1)
+ if ":" in model_name:
+ base_name, variant = model_name.split(":", 1)
label = f"{base_name.title()} {variant} (Ollama)"
else:
label = f"{model_name.title()} (Ollama)"
-
- ollama_model_options.append({
- "value": model_name,
- "label": label
- })
-
+
+ ollama_model_options.append(
+ {"value": model_name, "label": label}
+ )
+
# Add additional context to the response
providers["ollama_models"] = ollama_model_options
except Exception as e:
logger.error(f"Error fetching Ollama models: {e}")
# Don't fail if we can't get Ollama models
providers["ollama_models"] = []
-
+
# Prepare response data
models_info = {
"providers": providers,
"valid_providers": VALID_PROVIDERS,
"provider_options": [
- {"value": key, "label": value}
- for key, value in providers.items()
+ {"value": key, "label": value} for key, value in providers.items()
],
- "ollama_available": is_ollama_available()
+ "ollama_available": is_ollama_available(),
}
-
+
return jsonify(models_info)
except Exception as e:
logger.error(f"Error getting available models: {e}")
return jsonify({"error": str(e)}), 500
+
@settings_api_bp.route("/available-search-engines", methods=["GET"])
def get_available_search_engines():
"""Get available search engines"""
try:
# First try to get engines from search_engines.toml file
engines_dict = get_engines_from_file()
-
+
# If we got engines from file, use those
if engines_dict:
# Make sure searxng is included if it should be
- if 'searxng' not in engines_dict:
- engines_dict['searxng'] = {
- 'display_name': 'SearXNG (Self-hosted)',
- 'description': 'Self-hosted metasearch engine',
- 'strengths': ['privacy', 'customization', 'no API key needed']
+ if "searxng" not in engines_dict:
+ engines_dict["searxng"] = {
+ "display_name": "SearXNG (Self-hosted)",
+ "description": "Self-hosted metasearch engine",
+ "strengths": ["privacy", "customization", "no API key needed"],
}
-
+
# Format as options for dropdown
engine_options = [
- {"value": key, "label": engines_dict.get(key, {}).get("display_name", key)}
+ {
+ "value": key,
+ "label": engines_dict.get(key, {}).get("display_name", key),
+ }
for key in engines_dict.keys()
]
-
- return jsonify({
- "engines": engines_dict,
- "engine_options": engine_options
- })
-
+
+ return jsonify({"engines": engines_dict, "engine_options": engine_options})
+
# Fallback to factory function if file method failed
try:
# Import needed modules
- from ...web_search_engines.search_engine_factory import get_available_engines
from ...defaults import search_engines as default_engines
-
+ from ...web_search_engines.search_engine_factory import (
+ get_available_engines,
+ )
+
# Get available engines
search_engines = get_available_engines(include_api_key_services=True)
-
+
# Handle if search_engines is a list (not a dict)
if isinstance(search_engines, list):
# Convert to dict with engine name as key and display name as value
- engines_dict = {engine: engine.replace('_', ' ').title() for engine in search_engines}
+ engines_dict = {
+ engine: engine.replace("_", " ").title()
+ for engine in search_engines
+ }
else:
engines_dict = search_engines
-
+
# Make sure searxng is included
- if 'searxng' not in engines_dict:
- engines_dict['searxng'] = 'SearXNG (Self-hosted)'
-
+ if "searxng" not in engines_dict:
+ engines_dict["searxng"] = "SearXNG (Self-hosted)"
+
# Format as options for dropdown
engine_options = [
- {"value": key, "label": value if isinstance(value, str) else key.replace('_', ' ').title()}
+ {
+ "value": key,
+ "label": (
+ value
+ if isinstance(value, str)
+ else key.replace("_", " ").title()
+ ),
+ }
for key, value in engines_dict.items()
]
-
- return jsonify({
- "engines": engines_dict,
- "engine_options": engine_options
- })
+
+ return jsonify({"engines": engines_dict, "engine_options": engine_options})
except Exception as e:
# If both methods fail, return default engines with searxng
logger.error(f"Error getting available search engines from factory: {e}")
-
+
# Use hardcoded defaults from search_engines.toml
defaults = {
"wikipedia": "Wikipedia",
- "arxiv": "ArXiv Papers",
+ "arxiv": "ArXiv Papers",
"pubmed": "PubMed Medical",
"github": "GitHub Code",
"searxng": "SearXNG (Self-hosted)",
"serpapi": "SerpAPI (Google)",
"google_pse": "Google PSE",
- "auto": "Auto-select"
+ "auto": "Auto-select",
}
-
+
engine_options = [
- {"value": key, "label": value}
- for key, value in defaults.items()
+ {"value": key, "label": value} for key, value in defaults.items()
]
-
- return jsonify({
- "engines": defaults,
- "engine_options": engine_options
- })
-
+
+ return jsonify({"engines": defaults, "engine_options": engine_options})
+
except Exception as e:
logger.error(f"Error getting available search engines: {e}")
return jsonify({"error": str(e)}), 500
+
def get_engines_from_file():
"""Get available search engines directly from the toml file"""
try:
- import toml
from pathlib import Path
+
+ import toml
+
from ...config.config_files import CONFIG_DIR, get_config_dir
-
+
# Try to load from the actual config directory
config_dir = get_config_dir()
search_engines_file = config_dir / "config" / "search_engines.toml"
-
+
# If file doesn't exist in user config, try the defaults
if not search_engines_file.exists():
# Look in the defaults folder instead
- from ...defaults import search_engines
import inspect
-
+
+ from ...defaults import search_engines
+
# Get the path to the search_engines.toml file
module_path = inspect.getfile(search_engines)
default_file = Path(module_path)
-
- if default_file.exists() and default_file.suffix == '.toml':
+
+ if default_file.exists() and default_file.suffix == ".toml":
search_engines_file = default_file
-
+
# If we found a file, load it
if search_engines_file.exists():
data = toml.load(search_engines_file)
-
+
# Filter out the metadata entries (like DEFAULT_SEARCH_ENGINE)
engines = {k: v for k, v in data.items() if isinstance(v, dict)}
-
+
# Add display names for each engine
for key, engine in engines.items():
- if 'display_name' not in engine:
+ if "display_name" not in engine:
# Create a display name from the key
- engine['display_name'] = key.replace('_', ' ').title()
-
+ engine["display_name"] = key.replace("_", " ").title()
+
return engines
-
+
return None
except Exception as e:
logger.error(f"Error loading search engines from file: {e}")
- return None
\ No newline at end of file
+ return None
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 91d021c91e..8aeca9d269 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -1,9 +1,19 @@
-import os
import logging
+import os
import platform
import subprocess
+
import toml
-from flask import Blueprint, current_app, flash, jsonify, redirect, render_template, request, url_for
+from flask import (
+ Blueprint,
+ current_app,
+ flash,
+ jsonify,
+ redirect,
+ render_template,
+ request,
+ url_for,
+)
from ..database.models import Setting, SettingType
from ..services.settings_manager import SettingsManager
@@ -20,7 +30,10 @@ CONFIG_DIR = None
MAIN_CONFIG_FILE = None
LOCAL_COLLECTIONS_FILE = None
-def set_config_paths(config_dir, search_engines_file, main_config_file, local_collections_file):
+
+def set_config_paths(
+ config_dir, search_engines_file, main_config_file, local_collections_file
+):
"""Set the config paths for the settings routes (legacy support)"""
global CONFIG_DIR, SEARCH_ENGINES_FILE, MAIN_CONFIG_FILE, LOCAL_COLLECTIONS_FILE
CONFIG_DIR = config_dir
@@ -28,55 +41,61 @@ def set_config_paths(config_dir, search_engines_file, main_config_file, local_co
MAIN_CONFIG_FILE = main_config_file
LOCAL_COLLECTIONS_FILE = local_collections_file
+
def get_db_session():
"""Get the database session from the app context"""
- if hasattr(current_app, 'db_session'):
+ if hasattr(current_app, "db_session"):
return current_app.db_session
else:
- return current_app.extensions['sqlalchemy'].session()
+ return current_app.extensions["sqlalchemy"].session()
+
@settings_bp.route("/", methods=["GET"])
def settings_page():
"""Main settings dashboard with links to specialized config pages"""
return render_template("settings_dashboard.html")
+
@settings_bp.route("/llm", methods=["GET", "POST"])
def llm_settings():
"""LLM settings page"""
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
if request.method == "POST":
# Process form submission
try:
# Get form data
form_data = request.form
-
+
# Update each setting
for key, value in form_data.items():
- if key.startswith('llm.'):
+ if key.startswith("llm."):
# Convert checkboxes to boolean
- if value == 'on':
+ if value == "on":
value = True
-
+
# Save the setting
settings_manager.set_setting(key, value)
-
+
# Export settings to file as well
settings_manager.export_to_file(SettingType.LLM)
-
+
flash("LLM settings saved successfully", "success")
except Exception as e:
logger.error(f"Error saving LLM settings: {e}")
flash(f"Error saving settings: {str(e)}", "error")
-
+
return redirect(url_for("settings.llm_settings"))
-
+
# Get all LLM settings
- settings = db_session.query(Setting).filter(
- Setting.type == SettingType.LLM
- ).order_by(Setting.category, Setting.name).all()
-
+ settings = (
+ db_session.query(Setting)
+ .filter(Setting.type == SettingType.LLM)
+ .order_by(Setting.category, Setting.name)
+ .all()
+ )
+
# Group settings by category
settings_by_category = {}
for setting in settings:
@@ -84,49 +103,52 @@ def llm_settings():
if category not in settings_by_category:
settings_by_category[category] = []
settings_by_category[category].append(setting)
-
+
return render_template(
- "llm_settings.html",
- settings_by_category=settings_by_category
+ "llm_settings.html", settings_by_category=settings_by_category
)
+
@settings_bp.route("/search", methods=["GET", "POST"])
def search_settings():
"""Search settings page"""
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
if request.method == "POST":
# Process form submission
try:
# Get form data
form_data = request.form
-
+
# Update each setting
for key, value in form_data.items():
- if key.startswith('search.'):
+ if key.startswith("search."):
# Convert checkboxes to boolean
- if value == 'on':
+ if value == "on":
value = True
-
+
# Save the setting
settings_manager.set_setting(key, value)
-
+
# Export settings to file as well
settings_manager.export_to_file(SettingType.SEARCH)
-
+
flash("Search settings saved successfully", "success")
except Exception as e:
logger.error(f"Error saving search settings: {e}")
flash(f"Error saving settings: {str(e)}", "error")
-
+
return redirect(url_for("settings.search_settings"))
-
+
# Get all search settings
- settings = db_session.query(Setting).filter(
- Setting.type == SettingType.SEARCH
- ).order_by(Setting.category, Setting.name).all()
-
+ settings = (
+ db_session.query(Setting)
+ .filter(Setting.type == SettingType.SEARCH)
+ .order_by(Setting.category, Setting.name)
+ .all()
+ )
+
# Group settings by category
settings_by_category = {}
for setting in settings:
@@ -134,49 +156,52 @@ def search_settings():
if category not in settings_by_category:
settings_by_category[category] = []
settings_by_category[category].append(setting)
-
+
return render_template(
- "search_settings.html",
- settings_by_category=settings_by_category
+ "search_settings.html", settings_by_category=settings_by_category
)
+
@settings_bp.route("/app", methods=["GET", "POST"])
def app_settings():
"""Application settings page"""
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
if request.method == "POST":
# Process form submission
try:
# Get form data
form_data = request.form
-
+
# Update each setting
for key, value in form_data.items():
- if key.startswith('app.'):
+ if key.startswith("app."):
# Convert checkboxes to boolean
- if value == 'on':
+ if value == "on":
value = True
-
+
# Save the setting
settings_manager.set_setting(key, value)
-
+
# Export settings to file as well
settings_manager.export_to_file(SettingType.APP)
-
+
flash("Application settings saved successfully", "success")
except Exception as e:
logger.error(f"Error saving application settings: {e}")
flash(f"Error saving settings: {str(e)}", "error")
-
+
return redirect(url_for("settings.app_settings"))
-
+
# Get all app settings
- settings = db_session.query(Setting).filter(
- Setting.type == SettingType.APP
- ).order_by(Setting.category, Setting.name).all()
-
+ settings = (
+ db_session.query(Setting)
+ .filter(Setting.type == SettingType.APP)
+ .order_by(Setting.category, Setting.name)
+ .all()
+ )
+
# Group settings by category
settings_by_category = {}
for setting in settings:
@@ -184,49 +209,52 @@ def app_settings():
if category not in settings_by_category:
settings_by_category[category] = []
settings_by_category[category].append(setting)
-
+
return render_template(
- "app_settings.html",
- settings_by_category=settings_by_category
+ "app_settings.html", settings_by_category=settings_by_category
)
+
@settings_bp.route("/report", methods=["GET", "POST"])
def report_settings():
"""Report generation settings page"""
db_session = get_db_session()
settings_manager = SettingsManager.get_instance(db_session)
-
+
if request.method == "POST":
# Process form submission
try:
# Get form data
form_data = request.form
-
+
# Update each setting
for key, value in form_data.items():
- if key.startswith('report.'):
+ if key.startswith("report."):
# Convert checkboxes to boolean
- if value == 'on':
+ if value == "on":
value = True
-
+
# Save the setting
settings_manager.set_setting(key, value)
-
+
# Export settings to file as well
settings_manager.export_to_file(SettingType.REPORT)
-
+
flash("Report settings saved successfully", "success")
except Exception as e:
logger.error(f"Error saving report settings: {e}")
flash(f"Error saving settings: {str(e)}", "error")
-
+
return redirect(url_for("settings.report_settings"))
-
+
# Get all report settings
- settings = db_session.query(Setting).filter(
- Setting.type == SettingType.REPORT
- ).order_by(Setting.category, Setting.name).all()
-
+ settings = (
+ db_session.query(Setting)
+ .filter(Setting.type == SettingType.REPORT)
+ .order_by(Setting.category, Setting.name)
+ .all()
+ )
+
# Group settings by category
settings_by_category = {}
for setting in settings:
@@ -234,33 +262,37 @@ def report_settings():
if category not in settings_by_category:
settings_by_category[category] = []
settings_by_category[category].append(setting)
-
+
return render_template(
- "report_settings.html",
- settings_by_category=settings_by_category
+ "report_settings.html", settings_by_category=settings_by_category
)
+
# Legacy routes for backward compatibility - these will redirect to the new routes
@settings_bp.route("/main", methods=["GET"])
def main_config_page():
"""Redirect to app settings page"""
return redirect(url_for("settings.app_settings"))
+
@settings_bp.route("/collections", methods=["GET"])
def collections_config_page():
"""Redirect to app settings page"""
return redirect(url_for("settings.app_settings"))
+
@settings_bp.route("/api_keys", methods=["GET"])
def api_keys_config_page():
"""Redirect to LLM settings page"""
return redirect(url_for("settings.llm_settings"))
+
@settings_bp.route("/search_engines", methods=["GET"])
def search_engines_config_page():
"""Redirect to search settings page"""
return redirect(url_for("settings.search_settings"))
+
@settings_bp.route("/open_file_location", methods=["POST"])
def open_file_location():
"""Open the location of a configuration file"""
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 5a476b0153..7d8c04e1ee 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -7,7 +7,7 @@ from datetime import datetime
from flask_socketio import emit
-from ..models.database import get_db_connection, add_log_to_db, calculate_duration
+from ..models.database import add_log_to_db, calculate_duration, get_db_connection
# Initialize logger
logger = logging.getLogger(__name__)
@@ -15,10 +15,19 @@ logger = logging.getLogger(__name__)
# Output directory for research results
OUTPUT_DIR = "research_outputs"
-def start_research_process(research_id, query, mode, active_research, termination_flags, run_research_callback, **kwargs):
+
+def start_research_process(
+ research_id,
+ query,
+ mode,
+ active_research,
+ termination_flags,
+ run_research_callback,
+ **kwargs,
+):
"""
Start a research process in a background thread.
-
+
Args:
research_id: The ID of the research
query: The research query
@@ -27,7 +36,7 @@ def start_research_process(research_id, query, mode, active_research, terminatio
termination_flags: Dictionary of termination flags
run_research_callback: The callback function to run the research
**kwargs: Additional parameters to pass to the research process (model, search_engine, etc.)
-
+
Returns:
threading.Thread: The thread running the research
"""
@@ -35,7 +44,7 @@ def start_research_process(research_id, query, mode, active_research, terminatio
thread = threading.Thread(
target=run_research_callback,
args=(research_id, query, mode, active_research, termination_flags),
- kwargs=kwargs
+ kwargs=kwargs,
)
thread.daemon = True
thread.start()
@@ -44,16 +53,25 @@ def start_research_process(research_id, query, mode, active_research, terminatio
"thread": thread,
"progress": 0,
"status": "in_progress",
- "log": [{"time": datetime.utcnow().isoformat(), "message": "Research started", "progress": 0}],
- "settings": kwargs # Store settings for reference
+ "log": [
+ {
+ "time": datetime.utcnow().isoformat(),
+ "message": "Research started",
+ "progress": 0,
+ }
+ ],
+ "settings": kwargs, # Store settings for reference
}
-
+
return thread
-def run_research_process(research_id, query, mode, active_research, termination_flags, **kwargs):
+
+def run_research_process(
+ research_id, query, mode, active_research, termination_flags, **kwargs
+):
"""
Run the research process in the background for a given research ID.
-
+
Args:
research_id: The ID of the research
query: The research query
@@ -70,18 +88,20 @@ def run_research_process(research_id, query, mode, active_research, termination_
return
logger.info(f"Starting research process for ID {research_id}, query: {query}")
-
+
# Extract key parameters
- model = kwargs.get('model')
- search_engine = kwargs.get('search_engine')
- max_results = kwargs.get('max_results')
- time_period = kwargs.get('time_period')
- iterations = kwargs.get('iterations')
- questions_per_iteration = kwargs.get('questions_per_iteration')
-
+ model = kwargs.get("model")
+ search_engine = kwargs.get("search_engine")
+ max_results = kwargs.get("max_results")
+ time_period = kwargs.get("time_period")
+ iterations = kwargs.get("iterations")
+ questions_per_iteration = kwargs.get("questions_per_iteration")
+
# Log all parameters for debugging
- logger.info(f"Research parameters: model={model}, search_engine={search_engine}, max_results={max_results}, time_period={time_period}, iterations={iterations}, questions_per_iteration={questions_per_iteration}")
-
+ logger.info(
+ f"Research parameters: model={model}, search_engine={search_engine}, max_results={max_results}, time_period={time_period}, iterations={iterations}, questions_per_iteration={questions_per_iteration}"
+ )
+
# Set up the AI Context Manager
output_dir = os.path.join(OUTPUT_DIR, f"research_{research_id}")
os.makedirs(output_dir, exist_ok=True)
@@ -190,8 +210,9 @@ def run_research_process(research_id, query, mode, active_research, termination_
# Add log entry in full format for detailed logging on client
if metadata:
event_data["log_entry"] = log_entry
-
+
from ..services.socket_service import emit_to_subscribers
+
emit_to_subscribers("research_progress", research_id, event_data)
except Exception as e:
logger.error(f"Socket emit error (non-critical): {str(e)}")
@@ -200,24 +221,29 @@ def run_research_process(research_id, query, mode, active_research, termination_
def check_termination():
if research_id in termination_flags and termination_flags[research_id]:
handle_termination(research_id, active_research, termination_flags)
- raise Exception("Research was terminated by user during long-running operation")
+ raise Exception(
+ "Research was terminated by user during long-running operation"
+ )
return False # Not terminated
# Set the progress callback in the system
from ...search_system import AdvancedSearchSystem
+
system = AdvancedSearchSystem()
system.set_progress_callback(progress_callback)
# Configure the system with the specified parameters
if model or search_engine:
# Log that we're overriding system settings
- logger.info(f"Overriding system settings with: model={model}, search_engine={search_engine}")
-
+ logger.info(
+ f"Overriding system settings with: model={model}, search_engine={search_engine}"
+ )
+
# Import configuration modules
+ from ...config.config_files import settings
from ...config.llm_config import get_llm
from ...config.search_config import get_search
- from ...config.config_files import settings
-
+
# Override LLM if specified
if model:
try:
@@ -230,36 +256,40 @@ def run_research_process(research_id, query, mode, active_research, termination_
logger.info(f"Successfully set LLM to: {model}")
except Exception as e:
logger.error(f"Error setting LLM model to {model}: {str(e)}")
-
+
# Override search engine if specified
if search_engine:
try:
# Temporarily override the search setting
original_search = settings.search.tool
settings.search.tool = search_engine
-
+
# Set other search parameters if provided
if max_results:
original_max_results = settings.search.max_results
settings.search.max_results = int(max_results)
-
+
if time_period:
original_time_period = settings.search.time_period
settings.search.time_period = time_period
-
+
if iterations:
original_iterations = settings.search.iterations
settings.search.iterations = int(iterations)
system.max_iterations = int(iterations)
-
+
if questions_per_iteration:
original_questions = settings.search.questions_per_iteration
- settings.search.questions_per_iteration = int(questions_per_iteration)
+ settings.search.questions_per_iteration = int(
+ questions_per_iteration
+ )
system.questions_per_iteration = int(questions_per_iteration)
-
+
# Create a new search object with these settings
- system.search = get_search(search_tool=search_engine, llm_instance=system.model)
-
+ system.search = get_search(
+ search_tool=search_engine, llm_instance=system.model
+ )
+
# Restore original settings
settings.search.tool = original_search
if max_results:
@@ -270,10 +300,12 @@ def run_research_process(research_id, query, mode, active_research, termination_
settings.search.iterations = original_iterations
if questions_per_iteration:
settings.search.questions_per_iteration = original_questions
-
+
logger.info(f"Successfully set search engine to: {search_engine}")
except Exception as e:
- logger.error(f"Error setting search engine to {search_engine}: {str(e)}")
+ logger.error(
+ f"Error setting search engine to {search_engine}: {str(e)}"
+ )
# Run the search
progress_callback("Starting research process", 5, {"phase": "init"})
@@ -321,11 +353,15 @@ def run_research_process(research_id, query, mode, active_research, termination_
# Quick Summary
if results.get("findings") or results.get("formatted_findings"):
raw_formatted_findings = results["formatted_findings"]
- logger.info(f"Found formatted_findings of length: {len(str(raw_formatted_findings))}")
+ logger.info(
+ f"Found formatted_findings of length: {len(str(raw_formatted_findings))}"
+ )
try:
clean_markdown = raw_formatted_findings
- logger.info(f"Successfully converted to clean markdown of length: {len(clean_markdown)}")
+ logger.info(
+ f"Successfully converted to clean markdown of length: {len(clean_markdown)}"
+ )
# First send a progress update for generating the summary
progress_callback(
@@ -342,7 +378,9 @@ def run_research_process(research_id, query, mode, active_research, termination_
x for x in query if x.isalnum() or x in [" ", "-", "_"]
)[:50]
safe_query = safe_query.replace(" ", "_").lower()
- report_path = os.path.join(OUTPUT_DIR, f"quick_summary_{safe_query}.md")
+ report_path = os.path.join(
+ OUTPUT_DIR, f"quick_summary_{safe_query}.md"
+ )
# Send progress update for writing to file
progress_callback(
@@ -397,7 +435,9 @@ def run_research_process(research_id, query, mode, active_research, termination_
)
conn.commit()
conn.close()
- logger.info(f"Database updated successfully for research_id: {research_id}")
+ logger.info(
+ f"Database updated successfully for research_id: {research_id}"
+ )
# Send the final completion message
progress_callback(
@@ -408,25 +448,32 @@ def run_research_process(research_id, query, mode, active_research, termination_
# Clean up resources
logger.info(f"Cleaning up resources for research_id: {research_id}")
- cleanup_research_resources(research_id, active_research, termination_flags)
+ cleanup_research_resources(
+ research_id, active_research, termination_flags
+ )
logger.info(f"Resources cleaned up for research_id: {research_id}")
-
+
except Exception as inner_e:
- logger.error(f"Error during quick summary generation: {str(inner_e)}")
+ logger.error(
+ f"Error during quick summary generation: {str(inner_e)}"
+ )
logger.error(traceback.format_exc())
raise Exception(f"Error generating quick summary: {str(inner_e)}")
else:
- raise Exception("No research findings were generated. Please try again.")
+ raise Exception(
+ "No research findings were generated. Please try again."
+ )
else:
# Full Report
progress_callback(
"Generating detailed report...", 85, {"phase": "report_generation"}
)
-
+
from ...report_generator import IntegratedReportGenerator
+
report_generator = IntegratedReportGenerator()
final_report = report_generator.generate_report(results, query)
-
+
progress_callback(
"Report generation complete", 95, {"phase": "report_complete"}
)
@@ -501,7 +548,9 @@ def run_research_process(research_id, query, mode, active_research, termination_
"solution": "Start Ollama with 'ollama serve' or check if it's installed correctly."
}
elif "Error type: model_not_found" in user_friendly_error:
- user_friendly_error = "Required Ollama model not found. Please pull the model first."
+ user_friendly_error = (
+ "Required Ollama model not found. Please pull the model first."
+ )
error_context = {
"solution": "Run 'ollama pull mistral' to download the required model."
}
@@ -568,10 +617,15 @@ def run_research_process(research_id, query, mode, active_research, termination_
try:
from ..services.socket_service import emit_to_subscribers
- emit_to_subscribers("research_progress", research_id, {"status": status, "error": message})
+
+ emit_to_subscribers(
+ "research_progress",
+ research_id,
+ {"status": status, "error": message},
+ )
except Exception as socket_error:
logger.error(f"Failed to emit error via socket: {str(socket_error)}")
-
+
except Exception as inner_e:
logger.error(f"Error in error handler: {str(inner_e)}")
logger.error(traceback.format_exc())
@@ -579,10 +633,11 @@ def run_research_process(research_id, query, mode, active_research, termination_
# Clean up resources
cleanup_research_resources(research_id, active_research, termination_flags)
+
def cleanup_research_resources(research_id, active_research, termination_flags):
"""
Clean up resources for a completed research.
-
+
Args:
research_id: The ID of the research
active_research: Dictionary of active research processes
@@ -617,9 +672,10 @@ def cleanup_research_resources(research_id, active_research, termination_flags):
try:
# Import here to avoid circular imports
from ..routes.research_routes import get_globals
+
globals_dict = get_globals()
- socket_subscriptions = globals_dict.get('socket_subscriptions', {})
-
+ socket_subscriptions = globals_dict.get("socket_subscriptions", {})
+
# Send a final message to any remaining subscribers with explicit status
if research_id in socket_subscriptions and socket_subscriptions[research_id]:
# Use the proper status message based on database status
@@ -636,18 +692,22 @@ def cleanup_research_resources(research_id, active_research, termination_flags):
"progress": 100,
}
- logger.info(f"Sending final {current_status} socket message for research {research_id}")
-
+ logger.info(
+ f"Sending final {current_status} socket message for research {research_id}"
+ )
+
from ..services.socket_service import emit_to_subscribers
+
emit_to_subscribers("research_progress", research_id, final_message)
-
+
except Exception as e:
logger.error(f"Error sending final cleanup message: {e}")
+
def handle_termination(research_id, active_research, termination_flags):
"""
Handle the termination of a research process.
-
+
Args:
research_id: The ID of the research
active_research: Dictionary of active research processes
@@ -656,7 +716,7 @@ def handle_termination(research_id, active_research, termination_flags):
# Explicitly set the status to suspended in the database
conn = get_db_connection()
cursor = conn.cursor()
-
+
# Calculate duration up to termination point - using UTC consistently
now = datetime.utcnow()
completed_at = now.isoformat()
@@ -682,25 +742,27 @@ def handle_termination(research_id, active_research, termination_flags):
# Clean up resources
cleanup_research_resources(research_id, active_research, termination_flags)
+
def cancel_research(research_id):
"""
Cancel/terminate a research process
-
+
Args:
research_id: The ID of the research to cancel
-
+
Returns:
bool: True if the research was found and cancelled, False otherwise
"""
# Import globals from research routes
from ..routes.research_routes import get_globals
+
globals_dict = get_globals()
- active_research = globals_dict['active_research']
- termination_flags = globals_dict['termination_flags']
-
+ active_research = globals_dict["active_research"]
+ termination_flags = globals_dict["termination_flags"]
+
# Set termination flag
termination_flags[research_id] = True
-
+
# Check if the research is active
if research_id in active_research:
# Call handle_termination to update database
@@ -709,23 +771,26 @@ def cancel_research(research_id):
else:
# Update database directly if not found in active_research
from ..models.database import get_db_connection
+
conn = get_db_connection()
cursor = conn.cursor()
-
+
# First check if the research exists
- cursor.execute("SELECT status FROM research_history WHERE id = ?", (research_id,))
+ cursor.execute(
+ "SELECT status FROM research_history WHERE id = ?", (research_id,)
+ )
result = cursor.fetchone()
-
+
if not result:
conn.close()
return False
-
+
# If it exists but isn't in active_research, still update status
cursor.execute(
"UPDATE research_history SET status = ? WHERE id = ?",
- ("suspended", research_id)
+ ("suspended", research_id),
)
conn.commit()
conn.close()
-
- return True
\ No newline at end of file
+
+ return True
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index 0cf8483dff..58cd98fdde 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -1,17 +1,17 @@
import json
import logging
import os
-import toml
from pathlib import Path
from typing import Any, Dict, List, Optional, Type, Union
-from sqlalchemy.exc import SQLAlchemyError
-from sqlalchemy.orm import Session
+import toml
from sqlalchemy import create_engine
-from sqlalchemy.orm import sessionmaker
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.sql import func
-from ...config.config_files import get_config_dir, settings as dynaconf_settings
+from ...config.config_files import get_config_dir
+from ...config.config_files import settings as dynaconf_settings
from ..database.models import Setting, SettingType
from ..models.settings import (
AppSetting,
@@ -19,22 +19,23 @@ from ..models.settings import (
LLMSetting,
ReportSetting,
SearchSetting,
- SettingsGroup
+ SettingsGroup,
)
# Setup logging
logger = logging.getLogger(__name__)
+
class SettingsManager:
"""
Manager for handling application settings with database storage and file fallback.
Provides methods to get and set settings, with the ability to override settings in memory.
"""
-
+
def __init__(self, db_session: Optional[Session] = None):
"""
Initialize the settings manager
-
+
Args:
db_session: SQLAlchemy session for database operations
"""
@@ -44,33 +45,33 @@ class SettingsManager:
self.search_engines_file = self.config_dir / "search_engines.toml"
self.collections_file = self.config_dir / "local_collections.toml"
self.secrets_file = self.config_dir / ".secrets.toml"
-
+
# In-memory cache for settings
self._settings_cache: Dict[str, Any] = {}
-
+
# Load settings if session is provided
if db_session:
self._load_settings_from_db()
-
+
# If cache is empty, fall back to file-based settings
if not self._settings_cache:
self._load_settings_from_files()
-
+
def get_setting(self, key: str, default: Any = None) -> Any:
"""
Get the value of a setting by key
-
+
Args:
key: Setting key
default: Default value if setting is not found
-
+
Returns:
Setting value or default
"""
# Check in-memory cache first
if key in self._settings_cache:
return self._settings_cache[key]
-
+
# Try to get from database
if self.db_session:
setting = self.db_session.query(Setting).filter(Setting.key == key).first()
@@ -78,88 +79,94 @@ class SettingsManager:
# Cache the setting
self._settings_cache[key] = setting.value
return setting.value
-
+
# Fall back to dynaconf
return dynaconf_settings.get(key, default)
-
+
def set_setting(self, key: str, value: Any, commit: bool = True) -> bool:
"""
Set a setting value
-
+
Args:
key: Setting key
value: Setting value
commit: Whether to commit the change
-
+
Returns:
True if successful, False otherwise
"""
# Update cache
self._settings_cache[key] = value
-
+
# Update database if available
if self.db_session:
try:
- setting = self.db_session.query(Setting).filter(Setting.key == key).first()
+ setting = (
+ self.db_session.query(Setting).filter(Setting.key == key).first()
+ )
if setting:
setting.value = value
- setting.updated_at = func.now() # Explicitly set the current timestamp
+ setting.updated_at = (
+ func.now()
+ ) # Explicitly set the current timestamp
else:
# Determine setting type from key
setting_type = SettingType.APP
- if key.startswith('llm.'):
+ if key.startswith("llm."):
setting_type = SettingType.LLM
- elif key.startswith('search.'):
+ elif key.startswith("search."):
setting_type = SettingType.SEARCH
- elif key.startswith('report.'):
+ elif key.startswith("report."):
setting_type = SettingType.REPORT
-
+
# Create a new setting
new_setting = Setting(
key=key,
value=value,
type=setting_type,
- name=key.split('.')[-1].replace('_', ' ').title(),
- description=f"Setting for {key}"
+ name=key.split(".")[-1].replace("_", " ").title(),
+ description=f"Setting for {key}",
)
self.db_session.add(new_setting)
-
+
if commit:
self.db_session.commit()
-
+
return True
except SQLAlchemyError as e:
logger.error(f"Error setting value for {key}: {e}")
self.db_session.rollback()
return False
-
+
# No database session, only update cache
return True
-
- def get_all_settings(self, setting_type: Optional[SettingType] = None) -> Dict[str, Any]:
+
+ def get_all_settings(
+ self, setting_type: Optional[SettingType] = None
+ ) -> Dict[str, Any]:
"""
Get all settings, optionally filtered by type
-
+
Args:
setting_type: Optional filter by setting type
-
+
Returns:
Dictionary of settings
"""
result = {}
-
+
# Get from database if available
if self.db_session:
query = self.db_session.query(Setting)
if setting_type:
query = query.filter(Setting.type == setting_type)
-
+
for setting in query.all():
result[setting.key] = setting.value
-
+
# Merge with cache (cache takes precedence)
result.update(self._settings_cache)
-
+
# Fall back to dynaconf for any settings not in DB or cache
if not result:
# Get from dynaconf
@@ -172,43 +179,43 @@ class SettingsManager:
result[full_key] = value
else:
# Get all settings from dynaconf
- for section in ['llm', 'search', 'report', 'app']:
+ for section in ["llm", "search", "report", "app"]:
section_obj = getattr(dynaconf_settings, section, {})
for key, value in section_obj.items():
full_key = f"{section}.{key}"
result[full_key] = value
-
+
return result
-
+
def create_or_update_setting(
- self,
- setting: Union[BaseSetting, Dict[str, Any]],
- commit: bool = True
+ self, setting: Union[BaseSetting, Dict[str, Any]], commit: bool = True
) -> Optional[Setting]:
"""
Create or update a setting
-
+
Args:
setting: Setting object or dictionary
commit: Whether to commit the change
-
+
Returns:
The created or updated Setting model, or None if failed
"""
if not self.db_session:
- logger.warning("No database session available, cannot create/update setting")
+ logger.warning(
+ "No database session available, cannot create/update setting"
+ )
return None
-
+
# Convert dict to BaseSetting if needed
if isinstance(setting, dict):
# Determine type from key if not specified
- if 'type' not in setting and 'key' in setting:
- key = setting['key']
- if key.startswith('llm.'):
+ if "type" not in setting and "key" in setting:
+ key = setting["key"]
+ if key.startswith("llm."):
setting_obj = LLMSetting(**setting)
- elif key.startswith('search.'):
+ elif key.startswith("search."):
setting_obj = SearchSetting(**setting)
- elif key.startswith('report.'):
+ elif key.startswith("report."):
setting_obj = ReportSetting(**setting)
else:
setting_obj = AppSetting(**setting)
@@ -217,11 +224,15 @@ class SettingsManager:
setting_obj = BaseSetting(**setting)
else:
setting_obj = setting
-
+
try:
# Check if setting exists
- db_setting = self.db_session.query(Setting).filter(Setting.key == setting_obj.key).first()
-
+ db_setting = (
+ self.db_session.query(Setting)
+ .filter(Setting.key == setting_obj.key)
+ .first()
+ )
+
if db_setting:
# Update existing setting
db_setting.value = setting_obj.value
@@ -235,7 +246,9 @@ class SettingsManager:
db_setting.step = setting_obj.step
db_setting.visible = setting_obj.visible
db_setting.editable = setting_obj.editable
- db_setting.updated_at = func.now() # Explicitly set the current timestamp
+ db_setting.updated_at = (
+ func.now()
+ ) # Explicitly set the current timestamp
else:
# Create new setting
db_setting = Setting(
@@ -251,123 +264,135 @@ class SettingsManager:
max_value=setting_obj.max_value,
step=setting_obj.step,
visible=setting_obj.visible,
- editable=setting_obj.editable
+ editable=setting_obj.editable,
)
self.db_session.add(db_setting)
-
+
# Update cache
self._settings_cache[setting_obj.key] = setting_obj.value
-
+
if commit:
self.db_session.commit()
-
+
return db_setting
-
+
except SQLAlchemyError as e:
logger.error(f"Error creating/updating setting {setting_obj.key}: {e}")
self.db_session.rollback()
return None
-
+
def delete_setting(self, key: str, commit: bool = True) -> bool:
"""
Delete a setting
-
+
Args:
key: Setting key
commit: Whether to commit the change
-
+
Returns:
True if successful, False otherwise
"""
if not self.db_session:
logger.warning("No database session available, cannot delete setting")
return False
-
+
try:
# Remove from cache
if key in self._settings_cache:
del self._settings_cache[key]
-
+
# Remove from database
result = self.db_session.query(Setting).filter(Setting.key == key).delete()
-
+
if commit:
self.db_session.commit()
-
+
return result > 0
except SQLAlchemyError as e:
logger.error(f"Error deleting setting {key}: {e}")
self.db_session.rollback()
return False
-
+
def export_to_file(self, setting_type: Optional[SettingType] = None) -> bool:
"""
Export settings to file
-
+
Args:
setting_type: Type of settings to export (or all if None)
-
+
Returns:
True if successful, False otherwise
"""
try:
# Get settings
settings = self.get_all_settings(setting_type)
-
+
# Group by section
sections = {}
for key, value in settings.items():
# Split key into section and name
- parts = key.split('.', 1)
+ parts = key.split(".", 1)
if len(parts) == 2:
section, name = parts
if section not in sections:
sections[section] = {}
sections[section][name] = value
-
+
# Write to appropriate file
if setting_type == SettingType.LLM:
file_path = self.settings_file
- section_name = 'llm'
+ section_name = "llm"
elif setting_type == SettingType.SEARCH:
file_path = self.search_engines_file
- section_name = 'search'
+ section_name = "search"
elif setting_type == SettingType.REPORT:
file_path = self.settings_file
- section_name = 'report'
+ section_name = "report"
else:
# Write all sections to appropriate files
for section_name, section_data in sections.items():
- if section_name == 'search':
- self._write_section_to_file(self.search_engines_file, section_name, section_data)
+ if section_name == "search":
+ self._write_section_to_file(
+ self.search_engines_file, section_name, section_data
+ )
else:
- self._write_section_to_file(self.settings_file, section_name, section_data)
+ self._write_section_to_file(
+ self.settings_file, section_name, section_data
+ )
return True
-
+
# Write specific section
if section_name in sections:
- return self._write_section_to_file(file_path, section_name, sections[section_name])
-
+ return self._write_section_to_file(
+ file_path, section_name, sections[section_name]
+ )
+
return False
-
+
except Exception as e:
logger.error(f"Error exporting settings to file: {e}")
return False
-
- def import_from_file(self, setting_type: Optional[SettingType] = None, commit: bool = True) -> bool:
+
+ def import_from_file(
+ self, setting_type: Optional[SettingType] = None, commit: bool = True
+ ) -> bool:
"""
Import settings from file
-
+
Args:
setting_type: Type of settings to import (or all if None)
commit: Whether to commit changes to database
-
+
Returns:
True if successful, False otherwise
"""
try:
# Determine file path
- if setting_type == SettingType.LLM or setting_type == SettingType.APP or setting_type == SettingType.REPORT:
+ if (
+ setting_type == SettingType.LLM
+ or setting_type == SettingType.APP
+ or setting_type == SettingType.REPORT
+ ):
file_path = self.settings_file
elif setting_type == SettingType.SEARCH:
file_path = self.search_engines_file
@@ -378,99 +403,103 @@ class SettingsManager:
success &= self.import_from_file(SettingType.SEARCH, commit=False)
success &= self.import_from_file(SettingType.REPORT, commit=False)
success &= self.import_from_file(SettingType.APP, commit=False)
-
+
# Commit all changes at once
if commit and self.db_session:
self.db_session.commit()
-
+
return success
-
+
# Read from file
if not os.path.exists(file_path):
logger.warning(f"Settings file does not exist: {file_path}")
return False
-
+
# Parse TOML file
- with open(file_path, 'r') as f:
+ with open(file_path, "r") as f:
file_data = toml.load(f)
-
+
# Extract section based on setting type
section_name = setting_type.value.lower() if setting_type else None
if section_name and section_name in file_data:
section_data = file_data[section_name]
else:
section_data = file_data
-
+
# Import settings
for key, value in section_data.items():
if section_name:
full_key = f"{section_name}.{key}"
else:
# Try to determine section from key structure
- if '.' in key:
+ if "." in key:
full_key = key
else:
# Assume it's an app setting
full_key = f"app.{key}"
-
+
self.set_setting(full_key, value, commit=False)
-
+
# Commit if requested
if commit and self.db_session:
self.db_session.commit()
-
+
return True
-
+
except Exception as e:
logger.error(f"Error importing settings from file: {e}")
if self.db_session:
self.db_session.rollback()
return False
-
+
def _load_settings_from_db(self):
"""Load all settings from database into memory cache"""
if not self.db_session:
return
-
+
try:
for setting in self.db_session.query(Setting).all():
self._settings_cache[setting.key] = setting.value
except SQLAlchemyError as e:
logger.error(f"Error loading settings from database: {e}")
-
+
def _load_settings_from_files(self):
"""Load settings from files into memory cache"""
# Load from main settings file
if os.path.exists(self.settings_file):
try:
- with open(self.settings_file, 'r') as f:
+ with open(self.settings_file, "r") as f:
data = toml.load(f)
for section, values in data.items():
for key, value in values.items():
self._settings_cache[f"{section}.{key}"] = value
except Exception as e:
logger.error(f"Error loading settings from {self.settings_file}: {e}")
-
+
# Load from search engines file
if os.path.exists(self.search_engines_file):
try:
- with open(self.search_engines_file, 'r') as f:
+ with open(self.search_engines_file, "r") as f:
data = toml.load(f)
- if 'search' in data:
- for key, value in data['search'].items():
+ if "search" in data:
+ for key, value in data["search"].items():
self._settings_cache[f"search.{key}"] = value
except Exception as e:
- logger.error(f"Error loading settings from {self.search_engines_file}: {e}")
-
- def _write_section_to_file(self, file_path: Path, section: str, data: Dict[str, Any]) -> bool:
+ logger.error(
+ f"Error loading settings from {self.search_engines_file}: {e}"
+ )
+
+ def _write_section_to_file(
+ self, file_path: Path, section: str, data: Dict[str, Any]
+ ) -> bool:
"""
Write a section of settings to a TOML file
-
+
Args:
file_path: Path to the file
section: Section name
data: Section data
-
+
Returns:
True if successful, False otherwise
"""
@@ -478,41 +507,41 @@ class SettingsManager:
# Create file if it doesn't exist
if not os.path.exists(file_path):
file_path.parent.mkdir(parents=True, exist_ok=True)
- with open(file_path, 'w') as f:
+ with open(file_path, "w") as f:
f.write(f"[{section}]\n")
-
+
# Read existing file
- with open(file_path, 'r') as f:
+ with open(file_path, "r") as f:
file_data = toml.load(f)
-
+
# Update section
file_data[section] = data
-
+
# Write back to file
- with open(file_path, 'w') as f:
+ with open(file_path, "w") as f:
toml.dump(file_data, f)
-
+
return True
except Exception as e:
logger.error(f"Error writing section {section} to {file_path}: {e}")
return False
-
+
@classmethod
- def get_instance(cls, db_session: Optional[Session] = None) -> 'SettingsManager':
+ def get_instance(cls, db_session: Optional[Session] = None) -> "SettingsManager":
"""
Get a singleton instance of the settings manager
-
+
Args:
db_session: Optional database session
-
+
Returns:
SettingsManager instance
"""
- if not hasattr(cls, '_instance'):
+ if not hasattr(cls, "_instance"):
cls._instance = cls(db_session)
elif db_session and not cls._instance.db_session:
# Update existing instance with a session
cls._instance.db_session = db_session
cls._instance._load_settings_from_db()
-
- return cls._instance
\ No newline at end of file
+
+ return cls._instance
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index b4a0107810..67510c92d0 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -8,30 +8,32 @@ 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")
+
def emit_socket_event(event, data, room=None):
"""
Emit a socket event to clients.
-
+
Args:
event: The event name to emit
data: The data to send with the event
room: Optional room ID to send to specific client
-
+
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
-
+
try:
# If room is specified, only emit to that room
if room:
@@ -44,29 +46,30 @@ def emit_socket_event(event, data, room=None):
logger.error(f"Error emitting socket event {event}: {str(e)}")
return False
+
def emit_to_subscribers(event_base, research_id, data):
"""
Emit an event to all subscribers of a specific research.
-
+
Args:
event_base: Base event name (will be formatted with research_id)
research_id: ID of the research
data: The data to send with the event
-
+
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
-
+
try:
# Emit to the general channel for the research
full_event = f"{event_base}_{research_id}"
socketio.emit(full_event, data)
-
+
# Emit to specific subscribers
if research_id in socket_subscriptions and socket_subscriptions[research_id]:
for sid in socket_subscriptions[research_id]:
@@ -74,17 +77,21 @@ def emit_to_subscribers(event_base, research_id, data):
socketio.emit(full_event, data, room=sid)
except Exception as sub_err:
logger.error(f"Error emitting to subscriber {sid}: {str(sub_err)}")
-
+
return True
except Exception as e:
- logger.error(f"Error emitting to subscribers for research {research_id}: {str(e)}")
+ logger.error(
+ f"Error emitting to subscribers for research {research_id}: {str(e)}"
+ )
return False
+
# Socket event handlers moved from app.py
def handle_connect(request):
"""Handle client connection"""
logger.info(f"Client connected: {request.sid}")
+
def handle_disconnect(request):
"""Handle client disconnection"""
try:
@@ -100,12 +107,14 @@ def handle_disconnect(request):
except Exception as e:
logger.error(f"Error handling disconnect: {e}")
+
def handle_subscribe(data, request, active_research=None):
"""Handle client subscription to research updates"""
- from ..models.database import get_db_connection
import sqlite3
from datetime import datetime
-
+
+ from ..models.database import get_db_connection
+
research_id = data.get("research_id")
if research_id:
# First check if this research is still active
@@ -148,7 +157,7 @@ def handle_subscribe(data, request, active_research=None):
"status": "in_progress",
"log_entry": latest_log,
},
- room=request.sid
+ room=request.sid,
)
elif status in ["completed", "failed", "suspended"]:
# Send final status for completed research
@@ -177,11 +186,16 @@ def handle_subscribe(data, request, active_research=None):
},
},
},
- room=request.sid
+ room=request.sid,
)
else:
# Research not found
- emit_socket_event("error", {"message": f"Research ID {research_id} not found"}, room=request.sid)
+ emit_socket_event(
+ "error",
+ {"message": f"Research ID {research_id} not found"},
+ room=request.sid,
+ )
+
def handle_socket_error(e):
"""Handle Socket.IO errors"""
@@ -189,8 +203,9 @@ def handle_socket_error(e):
# Don't propagate exceptions to avoid crashing the server
return False
+
def handle_default_error(e):
"""Handle unhandled Socket.IO errors"""
logger.error(f"Unhandled Socket.IO error: {str(e)}")
# Don't propagate exceptions to avoid crashing the server
- return False
\ No newline at end of file
+ return False
diff --git a/src/local_deep_research/web/utils/formatters.py b/src/local_deep_research/web/utils/formatters.py
index 9b51accd0d..344fe4483a 100644
--- a/src/local_deep_research/web/utils/formatters.py
+++ b/src/local_deep_research/web/utils/formatters.py
@@ -4,6 +4,7 @@ import traceback
# Initialize logger
logger = logging.getLogger(__name__)
+
def convert_debug_to_markdown(raw_text, query):
"""
Convert the debug-formatted text to clean markdown.
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index 47e1ed2c7a..02cd398725 100644
--- a/src/local_deep_research/web_search_engines/search_engine_factory.py
+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py
@@ -2,7 +2,7 @@ import importlib
import inspect
import logging
import os
-from typing import Any, Dict, Optional, Union, List
+from typing import Any, Dict, List, Optional, Union
from .search_engine_base import BaseSearchEngine
from .search_engines_config import DEFAULT_SEARCH_ENGINE, SEARCH_ENGINES
@@ -231,38 +231,40 @@ def _create_full_search_wrapper(
return base_engine
-def get_available_engines(include_api_key_services: bool = True) -> Union[Dict[str, str], List[str]]:
+def get_available_engines(
+ include_api_key_services: bool = True,
+) -> Union[Dict[str, str], List[str]]:
"""
Get all available search engines from the configuration.
-
+
Args:
include_api_key_services: Whether to include engines that require API keys
-
+
Returns:
Dictionary of engine names mapped to descriptions, or a list of engine names
"""
try:
# Get engines from SEARCH_ENGINES dict
available_engines = {}
-
+
for name, config in SEARCH_ENGINES.items():
# Skip hidden engines (those that start with _)
- if name.startswith('_'):
+ if name.startswith("_"):
continue
-
+
# Skip engines that require API keys if requested
- if not include_api_key_services and config.get('requires_api_key', False):
+ if not include_api_key_services and config.get("requires_api_key", False):
continue
-
+
# Add to available engines with display name
- strengths = config.get('strengths', [])
- description = name.replace('_', ' ').title()
-
+ strengths = config.get("strengths", [])
+ description = name.replace("_", " ").title()
+
if strengths and len(strengths) > 0:
description += f" - {strengths[0]}"
-
+
available_engines[name] = description
-
+
return available_engines
except Exception as e:
logger.error(f"Error getting available engines: {e}")