~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
minor
LearningCircuit77d8d3ec6fe7
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 668284c670..be7a2c5773 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -12,7 +12,7 @@ import tomlfrom .. import get_report_generator # Use the lazy import functionfrom ..config.llm_config import get_llmfrom ..config.search_config import get_search-from ..search_system import AdvancedSearchSystem+from ..search_system.search_system import AdvancedSearchSystemfrom ..utilties.search_utilities import remove_think_tagslogger = logging.getLogger(__name__)diff --git a/src/local_deep_research/search_system/__init__.py b/src/local_deep_research/search_system/__init__.pyindex 8428fb7824..2614545b6d 100644--- a/src/local_deep_research/search_system/__init__.py+++ b/src/local_deep_research/search_system/__init__.py@@ -1 +1,4 @@# Search System Package+from .search_system import AdvancedSearchSystem++__all__ = ["AdvancedSearchSystem"]diff --git a/src/local_deep_research/search_system/knowledge/base_knowledge.py b/src/local_deep_research/search_system/knowledge/base_knowledge.pyindex 32a9b048e6..0630ffb4ea 100644--- a/src/local_deep_research/search_system/knowledge/base_knowledge.py+++ b/src/local_deep_research/search_system/knowledge/base_knowledge.py@@ -1,15 +1,98 @@-from abc import ABC, abstractmethod+"""+Base class for all knowledge managers.+Defines the common interface and shared functionality for different knowledge management approaches.+"""+import logging+from abc import ABC, abstractmethod+from typing import Listlogger = logging.getLogger(__name__)+class BaseKnowledgeManager(ABC):- """Base class for knowledge management services."""-+ """Abstract base class for all knowledge managers."""+def __init__(self, model):+ """+ Initialize the knowledge manager.++ Args:+ model: The language model to use for knowledge operations+ """self.model = model-+@abstractmethod- def compress_knowledge(self, current_knowledge: str, query: str, section_links: list, **kwargs) -> str:- """Compress and summarize accumulated knowledge."""+ def compress_knowledge(self, knowledge: str, query: str, links: List[str]) -> str:+ """+ Compress and summarize accumulated knowledge.++ Args:+ knowledge: The accumulated knowledge to compress+ query: The original research query+ links: List of source links++ Returns:+ str: Compressed knowledge+ """pass++ @abstractmethod+ def format_citations(self, links: List[str]) -> str:+ """+ Format source links into citations.++ Args:+ links: List of source links++ Returns:+ str: Formatted citations+ """+ pass++ def _validate_knowledge(self, knowledge: str) -> bool:+ """+ Validate the knowledge input.++ Args:+ knowledge: The knowledge to validate++ Returns:+ bool: True if knowledge is valid, False otherwise+ """+ if not knowledge or not isinstance(knowledge, str):+ logger.error("Invalid knowledge provided")+ return False+ return True++ def _validate_links(self, links: List[str]) -> bool:+ """+ Validate the source links.++ Args:+ links: List of source links to validate++ Returns:+ bool: True if links are valid, False otherwise+ """+ if not isinstance(links, list):+ logger.error("Invalid links format")+ return False+ if not all(isinstance(link, str) for link in links):+ logger.error("Invalid link type in links list")+ return False+ return True++ def _extract_key_points(self, knowledge: str) -> List[str]:+ """+ Extract key points from knowledge.++ Args:+ knowledge: The knowledge to analyze++ Returns:+ List[str]: List of key points+ """+ # This is a placeholder implementation+ # Specific implementations should override this method+ return knowledge.split("\n")diff --git a/src/local_deep_research/search_system/questions/base_question.py b/src/local_deep_research/search_system/questions/base_question.pyindex 46007c1e62..5c80e6adb6 100644--- a/src/local_deep_research/search_system/questions/base_question.py+++ b/src/local_deep_research/search_system/questions/base_question.py@@ -1,16 +1,94 @@-from abc import ABC, abstractmethod-from typing import List, Dict+"""+Base class for all question generators.+Defines the common interface and shared functionality for different question generation approaches.+"""+import logging+from abc import ABC, abstractmethod+from typing import Dict, Listlogger = logging.getLogger(__name__)+class BaseQuestionGenerator(ABC):- """Base class for question generation services."""-+ """Abstract base class for all question generators."""+def __init__(self, model):+ """+ Initialize the question generator.++ Args:+ model: The language model to use for question generation+ """self.model = model-+@abstractmethod- def generate_questions(self, current_knowledge: str, query: str, **kwargs) -> List[str]:- """Generate questions based on current knowledge and query."""+ def generate_questions(+ self,+ current_knowledge: str,+ query: str,+ questions_per_iteration: int,+ questions_by_iteration: Dict[int, List[str]],+ ) -> List[str]:+ """+ Generate questions based on the current state of research.++ Args:+ current_knowledge: The accumulated knowledge so far+ query: The original research query+ questions_per_iteration: Number of questions to generate per iteration+ questions_by_iteration: Questions generated in previous iterations++ Returns:+ List[str]: Generated questions+ """pass++ def _validate_inputs(+ self,+ current_knowledge: str,+ query: str,+ questions_per_iteration: int,+ questions_by_iteration: Dict[int, List[str]],+ ) -> bool:+ """+ Validate the input parameters for question generation.++ Args:+ current_knowledge: The accumulated knowledge so far+ query: The original research query+ questions_per_iteration: Number of questions to generate per iteration+ questions_by_iteration: Questions generated in previous iterations++ Returns:+ bool: True if inputs are valid, False otherwise+ """+ if not query or not isinstance(query, str):+ logger.error("Invalid query provided")+ return False+ if questions_per_iteration < 1:+ logger.error("Invalid questions_per_iteration value")+ return False+ if not isinstance(questions_by_iteration, dict):+ logger.error("Invalid questions_by_iteration format")+ return False+ return True++ def _format_previous_questions(+ self, questions_by_iteration: Dict[int, List[str]]+ ) -> str:+ """+ Format previous questions for context.++ Args:+ questions_by_iteration: Questions generated in previous iterations++ Returns:+ str: Formatted string of previous questions+ """+ formatted = []+ for iteration, questions in questions_by_iteration.items():+ formatted.append(f"Iteration {iteration}:")+ for q in questions:+ formatted.append(f"- {q}")+ return "\n".join(formatted)diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system/search_system.pysimilarity index 86%rename from src/local_deep_research/search_system.pyrename to src/local_deep_research/search_system/search_system.pyindex 5e70a5deee..acc6742315 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system/search_system.py@@ -1,11 +1,11 @@-# src/local_deep_research/search_system.py+# src/local_deep_research/search_system/search_system.pyimport loggingfrom typing import Callable, Dict-from .config.config_files import settings-from .config.llm_config import get_llm-from .config.search_config import get_search-from .search_system.strategies.standard_strategy import StandardSearchStrategy+from ..config.config_files import settings+from ..config.llm_config import get_llm+from ..config.search_config import get_search+from .strategies.standard_strategy import StandardSearchStrategylogger = logging.getLogger(__name__)diff --git a/src/local_deep_research/search_system/strategies/base_strategy.py b/src/local_deep_research/search_system/strategies/base_strategy.pyindex e2daff88c9..ac1af0f8c5 100644--- a/src/local_deep_research/search_system/strategies/base_strategy.py+++ b/src/local_deep_research/search_system/strategies/base_strategy.py@@ -1,10 +1,118 @@-# Base Strategy Interface+"""+Base class for all search strategies.+Defines the common interface and shared functionality for different search approaches.+"""+import loggingfrom abc import ABC, abstractmethod-from typing import Dict+from typing import Callable, Dict, List, Optional++logger = logging.getLogger(__name__)+class BaseSearchStrategy(ABC):+ """Abstract base class for all search strategies."""++ def __init__(self):+ """Initialize the base strategy with common attributes."""+ self.progress_callback = None+ self.questions_by_iteration = {}+ self.all_links_of_system = []++ def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:+ """Set a callback function to receive progress updates."""+ self.progress_callback = callback++ def _update_progress(+ self,+ message: str,+ progress_percent: Optional[int] = None,+ metadata: Optional[dict] = None,+ ) -> None:+ """Send a progress update via the callback if available."""+ if self.progress_callback:+ self.progress_callback(message, progress_percent, metadata or {})+@abstractmethoddef analyze_topic(self, query: str) -> Dict:- """Analyze a topic and return findings."""+ """+ Analyze a topic using the strategy's specific approach.++ Args:+ query: The research query to analyze++ Returns:+ Dict containing:+ - findings: List of research findings+ - iterations: Number of iterations completed+ - questions: Questions generated by iteration+ - formatted_findings: Formatted output+ - current_knowledge: Accumulated knowledge+ - error: Optional error message+ """pass++ def _validate_search_engine(self) -> bool:+ """+ Validate that the search engine is available and configured.++ Returns:+ bool: True if search engine is available, False otherwise+ """+ if not hasattr(self, "search") or self.search is None:+ error_msg = (+ "Error: No search engine available. Please check your configuration."+ )+ self._update_progress(+ error_msg,+ 100,+ {+ "phase": "error",+ "error": "No search engine available",+ "status": "failed",+ },+ )+ return False+ return True++ def _handle_search_error(+ self, error: Exception, question: str, progress_base: int+ ) -> List:+ """+ Handle errors during search execution.++ Args:+ error: The exception that occurred+ question: The question being searched+ progress_base: The current progress percentage++ Returns:+ List: Empty list to continue processing+ """+ error_msg = f"Error during search: {str(error)}"+ logger.info(f"SEARCH ERROR: {error_msg}")+ self._update_progress(+ error_msg,+ progress_base + 2,+ {"phase": "search_error", "error": str(error)},+ )+ return []++ def _handle_analysis_error(+ self, error: Exception, question: str, progress_base: int+ ) -> None:+ """+ Handle errors during result analysis.++ Args:+ error: The exception that occurred+ question: The question being analyzed+ progress_base: The current progress percentage+ """+ error_msg = f"Error analyzing results: {str(error)}"+ logger.info(f"ANALYSIS ERROR: {error_msg}")+ self._update_progress(+ error_msg,+ progress_base + 10,+ {"phase": "analysis_error", "error": str(error)},+ )diff --git a/src/local_deep_research/search_system/strategies/standard_strategy.py b/src/local_deep_research/search_system/strategies/standard_strategy.pyindex 9aaf4f1dc4..63189d7d78 100644--- a/src/local_deep_research/search_system/strategies/standard_strategy.py+++ b/src/local_deep_research/search_system/strategies/standard_strategy.py@@ -1,8 +1,9 @@import loggingfrom typing import Callable, Dict+from ... import get_llm, get_searchfrom ...citation_handler import CitationHandler-from ...config import get_llm, get_search, settings+from ...config.config_files import settingsfrom ...utilties.enums import KnowledgeAccumulationApproachfrom ...utilties.search_utilities import extract_links_from_search_resultsfrom ..knowledge.standard_knowledge import StandardKnowledgeManagerdiff --git a/src/local_deep_research/search_system/tools/base_tool.py b/src/local_deep_research/search_system/tools/base_tool.pynew file mode 100644index 0000000000..3d868157ae--- /dev/null+++ b/src/local_deep_research/search_system/tools/base_tool.py@@ -0,0 +1,100 @@+"""+Base class for all agent-compatible tools.+Defines the common interface and shared functionality for different tools.+"""++import logging+from abc import ABC, abstractmethod+from typing import Any, Dict++logger = logging.getLogger(__name__)+++class BaseTool(ABC):+ """Abstract base class for all agent-compatible tools."""++ def __init__(self, name: str, description: str):+ """+ Initialize the tool.++ Args:+ name: The name of the tool+ description: A description of what the tool does+ """+ self.name = name+ self.description = description+ self.parameters: Dict[str, Dict[str, Any]] = {}++ @abstractmethod+ def execute(self, **kwargs) -> Any:+ """+ Execute the tool with the given parameters.++ Args:+ **kwargs: Tool-specific parameters++ Returns:+ Any: The result of the tool execution+ """+ pass++ def get_schema(self) -> Dict[str, Any]:+ """+ Get the JSON schema for the tool's parameters.++ Returns:+ Dict[str, Any]: The JSON schema+ """+ return {+ "name": self.name,+ "description": self.description,+ "parameters": self.parameters,+ }++ def validate_parameters(self, **kwargs) -> bool:+ """+ Validate the provided parameters against the tool's schema.++ Args:+ **kwargs: Parameters to validate++ Returns:+ bool: True if parameters are valid, False otherwise+ """+ for param_name, param_schema in self.parameters.items():+ if param_name not in kwargs:+ if param_schema.get("required", False):+ logger.error(f"Missing required parameter: {param_name}")+ return False+ continue++ param_value = kwargs[param_name]+ param_type = param_schema.get("type")++ if param_type and not isinstance(param_value, eval(param_type)):+ logger.error(f"Invalid type for parameter {param_name}")+ return False++ if "enum" in param_schema and param_value not in param_schema["enum"]:+ logger.error(f"Invalid value for parameter {param_name}")+ return False++ return True++ def _log_execution(self, **kwargs) -> None:+ """+ Log tool execution details.++ Args:+ **kwargs: Parameters used in execution+ """+ logger.info(f"Executing tool {self.name} with parameters: {kwargs}")++ def _log_result(self, result: Any) -> None:+ """+ Log tool execution result.++ Args:+ result: The result of the tool execution+ """+ logger.info(f"Tool {self.name} execution completed with result: {result}")