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.

4.9 KB
Raw Blame
# local_deep_research/config.py
from loguru import logger

from ..web_search_engines.search_engine_factory import (
    get_search as factory_get_search,
)
from .constants import DEFAULT_MAX_FILTERED_RESULTS
from .llm_config import get_llm
from .thread_settings import get_setting_from_snapshot
from ..security.log_sanitizer import redact_and_bound_for_log

# Whether to check the quality search results using the LLM.
QUALITY_CHECK_DDG_URLS = True


# get_setting_from_snapshot is now imported from thread_settings


# Expose get_search function
def get_search(
    search_tool=None,
    llm_instance=None,
    username=None,
    settings_snapshot=None,
    programmatic_mode=False,
    raise_on_error=False,
):
    """
    Helper function to get search engine

    Args:
        search_tool: Override the search tool setting (e.g. searxng, wikipedia)
        llm_instance: Override the LLM instance
        username: Optional username for thread context (e.g., background research threads)
        settings_snapshot: Settings snapshot from thread context
        programmatic_mode: If True, disables database operations and metrics tracking
        raise_on_error: Preserve initialization failures for agent availability.
    """

    # Use specified tool or default from settings
    tool = search_tool or get_setting_from_snapshot(
        "search.tool",
        "searxng",
        username=username,
        settings_snapshot=settings_snapshot,
    )

    # Debug: Check if we got a dict instead of a string
    if isinstance(tool, dict):
        logger.warning(
            f"Got dict for search.tool, extracting value: {tool.get('value')}"
        )
        if "value" in tool:
            tool = tool["value"]

    # (#6938: the tool name can be a request-supplied string.)
    logger.info(
        "Creating search engine with tool: {} (type: {})",
        redact_and_bound_for_log(str(tool), 200),
        type(tool),
    )

    # Get LLM instance (use provided or get fresh one). Pass username
    # explicitly: this runs BEFORE ``_username`` is injected into the
    # snapshot below, so without it a per-user registered LLM (and per-user
    # egress classification) would be invisible to this fresh get_llm.
    llm = llm_instance or get_llm(
        settings_snapshot=settings_snapshot, username=username
    )

    # Ensure username is in settings_snapshot for search engines that need it (e.g., library)
    if username and settings_snapshot is not None:
        # Create a copy to avoid modifying the original
        settings_snapshot = {**settings_snapshot, "_username": username}
    elif username:
        # Create new snapshot with username
        settings_snapshot = {"_username": username}

    # Get search parameters
    params = {
        "search_tool": tool,
        "llm_instance": llm,
        "max_results": get_setting_from_snapshot(
            "search.max_results",
            10,
            username=username,
            settings_snapshot=settings_snapshot,
        ),
        "region": get_setting_from_snapshot(
            "search.region",
            "wt-wt",
            username=username,
            settings_snapshot=settings_snapshot,
        ),
        # time_period is deliberately NOT forwarded here: passing it as an
        # explicit kwarg would override per-engine
        # default_params.time_period settings. create_search_engine()
        # resolves per-engine > global search.time_period from the
        # settings_snapshot passed below.
        "safe_search": get_setting_from_snapshot(
            "search.safe_search",
            True,
            username=username,
            settings_snapshot=settings_snapshot,
        ),
        "search_snippets_only": get_setting_from_snapshot(
            "search.snippets_only",
            True,
            username=username,
            settings_snapshot=settings_snapshot,
        ),
        "search_language": get_setting_from_snapshot(
            "search.search_language",
            "English",
            username=username,
            settings_snapshot=settings_snapshot,
        ),
        "max_filtered_results": get_setting_from_snapshot(
            "search.max_filtered_results",
            DEFAULT_MAX_FILTERED_RESULTS,
            username=username,
            settings_snapshot=settings_snapshot,
        ),
    }

    # Log NULL parameters for debugging
    logger.info(
        f"Search config: tool={tool}, max_results={params['max_results']}"
    )
    logger.info(f"Full params dict: {params}")

    # Create search engine
    if raise_on_error:
        params["raise_on_error"] = True
    search_engine = factory_get_search(
        settings_snapshot=settings_snapshot,
        programmatic_mode=programmatic_mode,
        **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