Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

refactor: Address code review feedback from djpetti

LearningCircuit33bfc947aba8
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
index 0e00f58a65..b9eb04f44a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
@@ -422,7 +422,7 @@ You have complete freedom to:
- Seek recent updates ("What's the latest status as of 2024/2025?")
- Explore contradictions ("Source says X but that conflicts with Y")
-Respond in JSON format:
+Respond with ONLY valid JSON, no markdown formatting, no additional text before or after:
{{
"action": "REFINE" or "COMPLETE",
"confidence": 0.0 to 1.0 (your honest assessment of completeness/accuracy),
@@ -444,20 +444,13 @@ Your refinement query can be as long and specific as needed to get good results.
content = str(response)
# Parse JSON from response
- # Handle case where LLM might include markdown code blocks
+ # If LLM includes markdown code blocks, extract the JSON
if "```json" in content:
json_str = content.split("```json")[1].split("```")[0].strip()
elif "```" in content:
json_str = content.split("```")[1].split("```")[0].strip()
else:
- # Try to find JSON object in the response
- import re
-
- json_match = re.search(r"\{.*\}", content, re.DOTALL)
- if json_match:
- json_str = json_match.group(0)
- else:
- json_str = content
+ json_str = content
evaluation = json.loads(json_str)
diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
index 61b259f178..c150726f41 100644
--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py
@@ -101,8 +101,6 @@ class ParallelSearchEngine(BaseSearchEngine):
def _get_available_engines(self) -> List[str]:
"""Get list of available engines based on is_public flag and API key availability"""
- import importlib
-
available = []
config_data = self._get_search_config()
@@ -112,58 +110,31 @@ class ParallelSearchEngine(BaseSearchEngine):
continue
# Try to get the engine class to check is_public flag
- try:
- # Load the engine class directly
- module_path = config_.get("module_path")
- class_name = config_.get("class_name")
+ success, engine_class, error_msg = self._load_engine_class(
+ name, config_
+ )
- if not module_path or not class_name:
+ if not success:
+ logger.debug(error_msg)
+ continue
+
+ # Check if engine is public or if local engines are allowed
+ if hasattr(engine_class, "is_public"):
+ if not engine_class.is_public and not self.allow_local_engines:
+ logger.debug(f"Skipping local/private engine: {name}")
+ continue
+ elif not engine_class.is_public and self.allow_local_engines:
+ logger.warning(
+ f"Including local/private engine {name} - data may be exposed"
+ )
+ else:
+ # No is_public flag - assume it's private/local for safety
+ if not self.allow_local_engines:
logger.debug(
- f"Missing module_path or class_name for {name}"
+ f"Skipping engine {name} - no is_public flag and local engines not allowed"
)
continue
- # Import the module
- package = None
- if module_path.startswith("."):
- # This is a relative import
- package = "local_deep_research.web_search_engines"
- module = importlib.import_module(module_path, package=package)
- engine_class = getattr(module, class_name)
-
- # Check if engine is public or if local engines are allowed
- if hasattr(engine_class, "is_public"):
- if (
- not engine_class.is_public
- and not self.allow_local_engines
- ):
- logger.debug(f"Skipping local/private engine: {name}")
- continue
- elif (
- not engine_class.is_public and self.allow_local_engines
- ):
- logger.warning(
- f"Including local/private engine {name} - data may be exposed"
- )
- else:
- # No is_public flag - use old name-based detection as fallback
- if not self.allow_local_engines:
- if name.startswith("local") or name in [
- "paperless",
- "personal_notes",
- "project_docs",
- "research_papers",
- "elasticsearch",
- ]:
- logger.debug(
- f"Skipping suspected local engine (no is_public flag): {name}"
- )
- continue
- except Exception as e:
- logger.debug(f"Could not load engine class for {name}: {e}")
- # Skip engines we can't load
- continue
-
# Skip engines that require API keys if we don't want to use them
if (
config_.get("requires_api_key", False)
@@ -174,24 +145,9 @@ class ParallelSearchEngine(BaseSearchEngine):
)
continue
- # Skip engines that require API keys if the key is not available or empty
- if config_.get("requires_api_key", False):
- api_key = config_.get("api_key", "").strip()
- # Check for common placeholder values
- if (
- not api_key
- or api_key
- in ["", "None", "PLACEHOLDER", "YOUR_API_KEY_HERE"]
- or api_key.endswith(
- "_API_KEY"
- ) # Default placeholders like BRAVE_API_KEY
- or api_key.startswith("YOUR_")
- or api_key == "null"
- ):
- logger.debug(
- f"Skipping {name} - requires API key but none configured (found: {api_key[:20] if api_key else 'empty'})"
- )
- continue
+ # Check API key availability
+ if not self._check_api_key_availability(name, config_):
+ continue
available.append(name)
@@ -199,8 +155,6 @@ class ParallelSearchEngine(BaseSearchEngine):
def _get_available_generic_engines(self) -> List[str]:
"""Get list of available generic search engines that pass API key checks"""
- import importlib
-
generic_engines = []
config_data = self._get_search_config()
@@ -209,26 +163,21 @@ class ParallelSearchEngine(BaseSearchEngine):
if name not in self.available_engines:
continue
- try:
- # Load the engine class to check is_generic flag
- module_path = config_.get("module_path")
- class_name = config_.get("class_name")
-
- if not module_path or not class_name:
- continue
+ # Load the engine class to check is_generic flag
+ success, engine_class, error_msg = self._load_engine_class(
+ name, config_
+ )
- package = None
- if module_path.startswith("."):
- package = "local_deep_research.web_search_engines"
- module = importlib.import_module(module_path, package=package)
- engine_class = getattr(module, class_name)
+ if not success:
+ logger.debug(
+ f"Could not check if {name} is generic: {error_msg}"
+ )
+ continue
- # Check if engine is generic
- if getattr(engine_class, "is_generic", False):
- generic_engines.append(name)
- logger.debug(f"Found generic engine: {name}")
- except Exception as e:
- logger.debug(f"Could not check if {name} is generic: {e}")
+ # Check if engine is generic
+ if getattr(engine_class, "is_generic", False):
+ generic_engines.append(name)
+ logger.debug(f"Found generic engine: {name}")
return generic_engines
@@ -530,7 +479,7 @@ Select up to {self.max_engines_to_select} engines that would best answer this qu
},
)
except Exception:
- pass
+ logger.debug("Socket emit error (non-critical)")
else:
# Emit failure event
try:
@@ -545,7 +494,7 @@ Select up to {self.max_engines_to_select} engines that would best answer this qu
},
)
except Exception:
- pass
+ logger.debug("Socket emit error (non-critical)")
except Exception as e:
logger.exception(f"Failed to get result from {engine_name}")
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 660059eb82..821a135f20 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -42,6 +42,90 @@ class BaseSearchEngine(ABC):
# Should be overridden by subclasses - defaults to False for safety
is_public = False
+ # Class attribute to indicate if this is a generic search engine (vs specialized)
+ # Generic engines are general web search (Google, Bing, etc) vs specialized (arXiv, PubMed)
+ is_generic = False
+
+ # Class attribute to indicate if this is a scientific/academic search engine
+ # Scientific engines include arXiv, PubMed, Semantic Scholar, etc.
+ is_scientific = False
+
+ @classmethod
+ def _load_engine_class(cls, name: str, config: Dict[str, Any]):
+ """
+ Helper method to load an engine class dynamically.
+
+ Args:
+ name: Engine name
+ config: Engine configuration dict with module_path and class_name
+
+ Returns:
+ Tuple of (success: bool, engine_class or None, error_msg or None)
+ """
+ import importlib
+
+ try:
+ module_path = config.get("module_path")
+ class_name = config.get("class_name")
+
+ if not module_path or not class_name:
+ return (
+ False,
+ None,
+ f"Missing module_path or class_name for {name}",
+ )
+
+ # Import the module
+ package = None
+ if module_path.startswith("."):
+ # This is a relative import
+ package = "local_deep_research.web_search_engines"
+ module = importlib.import_module(module_path, package=package)
+ engine_class = getattr(module, class_name)
+
+ return True, engine_class, None
+
+ except Exception as e:
+ return False, None, f"Could not load engine class for {name}: {e}"
+
+ @classmethod
+ def _check_api_key_availability(
+ cls, name: str, config: Dict[str, Any]
+ ) -> bool:
+ """
+ Helper method to check if an engine's API key is available and valid.
+
+ Args:
+ name: Engine name
+ config: Engine configuration dict
+
+ Returns:
+ True if API key is not required or is available and valid
+ """
+ from loguru import logger
+
+ if not config.get("requires_api_key", False):
+ return True
+
+ api_key = config.get("api_key", "").strip()
+
+ # Check for common placeholder values
+ if (
+ not api_key
+ or api_key in ["", "None", "PLACEHOLDER", "YOUR_API_KEY_HERE"]
+ or api_key.endswith(
+ "_API_KEY"
+ ) # Default placeholders like BRAVE_API_KEY
+ or api_key.startswith("YOUR_")
+ or api_key == "null"
+ ):
+ logger.debug(
+ f"Skipping {name} - requires API key but none configured"
+ )
+ return False
+
+ return True
+
def __init__(
self,
llm: Optional[BaseLLM] = None,