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.

feat: Enhance search system and UI with advanced options and logging

hashedviking457d630d21b4
diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.py
index 37af40c2ad..9fd2f66b4a 100644
--- a/src/local_deep_research/config/search_config.py
+++ b/src/local_deep_research/config/search_config.py
@@ -16,19 +16,26 @@ SEARCH_SNIPPETS_ONLY = settings.search.snippets_only
# Expose get_search function
-def get_search(search_tool=None):
+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
"""
# Use specified tool or default from settings
tool = search_tool or settings.search.tool
- logger.info(f"Search tool is: {tool}")
+ logger.info(f"Creating search engine with tool: {tool}")
+
+ # Get LLM instance (use provided or get fresh one)
+ llm = llm_instance or get_llm()
# Get search parameters
params = {
"search_tool": tool,
- "llm_instance": get_llm(),
+ "llm_instance": llm,
"max_results": settings.search.max_results,
"region": settings.search.region,
"time_period": settings.search.time_period,
@@ -37,7 +44,17 @@ def get_search(search_tool=None):
"search_language": settings.search.search_language,
"max_filtered_results": settings.search.max_filtered_results,
}
- logger.info(f"Search config params: {params}")
-
- # Create and return search engine
- return factory_get_search(**params)
+
+ # Log parameters for debugging
+ 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__}")
+ else:
+ logger.error(f"Failed to create search engine for tool: {tool}")
+
+ return search_engine
diff --git a/src/local_deep_research/defaults/search_engines.toml b/src/local_deep_research/defaults/search_engines.toml
index 1e6ca8bbb6..4c298519d4 100644
--- a/src/local_deep_research/defaults/search_engines.toml
+++ b/src/local_deep_research/defaults/search_engines.toml
@@ -95,6 +95,32 @@ time_period = "y"
safe_search = true
search_language = "English"
+[searxng]
+module_path = ".engines.search_engine_searxng"
+class_name = "SearXNGSearchEngine"
+requires_api_key = true
+api_key_env = "SEARXNG_INSTANCE"
+reliability = 0.8
+strengths = [
+ "privacy-focused", "metasearch engine", "self-hosted",
+ "no tracking", "configurable", "multiple engines in one"
+]
+weaknesses = [
+ "requires self-hosting", "depends on other search engines",
+ "may be rate limited by underlying engines"
+]
+supports_full_search = true
+full_search_module = ".engines.full_search"
+full_search_class = "FullSearchResults"
+
+[searxng.default_params]
+max_results = 15
+categories = ["general"]
+language = "en"
+safe_search = 1
+delay_between_requests = 2.0
+include_full_content = true
+
[google_pse]
module_path = ".engines.search_engine_google_pse"
class_name = "GooglePSESearchEngine"
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 198a9205fe..eb21fa8da2 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -34,6 +34,18 @@ 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')
+ 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})")
# Check if search is available, log warning if not
if self.search is None:
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 0064ecbb42..73d53f88a2 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -43,6 +43,13 @@ def create_app():
# App configuration
app.config["SECRET_KEY"] = "deep-research-secret-key"
+ # Database configuration
+ db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', 'data', 'deep_research.db'))
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
+ app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
+ app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
+ app.config["SQLALCHEMY_ECHO"] = False
+
# Initialize extensions
socketio = SocketIO(
app,
diff --git a/src/local_deep_research/web/database/migrations.py b/src/local_deep_research/web/database/migrations.py
index 0d8f1f6c1e..f931e1ebde 100644
--- a/src/local_deep_research/web/database/migrations.py
+++ b/src/local_deep_research/web/database/migrations.py
@@ -225,8 +225,8 @@ def setup_predefined_settings(db_session):
{
"key": "app.research_iterations",
"name": "Research Iterations",
- "description": "Number of research iterations to perform",
- "category": "app_research",
+ "description": "Number of research cycles to perform",
+ "category": "app_parameters",
"ui_element": "number",
"min_value": 1,
"max_value": 5,
@@ -235,8 +235,8 @@ def setup_predefined_settings(db_session):
{
"key": "app.questions_per_iteration",
"name": "Questions Per Iteration",
- "description": "Number of follow-up questions per iteration",
- "category": "app_research",
+ "description": "Number of questions to generate per research cycle",
+ "category": "app_parameters",
"ui_element": "number",
"min_value": 1,
"max_value": 10,
@@ -245,8 +245,8 @@ def setup_predefined_settings(db_session):
{
"key": "app.enable_notifications",
"name": "Enable Notifications",
- "description": "Enable sound notifications when research completes",
- "category": "app_interface",
+ "description": "Enable browser notifications for research events",
+ "category": "app_parameters",
"ui_element": "checkbox",
"value": True
},
@@ -265,30 +265,77 @@ def setup_predefined_settings(db_session):
}
]
- # Combine all settings
+ # 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
- # Create or update each setting
+ # 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."):
+ setting_type = SettingType.SEARCH
+ elif key.startswith("report."):
+ 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 == setting_dict["key"]).first()
+ existing = db_session.query(Setting).filter(Setting.key == key).first()
if existing:
- # Keep existing value, update metadata
- current_value = existing.value
- setting_dict["value"] = current_value
-
- # Create or update setting
- settings_manager.create_or_update_setting(setting_dict, commit=False)
+ # 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.category = setting_dict.get("category", existing.category)
+ 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"]
+ else:
+ # Create new setting
+ logger.info(f"Creating new setting: {key}")
+ setting = Setting(
+ key=key,
+ value=setting_dict.get("value"),
+ type=setting_type,
+ 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"),
+ options=setting_dict.get("options"),
+ min_value=setting_dict.get("min_value"),
+ max_value=setting_dict.get("max_value"),
+ step=setting_dict.get("step"),
+ visible=setting_dict.get("visible", 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 setting up predefined setting {setting_dict['key']}: {e}")
+ logger.error(f"Error ensuring setting {setting_dict.get('key')}: {e}")
+ db_session.rollback()
- # Commit all changes
- try:
- db_session.commit()
- logger.info("Successfully set up predefined settings")
- except Exception as e:
- db_session.rollback()
- logger.error(f"Error committing predefined settings: {e}")
\ No newline at end of file
+ # Log completion
+ logger.info("Predefined settings setup complete")
\ No newline at end of file
diff --git a/src/local_deep_research/web/database/models.py b/src/local_deep_research/web/database/models.py
index 5933d1b546..773d0c8486 100644
--- a/src/local_deep_research/web/database/models.py
+++ b/src/local_deep_research/web/database/models.py
@@ -64,7 +64,7 @@ class ResearchReport(Base):
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)
- metadata = Column(JSON, nullable=True) # Additional metadata about the report
+ report_metadata = Column(JSON, nullable=True) # Additional metadata about the report
# Relationships
research = relationship("Research", back_populates="report")
diff --git a/src/local_deep_research/web/models/settings.py b/src/local_deep_research/web/models/settings.py
index f720c60dc4..eda18b154b 100644
--- a/src/local_deep_research/web/models/settings.py
+++ b/src/local_deep_research/web/models/settings.py
@@ -1,7 +1,7 @@
from enum import Enum
from typing import Any, Dict, List, Optional, Union
-from pydantic import BaseModel, Field, validator
+from pydantic import BaseModel, Field, field_validator
class SettingType(str, Enum):
"""Types of settings in the system"""
@@ -27,13 +27,13 @@ class BaseSetting(BaseModel):
editable: bool = True
class Config:
- orm_mode = True
+ from_attributes = True
class LLMSetting(BaseSetting):
"""LLM-specific settings"""
type: SettingType = SettingType.LLM
- @validator('key')
+ @field_validator('key')
def validate_llm_key(cls, v):
# Ensure LLM settings follow a convention
if not v.startswith('llm.'):
@@ -44,7 +44,7 @@ class SearchSetting(BaseSetting):
"""Search-specific settings"""
type: SettingType = SettingType.SEARCH
- @validator('key')
+ @field_validator('key')
def validate_search_key(cls, v):
# Ensure search settings follow a convention
if not v.startswith('search.'):
@@ -55,7 +55,7 @@ class ReportSetting(BaseSetting):
"""Report generation settings"""
type: SettingType = SettingType.REPORT
- @validator('key')
+ @field_validator('key')
def validate_report_key(cls, v):
# Ensure report settings follow a convention
if not v.startswith('report.'):
@@ -66,7 +66,7 @@ class AppSetting(BaseSetting):
"""Application-wide settings"""
type: SettingType = SettingType.APP
- @validator('key')
+ @field_validator('key')
def validate_app_key(cls, v):
# Ensure app settings follow a convention
if not v.startswith('app.'):
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 1da7337c0f..91fce975f5 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -110,6 +110,18 @@ 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")
+ max_results = data.get("max_results")
+ 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}")
if not query:
return jsonify({"status": "error", "message": "Query is required"}), 400
@@ -164,8 +176,19 @@ def start_research():
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,
+ "search_engine": search_engine,
+ "max_results": max_results,
+ "time_period": time_period,
+ "iterations": iterations,
+ "questions_per_iteration": questions_per_iteration
+ }
+
cursor.execute(
- "INSERT INTO research_history (query, mode, status, created_at, progress_log) VALUES (?, ?, ?, ?, ?)",
+ "INSERT INTO research_history (query, mode, status, created_at, progress_log, metadata) VALUES (?, ?, ?, ?, ?, ?)",
(
query,
mode,
@@ -174,15 +197,19 @@ def start_research():
json.dumps(
[{"time": created_at, "message": "Research started", "progress": 0}]
),
+ json.dumps(research_settings)
),
)
research_id = cursor.lastrowid
conn.commit()
conn.close()
- # Start the research process
+ # Start the research process with the selected parameters
research_thread = start_research_process(research_id, query, mode,
- active_research, termination_flags, run_research_process)
+ 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})
diff --git a/src/local_deep_research/web/routes/settings_api.py b/src/local_deep_research/web/routes/settings_api.py
index 219e35f63c..ed3600d891 100644
--- a/src/local_deep_research/web/routes/settings_api.py
+++ b/src/local_deep_research/web/routes/settings_api.py
@@ -12,7 +12,7 @@ from ..models.settings import BaseSetting, SettingsGroup
logger = logging.getLogger(__name__)
# Create a Blueprint for settings API
-settings_api_bp = Blueprint("settings_api", __name__, url_prefix="/api/settings")
+settings_api_bp = Blueprint("settings_api", __name__, url_prefix="/")
def get_db_session() -> Session:
"""Get the database session from the app context"""
@@ -288,4 +288,209 @@ def get_ui_elements():
return jsonify({"ui_elements": ui_elements})
except Exception as e:
logger.error(f"Error getting UI elements: {e}")
- return jsonify({"error": str(e)}), 500
\ No newline at end of file
+ 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
+
+ # Get available providers
+ providers = get_available_providers()
+
+ # Add more Ollama models if available
+ 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")
+ )
+
+ # 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']
+ else:
+ # Older Ollama API versions might return a simpler structure
+ 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')
+ if model_name:
+ # Format label to be more readable
+ 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
+ })
+
+ # 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()
+ ],
+ "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']
+ }
+
+ # Format as options for dropdown
+ engine_options = [
+ {"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
+ })
+
+ # 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
+
+ # 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}
+ else:
+ engines_dict = search_engines
+
+ # Make sure searxng is included
+ 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()}
+ for key, value in engines_dict.items()
+ ]
+
+ 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",
+ "pubmed": "PubMed Medical",
+ "github": "GitHub Code",
+ "searxng": "SearXNG (Self-hosted)",
+ "serpapi": "SerpAPI (Google)",
+ "google_pse": "Google PSE",
+ "auto": "Auto-select"
+ }
+
+ engine_options = [
+ {"value": key, "label": value}
+ for key, value in defaults.items()
+ ]
+
+ 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
+ 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
+
+ # 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':
+ 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:
+ # Create a display name from the key
+ 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
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 29eafde49c..5a476b0153 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -15,7 +15,7 @@ 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):
+def start_research_process(research_id, query, mode, active_research, termination_flags, run_research_callback, **kwargs):
"""
Start a research process in a background thread.
@@ -26,6 +26,7 @@ def start_research_process(research_id, query, mode, active_research, terminatio
active_research: Dictionary of active research processes
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
@@ -33,7 +34,8 @@ def start_research_process(research_id, query, mode, active_research, terminatio
# Start research process in a background thread
thread = threading.Thread(
target=run_research_callback,
- args=(research_id, query, mode, active_research, termination_flags)
+ args=(research_id, query, mode, active_research, termination_flags),
+ kwargs=kwargs
)
thread.daemon = True
thread.start()
@@ -43,11 +45,12 @@ def start_research_process(research_id, query, mode, active_research, terminatio
"progress": 0,
"status": "in_progress",
"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):
+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.
@@ -57,6 +60,7 @@ def run_research_process(research_id, query, mode, active_research, termination_
mode: The research mode (quick/detailed)
active_research: Dictionary of active research processes
termination_flags: Dictionary of termination flags
+ **kwargs: Additional parameters for the research (model, search_engine, etc.)
"""
try:
# Check if this research has been terminated before we even start
@@ -66,7 +70,18 @@ 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')
+
+ # 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}")
+
# Set up the AI Context Manager
output_dir = os.path.join(OUTPUT_DIR, f"research_{research_id}")
os.makedirs(output_dir, exist_ok=True)
@@ -193,6 +208,73 @@ def run_research_process(research_id, query, mode, active_research, termination_
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}")
+
+ # Import configuration modules
+ 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:
+ # Temporarily override the model setting
+ original_model = settings.llm.model
+ settings.llm.model = model
+ system.model = get_llm()
+ # Restore original setting
+ settings.llm.model = original_model
+ 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)
+ 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)
+
+ # Restore original settings
+ settings.search.tool = original_search
+ if max_results:
+ settings.search.max_results = original_max_results
+ if time_period:
+ settings.search.time_period = original_time_period
+ if iterations:
+ 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)}")
+
# Run the search
progress_callback("Starting research process", 5, {"phase": "init"})
diff --git a/src/local_deep_research/web/services/settings_manager.py b/src/local_deep_research/web/services/settings_manager.py
index 6bd64124c7..0cf8483dff 100644
--- a/src/local_deep_research/web/services/settings_manager.py
+++ b/src/local_deep_research/web/services/settings_manager.py
@@ -9,6 +9,7 @@ from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
+from sqlalchemy.sql import func
from ...config.config_files import get_config_dir, settings as dynaconf_settings
from ..database.models import Setting, SettingType
@@ -88,21 +89,21 @@ class SettingsManager:
Args:
key: Setting key
value: Setting value
- commit: Whether to commit the change to the database
+ commit: Whether to commit the change
Returns:
True if successful, False otherwise
"""
- # Update in-memory cache
+ # Update cache
self._settings_cache[key] = value
- # Update in database if session exists
+ # Update database if available
if self.db_session:
try:
setting = self.db_session.query(Setting).filter(Setting.key == key).first()
if setting:
setting.value = value
- setting.updated_at = None # Let the database update this
+ setting.updated_at = func.now() # Explicitly set the current timestamp
else:
# Determine setting type from key
setting_type = SettingType.APP
@@ -234,7 +235,7 @@ class SettingsManager:
db_setting.step = setting_obj.step
db_setting.visible = setting_obj.visible
db_setting.editable = setting_obj.editable
- db_setting.updated_at = None # Let DB update this
+ db_setting.updated_at = func.now() # Explicitly set the current timestamp
else:
# Create new setting
db_setting = Setting(
diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.css
index d7d2d2e869..628d973a99 100644
--- a/src/local_deep_research/web/static/css/styles.css
+++ b/src/local_deep_research/web/static/css/styles.css
@@ -1418,4 +1418,125 @@ textarea:focus, input[type="text"]:focus {
.toast-warning i {
color: var(--warning-color);
+}
+
+/* Advanced Options */
+.advanced-options-toggle {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ margin: 1.5rem 0 1rem;
+ padding: 0.75rem 1rem;
+ cursor: pointer;
+ color: var(--accent-tertiary);
+ font-weight: 600;
+ transition: all 0.2s;
+ border-radius: 8px;
+ background-color: rgba(64, 191, 255, 0.05);
+ border: 1px solid rgba(64, 191, 255, 0.1);
+}
+
+.advanced-options-toggle:hover {
+ color: var(--accent-secondary);
+ background-color: rgba(110, 79, 246, 0.1);
+ border-color: rgba(110, 79, 246, 0.2);
+}
+
+.advanced-options-toggle .toggle-text {
+ margin-right: 0.5rem;
+}
+
+.advanced-options-toggle i {
+ transition: transform 0.3s ease;
+ margin-left: auto;
+}
+
+.advanced-options-toggle.open i {
+ transform: rotate(180deg);
+}
+
+.advanced-options-panel {
+ background-color: rgba(42, 42, 58, 0.5);
+ border-radius: 8px;
+ padding: 1.5rem;
+ margin-bottom: 1.5rem;
+ border: 1px solid var(--border-color);
+ display: none;
+ box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.1);
+}
+
+.form-row {
+ display: flex;
+ gap: 1.5rem;
+ margin-bottom: 1.5rem;
+}
+
+.form-group.half {
+ flex: 1;
+}
+
+.input-help {
+ display: block;
+ font-size: 0.8rem;
+ color: var(--text-muted);
+ margin-top: 0.5rem;
+}
+
+.form-options {
+ margin: 1.5rem 0;
+}
+
+.checkbox-label {
+ display: flex;
+ align-items: center;
+ cursor: pointer;
+ padding: 0.5rem;
+ border-radius: 4px;
+ transition: background-color 0.2s;
+}
+
+.checkbox-label:hover {
+ background-color: rgba(64, 191, 255, 0.05);
+}
+
+.checkbox-label input[type="checkbox"] {
+ margin-right: 0.75rem;
+}
+
+/* Improved form controls for advanced options */
+.form-control {
+ width: 100%;
+ padding: 0.75rem;
+ border-radius: 8px;
+ border: 1px solid var(--border-color);
+ background-color: var(--bg-secondary);
+ color: var(--text-primary);
+ font-family: inherit;
+ font-size: 0.95rem;
+ transition: border-color 0.2s, box-shadow 0.2s;
+}
+
+select.form-control {
+ appearance: none;
+ background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238a8aa0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
+ background-repeat: no-repeat;
+ background-position: right 0.75rem center;
+ background-size: 1rem;
+ padding-right: 2.5rem;
+}
+
+input[type="number"].form-control {
+ -moz-appearance: textfield;
+}
+
+input[type="number"].form-control::-webkit-outer-spin-button,
+input[type="number"].form-control::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+}
+
+.form-control:focus {
+ outline: none;
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.15);
}
\ No newline at end of file
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 34b698bb61..559b3908b6 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -9,6 +9,14 @@
let modeOptions = null;
let notificationToggle = null;
let startBtn = null;
+ let modelSelect = null;
+ let searchEngineSelect = null;
+ let maxResultsInput = null;
+ let timePeriodSelect = null;
+ let iterationsInput = null;
+ let questionsPerIterationInput = null;
+ let advancedToggle = null;
+ let advancedPanel = null;
/**
* Initialize the research component
@@ -20,6 +28,14 @@
modeOptions = document.querySelectorAll('.mode-option');
notificationToggle = document.getElementById('notification-toggle');
startBtn = document.getElementById('start-research-btn');
+ modelSelect = document.getElementById('model');
+ searchEngineSelect = document.getElementById('search_engine');
+ maxResultsInput = document.getElementById('max_results');
+ timePeriodSelect = document.getElementById('time_period');
+ iterationsInput = document.getElementById('iterations');
+ questionsPerIterationInput = document.getElementById('questions_per_iteration');
+ advancedToggle = document.querySelector('.advanced-options-toggle');
+ advancedPanel = document.querySelector('.advanced-options-panel');
if (!form || !queryInput || !modeOptions.length || !startBtn) {
console.error('Required DOM elements not found for research component');
@@ -29,6 +45,11 @@
// Set up event listeners
setupEventListeners();
+ // Load data
+ loadModelOptions();
+ loadSearchEngineOptions();
+ loadSettings();
+
console.log('Research component initialized');
}
@@ -49,6 +70,27 @@
// Form submission
form.addEventListener('submit', handleResearchSubmit);
+
+ // Advanced options toggle
+ if (advancedToggle && advancedPanel) {
+ // Set initial state (closed by default)
+ advancedPanel.style.display = 'none';
+ advancedToggle.classList.remove('open');
+
+ advancedToggle.addEventListener('click', function() {
+ const isVisible = advancedPanel.style.display === 'block';
+
+ // Toggle panel visibility
+ advancedPanel.style.display = isVisible ? 'none' : 'block';
+
+ // Toggle class for arrow rotation
+ if (isVisible) {
+ advancedToggle.classList.remove('open');
+ } else {
+ advancedToggle.classList.add('open');
+ }
+ });
+ }
}
/**
@@ -126,6 +168,12 @@
const query = queryInput.value.trim();
const activeMode = document.querySelector('.mode-option.active');
const mode = activeMode ? activeMode.dataset.mode : 'quick';
+ const model = modelSelect ? modelSelect.value : '';
+ const searchEngine = searchEngineSelect ? searchEngineSelect.value : '';
+ const maxResults = maxResultsInput ? maxResultsInput.value : '10';
+ const timePeriod = timePeriodSelect ? timePeriodSelect.value : 'all';
+ const iterations = iterationsInput ? iterationsInput.value : '2';
+ const questionsPerIteration = questionsPerIterationInput ? questionsPerIterationInput.value : '3';
const enableNotifications = notificationToggle ? notificationToggle.checked : true;
// Validate input
@@ -134,6 +182,9 @@
return;
}
+ // Debug selected values
+ console.log(`Starting research with model: ${model}, search engine: ${searchEngine}`);
+
// Disable form
setFormSubmitting(true);
@@ -146,29 +197,64 @@
return;
}
- // Start research process
- const response = await window.api.startResearch(query, mode);
+ // Prepare request payload - ensure consistent property names with backend
+ const payload = {
+ query,
+ mode,
+ model,
+ search_engine: searchEngine, // Make sure these match what backend expects
+ search_tool: searchEngine, // Include both for backward compatibility
+ max_results: maxResults,
+ time_period: timePeriod,
+ iterations,
+ questions_per_iteration: questionsPerIteration
+ };
- if (response && response.status === 'success' && response.research_id) {
- // Store research settings
- window.localStorage.setItem('notificationsEnabled', enableNotifications);
+ console.log('Sending research request with payload:', JSON.stringify(payload));
+
+ // Start research process using fetch API
+ window.fetch('/research/api/start_research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(payload)
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(`Server returned ${response.status}: ${response.statusText}`);
+ }
+ return response.json();
+ })
+ .then(data => {
+ if (data && data.status === 'success' && data.research_id) {
+ // Store research settings
+ window.localStorage.setItem('notificationsEnabled', enableNotifications);
+ window.localStorage.setItem('lastUsedModel', model);
+ window.localStorage.setItem('lastUsedSearchEngine', searchEngine);
+
+ // Navigate to progress page
+ navigateToResearchProgress(data.research_id, query, mode);
+ } else {
+ throw new Error('Invalid response from server');
+ }
+ })
+ .catch(error => {
+ console.error('Error starting research:', error);
- // Navigate to progress page
- navigateToResearchProgress(response.research_id, query, mode);
- } else {
- throw new Error('Invalid response from server');
- }
+ // Handle common errors
+ if (error.message.includes('409')) {
+ showFormError('Another research is already in progress. Please wait for it to complete.');
+ } else {
+ showFormError(`Error starting research: ${error.message}`);
+ }
+
+ // Re-enable the form
+ setFormSubmitting(false);
+ });
} catch (error) {
- console.error('Error starting research:', error);
-
- // Handle common errors
- if (error.message.includes('409')) {
- showFormError('Another research is already in progress. Please wait for it to complete.');
- } else {
- showFormError(`Error starting research: ${error.message}`);
- }
-
- // Re-enable the form
+ console.error('Error in form submission:', error);
+ showFormError(`Error: ${error.message}`);
setFormSubmitting(false);
}
}
@@ -184,7 +270,7 @@
if (!errorEl) {
// Create error element
errorEl = document.createElement('div');
- errorEl.className = 'form-error';
+ errorEl.className = 'form-error error-message';
form.insertBefore(errorEl, form.querySelector('.form-actions'));
}
@@ -232,6 +318,240 @@
window.location.href = `/research/progress/${researchId}`;
}
+ /**
+ * Load language model options from API
+ */
+ function loadModelOptions() {
+ if (!modelSelect) return;
+
+ // Set "Loading..." option temporarily
+ modelSelect.innerHTML = '<option value="">Loading models...</option>';
+
+ // Only populate the dropdown once with all options combined
+ // Fetch all data sources in parallel first
+ Promise.all([
+ // Get available models from API
+ fetch('/research/api/available-models')
+ .then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`)),
+
+ // Get current setting value
+ fetch('/research/api/?type=llm')
+ .then(response => response.ok ? response.json() : Promise.reject(`API returned ${response.status}`))
+ .catch(() => ({ settings: {} })) // Fallback if API fails
+ ])
+ .then(([modelsData, settingsData]) => {
+ let modelOptions = [];
+ let selectedValue = null;
+
+ // 1. Add Ollama models if available
+ if (modelsData.providers && modelsData.providers.ollama_models && modelsData.providers.ollama_models.length > 0) {
+ console.log('Found Ollama models:', modelsData.providers.ollama_models);
+ // Add all Ollama models from the API
+ modelOptions = [...modelOptions, ...modelsData.providers.ollama_models];
+ } else if (modelsData.ollama_models && modelsData.ollama_models.length > 0) {
+ // Backward compatibility
+ console.log('Found Ollama models (legacy format):', modelsData.ollama_models);
+ modelOptions = [...modelOptions, ...modelsData.ollama_models];
+ } else {
+ // If we don't have Ollama models from API, add common Ollama models as fallback
+ modelOptions = [
+ ...modelOptions,
+ { value: 'gemma3:12b', label: 'Gemma 3 12B (Ollama)' },
+ { value: 'mistral', label: 'Mistral (Ollama)' },
+ { value: 'deepseek-r1', label: 'DeepSeek R1 (Ollama)' },
+ { value: 'deepseek-r1:14b', label: 'DeepSeek R1 14B (Ollama)' },
+ { value: 'deepseek-r1:32b', label: 'DeepSeek R1 32B (Ollama)' }
+ ];
+ }
+
+ // 2. Add standard model options (these always appear, even without Ollama)
+ modelOptions = [
+ ...modelOptions,
+ { 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)' }
+ ];
+
+ // 3. Get the currently selected model value from settings if available
+ const currentModelSetting = settingsData?.settings?.['llm.model'];
+ if (currentModelSetting) {
+ selectedValue = currentModelSetting;
+ }
+
+ // Make sure we don't have duplicates (by value)
+ const uniqueOptions = [];
+ const uniqueValues = new Set();
+
+ modelOptions.forEach(option => {
+ if (!uniqueValues.has(option.value)) {
+ uniqueValues.add(option.value);
+ uniqueOptions.push(option);
+ }
+ });
+
+ // Finally populate the dropdown once with all options
+ populateSelectWithOptions(modelSelect, uniqueOptions, selectedValue || 'mistral');
+ })
+ .catch(error => {
+ console.error('Error loading LLM models:', error);
+
+ // Fallback to default options if all API calls fail
+ const defaultOptions = [
+ { value: 'gemma3:12b', label: 'Gemma 3 12B (Ollama)' },
+ { value: 'mistral', label: 'Mistral (Ollama)' },
+ { value: 'deepseek-r1', label: 'DeepSeek R1 (Ollama)' },
+ { 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)' }
+ ];
+
+ populateSelectWithOptions(modelSelect, defaultOptions, 'mistral');
+ });
+ }
+
+ /**
+ * Load search engine options from API
+ */
+ function loadSearchEngineOptions() {
+ if (!searchEngineSelect) return;
+
+ // Set default options in case API call fails
+ const defaultOptions = [
+ { value: 'google_pse', label: 'Google Programmable Search Engine' },
+ { value: 'searxng', label: 'SearXNG (Self-hosted)' },
+ { value: 'serpapi', label: 'SerpAPI (Google)' },
+ { value: 'duckduckgo', label: 'DuckDuckGo' }
+ ];
+
+ // Start with default options
+ populateSelectWithOptions(searchEngineSelect, defaultOptions, 'google_pse');
+
+ // Try to get search engine options from API
+ fetch('/research/api/available-search-engines')
+ .then(response => {
+ if (!response.ok) throw new Error(`API returned ${response.status}`);
+ return response.json();
+ })
+ .then(data => {
+ if (data.engine_options && data.engine_options.length > 0) {
+ // Use engine options if available
+ populateSelectWithOptions(searchEngineSelect, data.engine_options, searchEngineSelect.value);
+ }
+
+ // Also get the current setting value
+ return fetch('/research/api/?type=search');
+ })
+ .then(response => {
+ if (!response.ok) throw new Error(`API returned ${response.status}`);
+ return response.json();
+ })
+ .then(data => {
+ // Find search engine setting
+ const searchEngineSetting = data?.settings?.['search.tool'];
+ if (searchEngineSetting) {
+ // Update selection if needed
+ const option = Array.from(searchEngineSelect.options).find(opt => opt.value === searchEngineSetting);
+ if (option) {
+ option.selected = true;
+ }
+ }
+ })
+ .catch(error => {
+ console.error('Error loading search settings:', error);
+ });
+ }
+
+ /**
+ * Load other settings from API
+ */
+ function loadSettings() {
+ // Set default values
+ if (maxResultsInput) maxResultsInput.value = 10;
+ if (timePeriodSelect) {
+ const allTimeOption = timePeriodSelect.querySelector('option[value="all"]');
+ if (allTimeOption) allTimeOption.selected = true;
+ }
+ if (iterationsInput) iterationsInput.value = 2;
+ if (questionsPerIterationInput) questionsPerIterationInput.value = 3;
+ if (notificationToggle) notificationToggle.checked = true;
+
+ // Try to load search settings
+ fetch('/research/api/?type=search')
+ .then(response => {
+ if (!response.ok) throw new Error(`API returned ${response.status}`);
+ return response.json();
+ })
+ .then(data => {
+ if (data?.settings) {
+ if (maxResultsInput && data.settings['search.max_results'] !== undefined) {
+ maxResultsInput.value = data.settings['search.max_results'];
+ }
+
+ if (timePeriodSelect && data.settings['search.time_period']) {
+ const timePeriod = data.settings['search.time_period'];
+ const option = timePeriodSelect.querySelector(`option[value="${timePeriod}"]`);
+ if (option) {
+ option.selected = true;
+ }
+ }
+ }
+ })
+ .catch(error => {
+ console.error('Error loading search settings:', error);
+ });
+
+ // Try to load app settings
+ fetch('/research/api/?type=app')
+ .then(response => {
+ if (!response.ok) throw new Error(`API returned ${response.status}`);
+ return response.json();
+ })
+ .then(data => {
+ if (data?.settings) {
+ if (iterationsInput && data.settings['app.research_iterations'] !== undefined) {
+ iterationsInput.value = data.settings['app.research_iterations'];
+ }
+
+ if (questionsPerIterationInput && data.settings['app.questions_per_iteration'] !== undefined) {
+ questionsPerIterationInput.value = data.settings['app.questions_per_iteration'];
+ }
+
+ if (notificationToggle && data.settings['app.enable_notifications'] !== undefined) {
+ notificationToggle.checked = data.settings['app.enable_notifications'];
+ }
+ }
+ })
+ .catch(error => {
+ console.error('Error loading app settings:', error);
+ });
+ }
+
+ /**
+ * Populate a select element with options
+ * @param {HTMLSelectElement} selectElement - The select element to populate
+ * @param {Array} options - Array of option objects with value and label properties
+ * @param {string} defaultValue - The default value to select
+ */
+ function populateSelectWithOptions(selectElement, options, defaultValue) {
+ // Clear existing options
+ selectElement.innerHTML = '';
+
+ // Add options
+ options.forEach(option => {
+ const optionEl = document.createElement('option');
+ optionEl.value = option.value;
+ optionEl.textContent = option.label;
+
+ // Select default or matching value
+ if (option.value === defaultValue) {
+ optionEl.selected = true;
+ }
+
+ selectElement.appendChild(optionEl);
+ });
+ }
+
// Initialize on DOM content loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeResearch);
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 1d45105dcf..5eea4f3e94 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -42,7 +42,7 @@
<i class="fas fa-chevron-down"></i>
</div>
- <div class="advanced-options-panel" style="display: none;">
+ <div class="advanced-options-panel">
<div class="form-row">
<!-- Model Selection -->
<div class="form-group half">
@@ -122,176 +122,6 @@
</div>
{% endblock %}
-{% block scripts %}
-<script>
- // Load settings when the page loads
- document.addEventListener('DOMContentLoaded', function() {
- // Toggle advanced options
- const advancedToggle = document.querySelector('.advanced-options-toggle');
- const advancedPanel = document.querySelector('.advanced-options-panel');
-
- if (advancedToggle && advancedPanel) {
- advancedToggle.addEventListener('click', function() {
- const isVisible = advancedPanel.style.display !== 'none';
- advancedPanel.style.display = isVisible ? 'none' : 'block';
-
- // Update icon
- const icon = advancedToggle.querySelector('i');
- if (icon) {
- icon.className = isVisible ? 'fas fa-chevron-down' : 'fas fa-chevron-up';
- }
- });
- }
-
- // Load model options
- loadModelOptions();
-
- // Load search engine options
- loadSearchEngineOptions();
-
- // Load other settings
- loadSettings();
- });
-
- function loadModelOptions() {
- const modelSelect = document.getElementById('model');
- if (!modelSelect) return;
-
- fetch('/research/api/settings/?type=llm')
- .then(response => response.json())
- .then(data => {
- // Find model setting
- const modelSetting = data.settings['llm.model'];
- if (modelSetting) {
- // Get model options
- fetch(`/research/api/settings/llm.model`)
- .then(response => response.json())
- .then(settingData => {
- const setting = settingData.setting;
- if (setting && setting.options) {
- // Clear existing options
- modelSelect.innerHTML = '';
-
- // Add options
- setting.options.forEach(option => {
- const optionEl = document.createElement('option');
- optionEl.value = option.value;
- optionEl.textContent = option.label;
-
- // Select current value
- if (option.value === setting.value) {
- optionEl.selected = true;
- }
-
- modelSelect.appendChild(optionEl);
- });
- }
- })
- .catch(error => {
- console.error('Error loading model options:', error);
- modelSelect.innerHTML = '<option value="">Error loading models</option>';
- });
- }
- })
- .catch(error => {
- console.error('Error loading LLM settings:', error);
- modelSelect.innerHTML = '<option value="">Error loading models</option>';
- });
- }
-
- function loadSearchEngineOptions() {
- const searchEngineSelect = document.getElementById('search_engine');
- if (!searchEngineSelect) return;
-
- fetch('/research/api/settings/?type=search')
- .then(response => response.json())
- .then(data => {
- // Find search engine setting
- const searchEngineSetting = data.settings['search.tool'];
- if (searchEngineSetting) {
- // Get search engine options
- fetch(`/research/api/settings/search.tool`)
- .then(response => response.json())
- .then(settingData => {
- const setting = settingData.setting;
- if (setting && setting.options) {
- // Clear existing options
- searchEngineSelect.innerHTML = '';
-
- // Add options
- setting.options.forEach(option => {
- const optionEl = document.createElement('option');
- optionEl.value = option.value;
- optionEl.textContent = option.label;
-
- // Select current value
- if (option.value === setting.value) {
- optionEl.selected = true;
- }
-
- searchEngineSelect.appendChild(optionEl);
- });
- }
- })
- .catch(error => {
- console.error('Error loading search engine options:', error);
- searchEngineSelect.innerHTML = '<option value="">Error loading search engines</option>';
- });
- }
- })
- .catch(error => {
- console.error('Error loading search settings:', error);
- searchEngineSelect.innerHTML = '<option value="">Error loading search engines</option>';
- });
- }
-
- function loadSettings() {
- // Get settings elements
- const maxResultsInput = document.getElementById('max_results');
- const timePeriodSelect = document.getElementById('time_period');
- const iterationsInput = document.getElementById('iterations');
- const questionsPerIterationInput = document.getElementById('questions_per_iteration');
- const notificationToggle = document.getElementById('notification-toggle');
-
- // Load search settings
- fetch('/research/api/settings/?type=search')
- .then(response => response.json())
- .then(data => {
- if (maxResultsInput && data.settings['search.max_results']) {
- maxResultsInput.value = data.settings['search.max_results'];
- }
-
- if (timePeriodSelect && data.settings['search.time_period']) {
- const timePeriod = data.settings['search.time_period'];
- const option = timePeriodSelect.querySelector(`option[value="${timePeriod}"]`);
- if (option) {
- option.selected = true;
- }
- }
- })
- .catch(error => {
- console.error('Error loading search settings:', error);
- });
-
- // Load app settings
- fetch('/research/api/settings/?type=app')
- .then(response => response.json())
- .then(data => {
- if (iterationsInput && data.settings['app.research_iterations']) {
- iterationsInput.value = data.settings['app.research_iterations'];
- }
-
- if (questionsPerIterationInput && data.settings['app.questions_per_iteration']) {
- questionsPerIterationInput.value = data.settings['app.questions_per_iteration'];
- }
-
- if (notificationToggle && data.settings['app.enable_notifications'] !== undefined) {
- notificationToggle.checked = data.settings['app.enable_notifications'];
- }
- })
- .catch(error => {
- console.error('Error loading app settings:', error);
- });
- }
-</script>
+{% block component_scripts %}
+<script src="{{ url_for('research.serve_static', path='js/components/research.js') }}"></script>
{% endblock %}
\ No newline at end of file
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
index 180e27f1c6..6f4d4a43ca 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py
@@ -493,11 +493,14 @@ https://searxng.github.io/searxng/admin/installation.html
)
return []
- logger.info(f"SearXNG run method called with query: {query}")
+ logger.info(f"SearXNG search engine running with query: '{query}'")
+ logger.info(f"SearXNG instance URL: {self.instance_url}")
try:
# Call the parent class's run method
- return super().run(query)
+ results = super().run(query)
+ logger.info(f"SearXNG search completed with {len(results)} results")
+ return results
except Exception as e:
logger.error(f"Error in SearXNG run method: {str(e)}")
# Return empty results on error
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 ca9916bc68..47e1ed2c7a 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
+from typing import Any, Dict, Optional, Union, List
from .search_engine_base import BaseSearchEngine
from .search_engines_config import DEFAULT_SEARCH_ENGINE, SEARCH_ENGINES
@@ -231,16 +231,43 @@ def _create_full_search_wrapper(
return base_engine
-def get_available_engines(include_api_key_services: bool = True):
- """Get a list of available engine names"""
- if include_api_key_services:
+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('_'):
+ continue
+
+ # Skip engines that require API keys if requested
+ 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()
+
+ 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}")
+ # Fall back to list of engines directly from keys
return list(SEARCH_ENGINES.keys())
- else:
- return [
- name
- for name, config in SEARCH_ENGINES.items()
- if not config.get("requires_api_key", False)
- ]
def get_search(