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: add shared helper methods to BaseSearchEngine (#2272)

LearningCircuit4b5e3f8a0350
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 8d073b6f1b..fb52bffff7 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -111,6 +111,7 @@ paths = [
# Web search engines use api_key variable names (not actual secrets)
'''src/local_deep_research/web_search_engines/engines/.*\.py$''',
'''src/local_deep_research/web_search_engines/search_engine_factory\.py$''',
+ '''src/local_deep_research/web_search_engines/search_engine_base\.py$''',
# HTML templates use csrfToken variable names (not actual secrets)
'''src/local_deep_research/web/templates/.*\.html$''',
# Notification flow docs contain example code with parameter names
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
index 2f16995ba3..76d6fa64ae 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_brave.py
@@ -4,7 +4,6 @@ from langchain_community.tools import BraveSearch
from langchain_core.language_models import BaseLLM
from loguru import logger
-from ...config import search_config
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -72,20 +71,13 @@ class BraveSearchEngine(BaseSearchEngine):
"russian": "ru",
}
- # Get API key - check params, env vars, or database
- from ...config.search_config import get_setting_from_snapshot
-
- brave_api_key = api_key
- if not brave_api_key:
- brave_api_key = get_setting_from_snapshot(
- "search.engine.web.brave.api_key",
- settings_snapshot=settings_snapshot,
- )
-
- if not brave_api_key:
- raise ValueError(
- "Brave API key not found. Please provide api_key parameter, set the LDR_SEARCH_ENGINE_WEB_BRAVE_API_KEY environment variable, or set it in the UI settings."
- )
+ # Get API key - check params, settings, or env vars
+ brave_api_key = self._resolve_api_key(
+ api_key,
+ "search.engine.web.brave.api_key",
+ engine_name="Brave Search",
+ settings_snapshot=settings_snapshot,
+ )
# Get language code
language_code = language_code_mapping.get(search_language.lower(), "en")
@@ -181,94 +173,13 @@ class BraveSearchEngine(BaseSearchEngine):
return previews
+ except RateLimitError:
+ raise
except Exception as e:
- error_msg = str(e)
logger.exception("Error getting Brave Search results")
-
- # Check for rate limit patterns
- if (
- "429" in error_msg
- or "too many requests" in error_msg.lower()
- or "rate limit" in error_msg.lower()
- or "quota" in error_msg.lower()
- ):
- raise RateLimitError(
- f"Brave Search rate limit hit: {error_msg}"
- )
-
+ self._raise_if_rate_limit(e)
return []
- def _get_full_content(
- self, relevant_items: List[Dict[str, Any]]
- ) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant search results.
- If include_full_content is True and FullSearchResults is available,
- retrieves full webpage content for the results.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content if requested
- """
- # Check if we should get full content
- if (
- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
- and search_config.SEARCH_SNIPPETS_ONLY
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full Brave information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"]
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item
-
- results.append(result)
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, "full_search"):
- logger.info("Retrieving full webpage content")
-
- try:
- # Use FullSearchResults to get full content
- results_with_content = self.full_search._get_full_content(
- relevant_items
- )
-
- return results_with_content
-
- except Exception:
- logger.exception("Error retrieving full content")
- # Fall back to returning the items without full content
-
- # Return items with their full Brave information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item.copy()
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
- return results
-
def run(
self, query: str, research_context: Dict[str, Any] | None = None
) -> List[Dict[str, Any]]:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
index ba4351369f..79ec7aae17 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_guardian.py
@@ -4,10 +4,9 @@ from typing import Any, Dict, List, Optional, Tuple
from langchain_core.language_models import BaseLLM
from loguru import logger
-from ...config import search_config
-from ...config.search_config import get_setting_from_snapshot
from ...utilities.search_utilities import remove_think_tags
from ...security.safe_requests import safe_get
+from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -54,22 +53,17 @@ class GuardianSearchEngine(BaseSearchEngine):
max_results=max_results,
settings_snapshot=settings_snapshot,
)
- # Get API key - check params or database
- guardian_api_key = api_key
- if not guardian_api_key:
- guardian_api_key = get_setting_from_snapshot(
- "search.engine.web.guardian.api_key",
- settings_snapshot=settings_snapshot,
- )
- self.api_key = guardian_api_key
+
+ # Get API key - check params, settings, or env vars
+ self.api_key = self._resolve_api_key(
+ api_key,
+ "search.engine.web.guardian.api_key",
+ engine_name="Guardian",
+ settings_snapshot=settings_snapshot,
+ )
self.optimize_queries = optimize_queries
self.adaptive_search = adaptive_search
- if not self.api_key:
- raise ValueError(
- "Guardian API key not found. Please provide api_key parameter, set the LDR_SEARCH_ENGINE_WEB_GUARDIAN_API_KEY environment variable, or set it in the UI settings."
- )
-
# Set date ranges if not provided
if not from_date:
# Default to one month ago
@@ -416,8 +410,11 @@ ONE WORD ONLY:"""
return formatted_articles
- except Exception:
+ except RateLimitError:
+ raise
+ except Exception as e:
logger.exception("Error getting data from The Guardian API")
+ self._raise_if_rate_limit(e)
return []
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
@@ -491,13 +488,6 @@ ONE WORD ONLY:"""
f"Adding full content to {len(relevant_items)} relevant Guardian articles"
)
- # Check if we should add full content
- if (
- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
- and search_config.SEARCH_SNIPPETS_ONLY
- ):
- return relevant_items
-
# Get full articles for relevant items
results = []
for item in relevant_items:
@@ -603,6 +593,8 @@ ONE WORD ONLY:"""
return results
+ except RateLimitError:
+ raise
except Exception:
logger.exception("Error in Guardian search")
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py b/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
index 21edb5f4cf..263aa733d4 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
@@ -64,21 +64,13 @@ class ScaleSerpSearchEngine(BaseSearchEngine):
self.safe_search = safe_search
self.enable_cache = enable_cache # ScaleSerp's unique caching feature
- # Get API key - check params, env vars, or database
- from ...config.search_config import get_setting_from_snapshot
-
- scaleserp_api_key = api_key
- if not scaleserp_api_key:
- scaleserp_api_key = get_setting_from_snapshot(
- "search.engine.web.scaleserp.api_key",
- settings_snapshot=settings_snapshot,
- )
-
- if not scaleserp_api_key:
- raise ValueError(
- "ScaleSerp API key not found. Please provide api_key parameter or set it in the UI settings. "
- "Get your API key at https://scaleserp.com"
- )
+ # Get API key - check params, settings, or env vars
+ scaleserp_api_key = self._resolve_api_key(
+ api_key,
+ "search.engine.web.scaleserp.api_key",
+ engine_name="ScaleSerp",
+ settings_snapshot=settings_snapshot,
+ )
self.api_key = scaleserp_api_key
self.base_url = "https://api.scaleserp.com/search"
@@ -160,10 +152,7 @@ class ScaleSerpSearchEngine(BaseSearchEngine):
response = safe_get(self.base_url, params=params, timeout=30)
# Check for rate limits
- if response.status_code == 429:
- raise RateLimitError(
- f"ScaleSerp rate limit hit: {response.status_code} - {response.text}"
- )
+ self._raise_if_rate_limit(response.status_code)
response.raise_for_status()
@@ -248,23 +237,10 @@ class ScaleSerpSearchEngine(BaseSearchEngine):
except RateLimitError:
raise # Re-raise rate limit errors
except requests.exceptions.RequestException as e:
- error_msg = str(e)
logger.exception(
"Error getting ScaleSerp API results. Check API docs: https://docs.scaleserp.com"
)
-
- # Check for rate limit patterns in error message
- if any(
- pattern in error_msg.lower()
- for pattern in [
- "429",
- "rate limit",
- "quota",
- "too many requests",
- ]
- ):
- raise RateLimitError(f"ScaleSerp rate limit hit: {error_msg}")
-
+ self._raise_if_rate_limit(e)
return []
except Exception:
logger.exception("Unexpected error getting ScaleSerp API results")
@@ -275,8 +251,7 @@ class ScaleSerpSearchEngine(BaseSearchEngine):
) -> List[Dict[str, Any]]:
"""
Get full content for the relevant search results.
- If include_full_content is True and FullSearchResults is available,
- retrieves full webpage content for the results.
+ Extends base implementation to include knowledge graph data.
Args:
relevant_items: List of relevant preview dictionaries
@@ -284,69 +259,10 @@ class ScaleSerpSearchEngine(BaseSearchEngine):
Returns:
List of result dictionaries with full content if requested
"""
- # Check if we should get full content
- from ...config import search_config
-
- if (
- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
- and search_config.SEARCH_SNIPPETS_ONLY
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full ScaleSerp information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- else:
- result = item.copy()
-
- # Clean up temporary fields
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
- # Include knowledge graph and other metadata if this is the first call
- if results and self._knowledge_graph:
- results[0]["knowledge_graph"] = self._knowledge_graph
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, "full_search"):
- logger.info("Retrieving full webpage content")
-
- try:
- # Use FullSearchResults to get full content
- results_with_content = self.full_search._get_full_content(
- relevant_items
- )
-
- return results_with_content
-
- except Exception as e:
- logger.info(f"Error retrieving full content: {e}")
- # Fall back to returning the items without full content
-
- # Return items with their full ScaleSerp information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- else:
- result = item.copy()
-
- # Clean up temporary fields
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
+ results = super()._get_full_content(relevant_items)
- # Include knowledge graph and other metadata if this is the first call
- if results and self._knowledge_graph:
+ # Include knowledge graph if available
+ if results and hasattr(self, "_knowledge_graph"):
results[0]["knowledge_graph"] = self._knowledge_graph
return results
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
index fceb56dedc..0e20acd563 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py
@@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optional
from langchain_community.utilities import SerpAPIWrapper
from langchain_core.language_models import BaseLLM
-from ...config import search_config
+from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -71,20 +71,13 @@ class SerpAPISearchEngine(BaseSearchEngine):
"russian": "ru",
}
- # Get API key - check params, env vars, or database
- from ...config.search_config import get_setting_from_snapshot
-
- serpapi_api_key = api_key
- if not serpapi_api_key:
- serpapi_api_key = get_setting_from_snapshot(
- "search.engine.web.serpapi.api_key",
- settings_snapshot=settings_snapshot,
- )
-
- if not serpapi_api_key:
- raise ValueError(
- "SerpAPI key not found. Please provide api_key parameter, set the LDR_SEARCH_ENGINE_WEB_SERPAPI_API_KEY environment variable, or set it in the UI settings."
- )
+ # Get API key - check params, settings, or env vars
+ serpapi_api_key = self._resolve_api_key(
+ api_key,
+ "search.engine.web.serpapi.api_key",
+ engine_name="SerpAPI",
+ settings_snapshot=settings_snapshot,
+ )
# Get language code
language_code = language_code_mapping.get(search_language.lower(), "en")
@@ -165,83 +158,13 @@ class SerpAPISearchEngine(BaseSearchEngine):
return previews
- except Exception:
+ except RateLimitError:
+ raise
+ except Exception as e:
logger.exception("Error getting SerpAPI results")
+ self._raise_if_rate_limit(e)
return []
- def _get_full_content(
- self, relevant_items: List[Dict[str, Any]]
- ) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant search results.
- If include_full_content is True and FullSearchResults is available,
- retrieves full webpage content for the results.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content if requested
- """
- # Check if we should get full content
- if (
- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
- and search_config.SEARCH_SNIPPETS_ONLY
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full SerpAPI information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"]
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item
-
- results.append(result)
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, "full_search"):
- logger.info("Retrieving full webpage content")
-
- try:
- # Use FullSearchResults to get full content
- # This is a simplified approach - in a real implementation,
- # you would need to fetch and process the URLs
- results_with_content = self.full_search._get_full_content(
- relevant_items
- )
-
- return results_with_content
-
- except Exception as e:
- logger.info(f"Error retrieving full content: {e}")
- # Fall back to returning the items without full content
-
- # Return items with their full SerpAPI information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item.copy()
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
- return results
-
def run(
self, query: str, research_context: Dict[str, Any] | None = None
) -> List[Dict[str, Any]]:
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py b/src/local_deep_research/web_search_engines/engines/search_engine_serper.py
index d93ec3a741..41484c0755 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serper.py
@@ -67,20 +67,13 @@ class SerperSearchEngine(BaseSearchEngine):
self.safe_search = safe_search
self.search_language = search_language
- # Get API key - check params, env vars, or database
- from ...config.search_config import get_setting_from_snapshot
-
- serper_api_key = api_key
- if not serper_api_key:
- serper_api_key = get_setting_from_snapshot(
- "search.engine.web.serper.api_key",
- settings_snapshot=settings_snapshot,
- )
-
- if not serper_api_key:
- raise ValueError(
- "Serper API key not found. Please provide api_key parameter or set it in the UI settings."
- )
+ # Get API key - check params, settings, or env vars
+ serper_api_key = self._resolve_api_key(
+ api_key,
+ "search.engine.web.serper.api_key",
+ engine_name="Serper",
+ settings_snapshot=settings_snapshot,
+ )
self.api_key = serper_api_key
self.base_url = self.BASE_URL
@@ -169,10 +162,7 @@ class SerperSearchEngine(BaseSearchEngine):
)
# Check for rate limits
- if response.status_code == 429:
- raise RateLimitError(
- f"Serper rate limit hit: {response.status_code} - {response.text}"
- )
+ self._raise_if_rate_limit(response.status_code)
response.raise_for_status()
@@ -244,21 +234,8 @@ class SerperSearchEngine(BaseSearchEngine):
except RateLimitError:
raise # Re-raise rate limit errors
except requests.exceptions.RequestException as e:
- error_msg = str(e)
logger.exception("Error getting Serper API results")
-
- # Check for rate limit patterns in error message
- if any(
- pattern in error_msg.lower()
- for pattern in [
- "429",
- "rate limit",
- "quota",
- "too many requests",
- ]
- ):
- raise RateLimitError(f"Serper rate limit hit: {error_msg}")
-
+ self._raise_if_rate_limit(e)
return []
except Exception:
logger.exception("Unexpected error getting Serper API results")
@@ -269,8 +246,7 @@ class SerperSearchEngine(BaseSearchEngine):
) -> List[Dict[str, Any]]:
"""
Get full content for the relevant search results.
- If include_full_content is True and FullSearchResults is available,
- retrieves full webpage content for the results.
+ Extends base implementation to include knowledge graph data.
Args:
relevant_items: List of relevant preview dictionaries
@@ -278,69 +254,10 @@ class SerperSearchEngine(BaseSearchEngine):
Returns:
List of result dictionaries with full content if requested
"""
- # Check if we should get full content
- from ...config import search_config
-
- if (
- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
- and search_config.SEARCH_SNIPPETS_ONLY
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full Serper information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- else:
- result = item.copy()
-
- # Clean up temporary fields
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
- # Include knowledge graph and other metadata if this is the first call
- if results and self._knowledge_graph:
- results[0]["knowledge_graph"] = self._knowledge_graph
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, "full_search"):
- logger.info("Retrieving full webpage content")
-
- try:
- # Use FullSearchResults to get full content
- results_with_content = self.full_search._get_full_content(
- relevant_items
- )
-
- return results_with_content
-
- except Exception as e:
- logger.info(f"Error retrieving full content: {e}")
- # Fall back to returning the items without full content
-
- # Return items with their full Serper information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- else:
- result = item.copy()
-
- # Clean up temporary fields
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
+ results = super()._get_full_content(relevant_items)
- # Include knowledge graph and other metadata if this is the first call
- if results and self._knowledge_graph:
+ # Include knowledge graph if available
+ if results and hasattr(self, "_knowledge_graph"):
results[0]["knowledge_graph"] = self._knowledge_graph
return results
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
index c97f3494bf..bdf1ebf7fc 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_tavily.py
@@ -4,7 +4,6 @@ import requests
from langchain_core.language_models import BaseLLM
from loguru import logger
-from ...config import search_config
from ...security.safe_requests import safe_post
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine
@@ -66,21 +65,13 @@ class TavilySearchEngine(BaseSearchEngine):
self.include_domains = include_domains or []
self.exclude_domains = exclude_domains or []
- # Get API key - check params, database, or env vars
- from ...config.search_config import get_setting_from_snapshot
-
- tavily_api_key = api_key
- if not tavily_api_key:
- tavily_api_key = get_setting_from_snapshot(
- "search.engine.web.tavily.api_key",
- settings_snapshot=settings_snapshot,
- )
-
- if not tavily_api_key:
- raise ValueError(
- "Tavily API key not found. Please provide api_key parameter, "
- "set it in the UI settings, or set LDR_SEARCH_ENGINE_WEB_TAVILY_API_KEY environment variable."
- )
+ # Get API key - check params, settings, or env vars
+ tavily_api_key = self._resolve_api_key(
+ api_key,
+ "search.engine.web.tavily.api_key",
+ engine_name="Tavily",
+ settings_snapshot=settings_snapshot,
+ )
self.api_key = tavily_api_key
self.base_url = "https://api.tavily.com"
@@ -159,11 +150,8 @@ class TavilySearchEngine(BaseSearchEngine):
timeout=30,
)
- # Check for errors
- if response.status_code == 429:
- raise RateLimitError(
- f"Tavily rate limit hit: {response.status_code} - {response.text}"
- )
+ # Check for rate limits
+ self._raise_if_rate_limit(response.status_code)
response.raise_for_status()
@@ -198,21 +186,8 @@ class TavilySearchEngine(BaseSearchEngine):
except RateLimitError:
raise # Re-raise rate limit errors
except requests.exceptions.RequestException as e:
- error_msg = str(e)
logger.exception("Error getting Tavily results")
-
- # Check for rate limit patterns in error message
- if any(
- pattern in error_msg.lower()
- for pattern in [
- "429",
- "rate limit",
- "quota",
- "too many requests",
- ]
- ):
- raise RateLimitError(f"Tavily rate limit hit: {error_msg}")
-
+ self._raise_if_rate_limit(e)
return []
except Exception:
logger.exception("Unexpected error getting Tavily results")
@@ -223,8 +198,7 @@ class TavilySearchEngine(BaseSearchEngine):
) -> List[Dict[str, Any]]:
"""
Get full content for the relevant search results.
- If include_full_content is True and raw content was retrieved,
- includes it in the results.
+ Extends base implementation to include Tavily's raw_content.
Args:
relevant_items: List of relevant preview dictionaries
@@ -232,68 +206,16 @@ class TavilySearchEngine(BaseSearchEngine):
Returns:
List of result dictionaries with full content if available
"""
- # Check if we should get full content
- if (
- hasattr(search_config, "SEARCH_SNIPPETS_ONLY")
- and search_config.SEARCH_SNIPPETS_ONLY
- ):
- logger.info("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full Tavily information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"]
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item
-
- results.append(result)
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, "full_search"):
- logger.info("Retrieving full webpage content")
+ results = super()._get_full_content(relevant_items)
- try:
- # Use FullSearchResults to get full content
- results_with_content = self.full_search._get_full_content(
- relevant_items
- )
-
- return results_with_content
-
- except Exception:
- logger.exception("Error retrieving full content")
- # Fall back to returning the items without full content
-
- # Return items with their full Tavily information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
-
- # If Tavily provided raw_content, include it
- if "raw_content" in result and self.include_full_content:
+ # If Tavily provided raw_content and full content is requested, use it
+ if self.include_full_content:
+ for result in results:
+ if "raw_content" in result:
result["content"] = result.get(
"raw_content", result.get("content", "")
)
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item.copy()
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
return results
def run(
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 41e0c8a928..7d884d9fb5 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
@@ -1,8 +1,9 @@
import json
+import re
import time
from abc import ABC, abstractmethod
from datetime import datetime, UTC
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Set, Union
from langchain_core.language_models import BaseLLM
from loguru import logger
@@ -15,6 +16,7 @@ from tenacity import (
from tenacity.wait import wait_base
from ..advanced_search_system.filters.base_filter import BaseFilter
+from ..config.thread_settings import get_setting_from_snapshot
from ..utilities.json_utils import extract_json, get_llm_response_text
from ..utilities.thread_context import clear_search_context, set_search_context
@@ -63,6 +65,22 @@ class BaseSearchEngine(ABC):
# Code engines specialize in searching code repositories
is_code = False
+ # Class attribute for rate limit detection patterns
+ # Subclasses can override to add engine-specific patterns
+ rate_limit_patterns: Set[str] = {
+ "rate limit",
+ "rate_limit",
+ "ratelimit",
+ "too many requests",
+ "throttl",
+ "quota exceeded",
+ "quota_exceeded",
+ "limit exceeded",
+ "request limit",
+ "api limit",
+ "usage limit",
+ }
+
@staticmethod
def _ensure_list(value, *, default=None):
"""Normalize a value that should be a list.
@@ -649,31 +667,354 @@ Respond with ONLY the JSON array, no other text."""
# Fall back to returning top results on error
return previews[: min(5, len(previews))]
- @abstractmethod
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ # =========================================================================
+ # Shared Helper Methods for Subclasses
+ # =========================================================================
+
+ @staticmethod
+ def _is_valid_api_key(api_key: Optional[str]) -> bool:
"""
- Get preview information (titles, summaries) for initial search results.
+ Check if an API key is valid (not a placeholder value).
Args:
- query: The search query
+ api_key: The API key to validate
Returns:
- List of preview dictionaries with at least 'id', 'title', and 'snippet' keys
+ True if the key appears to be a real API key, False if it's a placeholder
+
+ Example:
+ >>> BaseSearchEngine._is_valid_api_key("sk-abc123")
+ True
+ >>> BaseSearchEngine._is_valid_api_key("YOUR_API_KEY_HERE")
+ False
"""
- pass
+ if not api_key:
+ return False
+
+ api_key = api_key.strip()
+
+ # Empty or whitespace-only
+ if not api_key:
+ return False
+
+ # Common placeholder values
+ placeholders = {
+ "",
+ "None",
+ "null",
+ "PLACEHOLDER",
+ "YOUR_API_KEY_HERE",
+ "YOUR_API_KEY",
+ "API_KEY",
+ "your_api_key",
+ "your-api-key",
+ }
+
+ if api_key in placeholders:
+ return False
+
+ # Patterns that indicate placeholders
+ if api_key.endswith("_API_KEY"):
+ return False
+ if api_key.startswith("YOUR_"):
+ return False
+ if api_key.startswith("<") and api_key.endswith(">"):
+ return False
+ if api_key.startswith("${") and api_key.endswith("}"):
+ return False
+
+ return True
+
+ def _resolve_api_key(
+ self,
+ api_key: Optional[str],
+ setting_key: str,
+ engine_name: str = "search engine",
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ ) -> str:
+ """
+ Resolve an API key from multiple sources with priority order.
+
+ Environment variables are handled automatically by SettingsManager
+ when building the settings snapshot, so they don't need to be
+ checked separately here.
+
+ Priority order:
+ 1. Direct parameter (api_key argument)
+ 2. Settings snapshot (via setting_key)
+
+ Args:
+ api_key: API key passed directly as parameter
+ setting_key: Key to look up in settings snapshot (e.g., "search.brave_api_key")
+ engine_name: Human-readable engine name for error messages
+ settings_snapshot: Optional settings snapshot dict (uses self.settings_snapshot if not provided)
+
+ Returns:
+ The resolved API key string
+
+ Raises:
+ ValueError: If no valid API key is found from any source
+
+ Example:
+ >>> engine._resolve_api_key(
+ ... api_key=None,
+ ... setting_key="search.brave_api_key",
+ ... engine_name="Brave Search"
+ ... )
+ "sk-abc123..."
+ """
+ # Use instance settings snapshot if not provided
+ if settings_snapshot is None:
+ settings_snapshot = self.settings_snapshot
+
+ # Priority 1: Direct parameter
+ if self._is_valid_api_key(api_key):
+ return api_key.strip()
+
+ # Priority 2: Settings snapshot (includes env var overrides via SettingsManager)
+ if settings_snapshot:
+ settings_value = get_setting_from_snapshot(
+ setting_key,
+ default=None,
+ settings_snapshot=settings_snapshot,
+ )
+ if self._is_valid_api_key(settings_value):
+ return settings_value.strip() if settings_value else ""
+
+ # No valid API key found
+ masked_key = self._mask_api_key(str(api_key)) if api_key else "None"
+ raise ValueError(
+ f"No valid API key found for {engine_name}. "
+ f"Checked: direct parameter ({masked_key}), "
+ f"settings key '{setting_key}'. "
+ f"Please provide a valid API key."
+ )
+
+ def _is_rate_limit_error(
+ self,
+ error: Union[Exception, str, int],
+ additional_patterns: Optional[Set[str]] = None,
+ ) -> bool:
+ """
+ Detect if an error is a rate limit error.
+
+ Checks multiple sources for rate limit indicators:
+ - HTTP status code 429
+ - HTTPError response objects
+ - Error messages containing rate limit phrases
+
+ Args:
+ error: The error to check (Exception, string, or HTTP status code)
+ additional_patterns: Optional set of additional patterns to match
+
+ Returns:
+ True if the error appears to be a rate limit error
+
+ Example:
+ >>> engine._is_rate_limit_error(429)
+ True
+ >>> engine._is_rate_limit_error("Rate limit exceeded")
+ True
+ >>> engine._is_rate_limit_error(ValueError("Invalid input"))
+ False
+ """
+ # Combine default and additional patterns
+ patterns = self.rate_limit_patterns.copy()
+ if additional_patterns:
+ patterns.update(additional_patterns)
+
+ # Check integer status code directly
+ if isinstance(error, int):
+ return error == 429
+
+ # Convert to string for pattern matching
+ error_str = ""
+ status_code = None
+
+ if isinstance(error, str):
+ error_str = error
+ elif isinstance(error, Exception):
+ error_str = str(error)
+
+ # Check for HTTP status code in common HTTP error types
+ if hasattr(error, "status_code"):
+ status_code = error.status_code
+ elif hasattr(error, "response"):
+ response = error.response
+ if hasattr(response, "status_code"):
+ status_code = response.status_code
+
+ # Check status code first
+ if status_code == 429:
+ return True
+
+ # Case-insensitive pattern matching
+ error_lower = error_str.lower()
+ for pattern in patterns:
+ if pattern.lower() in error_lower:
+ return True
+
+ return False
+
+ def _raise_if_rate_limit(
+ self,
+ error: Union[Exception, str, int],
+ additional_patterns: Optional[Set[str]] = None,
+ ) -> None:
+ """
+ Raise RateLimitError if the given error is a rate limit error.
+
+ Convenience method that combines _is_rate_limit_error check with
+ raising RateLimitError.
+
+ Args:
+ error: The error to check
+ additional_patterns: Optional set of additional patterns to match
+
+ Raises:
+ RateLimitError: If the error is detected as a rate limit error
+
+ Example:
+ >>> try:
+ ... response = make_api_call()
+ ... except Exception as e:
+ ... engine._raise_if_rate_limit(e)
+ """
+ if self._is_rate_limit_error(error, additional_patterns):
+ error_msg = str(error) if not isinstance(error, str) else error
+ raise RateLimitError(
+ f"Rate limit detected: {self._sanitize_error_message(error_msg)}"
+ )
+
+ def _extract_full_result(self, item: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Extract the full result from an item that may contain a _full_result key.
+
+ This is a helper for the default _get_full_content implementation.
+ It extracts data from the _full_result key if present, otherwise uses
+ the item directly, and removes the internal _full_result key.
+
+ Args:
+ item: A search result item that may contain a _full_result key
+
+ Returns:
+ A dictionary with the full result data, without the _full_result key
+
+ Example:
+ >>> engine._extract_full_result({"title": "A", "_full_result": {"title": "A", "content": "Full"}})
+ {"title": "A", "content": "Full"}
+ """
+ source = item.get("_full_result")
+ if source is None:
+ source = item
+ return {k: v for k, v in source.items() if k != "_full_result"}
- @abstractmethod
def _get_full_content(
self, relevant_items: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""
Get full content for the relevant items.
+ Default implementation extracts data from _full_result keys if present.
+ Subclasses can override this method to fetch additional content from
+ external sources (e.g., web scraping, API calls).
+
Args:
relevant_items: List of relevant preview dictionaries
Returns:
List of result dictionaries with full content
+
+ Example:
+ >>> engine._get_full_content([
+ ... {"title": "A", "_full_result": {"title": "A", "content": "Full A"}},
+ ... {"title": "B"}
+ ... ])
+ [{"title": "A", "content": "Full A"}, {"title": "B"}]
+ """
+ if not relevant_items:
+ return []
+ return [self._extract_full_result(item) for item in relevant_items]
+
+ def _sanitize_error_message(self, message: str) -> str:
+ """
+ Remove/mask API keys, tokens, and secrets from error messages.
+
+ Uses pattern matching for common credential formats.
+
+ Args:
+ message: The error message to sanitize
+
+ Returns:
+ Sanitized message with sensitive data redacted
+
+ Example:
+ >>> engine._sanitize_error_message("Error with key sk-abc123xyz")
+ "Error with key [REDACTED]"
+ """
+ if not message:
+ return message
+
+ sanitized = message
+
+ # Additional regex patterns for common credential formats
+ patterns = [
+ # Bearer tokens
+ (r"Bearer\s+[A-Za-z0-9\-._~+/]+=*", "Bearer [REDACTED]"),
+ # API keys in URLs
+ (
+ r"([?&])(api_key|apikey|key|token|secret)=([A-Za-z0-9\-._~+/]+)",
+ r"\1\2=[REDACTED]",
+ ),
+ # URL credentials (user:pass@host)
+ (r"(https?://)([^:\s]+):([^@\s]+)@", r"\1[REDACTED]:[REDACTED]@"),
+ # Common API key patterns (sk-*, pk-*, etc.)
+ (r"\b(sk-[A-Za-z0-9]{20,})\b", "[REDACTED_KEY]"),
+ (r"\b(pk-[A-Za-z0-9]{20,})\b", "[REDACTED_KEY]"),
+ ]
+
+ for pattern, replacement in patterns:
+ sanitized = re.sub(pattern, replacement, sanitized)
+
+ return sanitized
+
+ def _mask_api_key(self, api_key: str, visible_chars: int = 4) -> str:
+ """
+ Mask an API key for safe logging, showing only first and last characters.
+
+ Args:
+ api_key: The API key to mask
+ visible_chars: Number of characters to show at start and end
+
+ Returns:
+ Masked API key in format "sk-1...nop" or "***" for short keys
+
+ Example:
+ >>> engine._mask_api_key("sk-abcdefghijklmnop123456")
+ "sk-a...3456"
+ >>> engine._mask_api_key("short")
+ "***"
+ """
+ if not api_key:
+ return "***"
+
+ api_key = str(api_key).strip()
+
+ if len(api_key) <= visible_chars * 2:
+ return "***"
+
+ return f"{api_key[:visible_chars]}...{api_key[-visible_chars:]}"
+
+ @abstractmethod
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Get preview information (titles, summaries) for initial search results.
+
+ Args:
+ query: The search query
+
+ Returns:
+ List of preview dictionaries with at least 'id', 'title', and 'snippet' keys
"""
pass
diff --git a/tests/search_engines/test_base_helpers.py b/tests/search_engines/test_base_helpers.py
new file mode 100644
index 0000000000..43ea335020
--- /dev/null
+++ b/tests/search_engines/test_base_helpers.py
@@ -0,0 +1,826 @@
+"""
+Tests for BaseSearchEngine helper methods.
+
+Tests cover:
+- _resolve_api_key() - API key resolution from multiple sources
+- _is_rate_limit_error() - Rate limit error detection
+- _get_full_content() - Default full content extraction
+- _sanitize_error_message() - Error message sanitization
+- _mask_api_key() - API key masking for safe logging
+"""
+
+import copy
+from unittest.mock import Mock, patch
+
+import pytest
+
+from src.local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+)
+from src.local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+)
+
+
+class ConcreteSearchEngine(BaseSearchEngine):
+ """Concrete implementation for testing."""
+
+ is_public = True
+ is_generic = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, relevant_items):
+ return super()._get_full_content(relevant_items)
+
+
+class TestIsValidApiKey:
+ """Tests for _is_valid_api_key static method."""
+
+ def test_valid_api_key_returns_true(self):
+ """Valid API key returns True."""
+ assert BaseSearchEngine._is_valid_api_key("sk-abc123def456") is True
+
+ def test_empty_string_returns_false(self):
+ """Empty string returns False."""
+ assert BaseSearchEngine._is_valid_api_key("") is False
+
+ def test_none_returns_false(self):
+ """None returns False."""
+ assert BaseSearchEngine._is_valid_api_key(None) is False
+
+ def test_placeholder_your_api_key_here(self):
+ """YOUR_API_KEY_HERE placeholder returns False."""
+ assert BaseSearchEngine._is_valid_api_key("YOUR_API_KEY_HERE") is False
+
+ def test_placeholder_none_string(self):
+ """'None' string returns False."""
+ assert BaseSearchEngine._is_valid_api_key("None") is False
+
+ def test_placeholder_null_string(self):
+ """'null' string returns False."""
+ assert BaseSearchEngine._is_valid_api_key("null") is False
+
+ def test_placeholder_ends_with_api_key(self):
+ """Keys ending with _API_KEY are rejected."""
+ assert BaseSearchEngine._is_valid_api_key("BRAVE_API_KEY") is False
+
+ def test_placeholder_starts_with_your(self):
+ """Keys starting with YOUR_ are rejected."""
+ assert BaseSearchEngine._is_valid_api_key("YOUR_SECRET_KEY") is False
+
+ def test_whitespace_only_returns_false(self):
+ """Whitespace-only string returns False."""
+ assert BaseSearchEngine._is_valid_api_key(" ") is False
+
+ def test_strips_whitespace(self):
+ """Valid key with whitespace is accepted after stripping."""
+ assert BaseSearchEngine._is_valid_api_key(" sk-abc123 ") is True
+
+ def test_angle_bracket_placeholder(self):
+ """Angle bracket placeholders are rejected."""
+ assert BaseSearchEngine._is_valid_api_key("<API_KEY>") is False
+
+ def test_env_var_placeholder(self):
+ """Environment variable placeholders are rejected."""
+ assert BaseSearchEngine._is_valid_api_key("${API_KEY}") is False
+
+
+class TestResolveApiKey:
+ """Tests for _resolve_api_key method."""
+
+ def test_returns_provided_key(self):
+ """Returns the provided API key when valid."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._resolve_api_key(
+ api_key="sk-direct-key",
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert result == "sk-direct-key"
+
+ def test_falls_back_to_settings(self):
+ """Falls back to settings snapshot when no direct key."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "sk-settings-key"},
+ programmatic_mode=True,
+ )
+ result = engine._resolve_api_key(
+ api_key=None,
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert result == "sk-settings-key"
+
+ def test_priority_order(self):
+ """Direct parameter takes priority over settings."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "sk-settings-key"},
+ programmatic_mode=True,
+ )
+ result = engine._resolve_api_key(
+ api_key="sk-direct-key",
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert result == "sk-direct-key"
+
+ def test_rejects_placeholder_in_direct_key(self):
+ """Rejects placeholder values in direct parameter."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "sk-settings-key"},
+ programmatic_mode=True,
+ )
+ result = engine._resolve_api_key(
+ api_key="YOUR_API_KEY_HERE",
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert result == "sk-settings-key"
+
+ def test_raises_value_error_when_not_found(self):
+ """Raises ValueError when no valid key found."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ with pytest.raises(ValueError) as exc_info:
+ engine._resolve_api_key(
+ api_key=None,
+ setting_key="search.nonexistent_key",
+ engine_name="Test Engine",
+ )
+ assert "No valid API key found" in str(exc_info.value)
+ assert "Test Engine" in str(exc_info.value)
+
+ def test_handles_empty_string(self):
+ """Empty string is treated as no key provided."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "sk-settings-key"},
+ programmatic_mode=True,
+ )
+ result = engine._resolve_api_key(
+ api_key="",
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert result == "sk-settings-key"
+
+ def test_strips_whitespace_from_key(self):
+ """Strips whitespace from resolved key."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._resolve_api_key(
+ api_key=" sk-whitespace-key ",
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert result == "sk-whitespace-key"
+
+ def test_uses_instance_settings_snapshot(self):
+ """Uses self.settings_snapshot when snapshot not provided."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "sk-instance-key"},
+ programmatic_mode=True,
+ )
+ result = engine._resolve_api_key(
+ api_key=None,
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ settings_snapshot=None, # Should use self.settings_snapshot
+ )
+ assert result == "sk-instance-key"
+
+
+class TestIsRateLimitError:
+ """Tests for _is_rate_limit_error method."""
+
+ def test_detects_429_status_code(self):
+ """Detects 429 HTTP status code."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error(429) is True
+
+ def test_429_alone_does_not_match(self):
+ """Bare '429' in a string does not trigger false positive."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error("Error code 429") is False
+ # But '429' combined with a real phrase still matches
+ assert (
+ engine._is_rate_limit_error("Error 429: Too Many Requests") is True
+ )
+
+ def test_detects_rate_limit_phrases(self):
+ """Detects common rate limit phrases."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error("Rate limit exceeded") is True
+ assert engine._is_rate_limit_error("rate_limit hit") is True
+ assert engine._is_rate_limit_error("You hit the ratelimit") is True
+
+ def test_case_insensitive(self):
+ """Detection is case insensitive."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error("RATE LIMIT EXCEEDED") is True
+ assert engine._is_rate_limit_error("Rate Limit Exceeded") is True
+
+ def test_detects_httperror_with_429(self):
+ """Detects HTTPError with 429 status code."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+
+ class MockHTTPError(Exception):
+ def __init__(self):
+ super().__init__("HTTP Error")
+ self.response = Mock(status_code=429)
+
+ error = MockHTTPError()
+ assert engine._is_rate_limit_error(error) is True
+
+ def test_additional_patterns(self):
+ """Additional patterns are matched."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert (
+ engine._is_rate_limit_error(
+ "Custom error", additional_patterns={"custom error"}
+ )
+ is True
+ )
+
+ def test_detects_throttling(self):
+ """Detects throttling messages."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error("Request throttled") is True
+ assert engine._is_rate_limit_error("Throttling active") is True
+
+ def test_non_rate_limit_error(self):
+ """Non-rate-limit errors return False."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error(ValueError("Invalid input")) is False
+ assert engine._is_rate_limit_error("Connection refused") is False
+ assert engine._is_rate_limit_error(500) is False
+
+ def test_detects_quota_exceeded(self):
+ """Detects quota exceeded messages."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert engine._is_rate_limit_error("Quota exceeded for today") is True
+ assert engine._is_rate_limit_error("API quota_exceeded") is True
+
+ def test_detects_too_many_requests(self):
+ """Detects 'too many requests' phrase."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ assert (
+ engine._is_rate_limit_error("Too many requests, please slow down")
+ is True
+ )
+
+
+class TestRaiseIfRateLimit:
+ """Tests for _raise_if_rate_limit method."""
+
+ def test_raises_rate_limit_error_when_detected(self):
+ """Raises RateLimitError when rate limit detected."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ with pytest.raises(RateLimitError):
+ engine._raise_if_rate_limit(429)
+
+ def test_does_not_raise_for_non_rate_limit(self):
+ """Does not raise for non-rate-limit errors."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ # Should not raise
+ engine._raise_if_rate_limit("Connection refused")
+ engine._raise_if_rate_limit(ValueError("Invalid input"))
+
+ def test_sanitizes_error_message(self):
+ """Error message is sanitized before raising."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ with pytest.raises(RateLimitError) as exc_info:
+ engine._raise_if_rate_limit(
+ "Rate limit with key sk-abcd1234efgh5678ijkl"
+ )
+ # The API key should be redacted
+ assert "sk-abcd1234" not in str(exc_info.value)
+
+
+class TestGetFullContentDefault:
+ """Tests for default _get_full_content implementation."""
+
+ def test_empty_input(self):
+ """Empty input returns empty list."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._get_full_content([])
+ assert result == []
+
+ def test_extracts_full_result(self):
+ """Extracts data from _full_result key."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [
+ {
+ "title": "Preview",
+ "_full_result": {"title": "Full", "content": "Content"},
+ }
+ ]
+ result = engine._get_full_content(items)
+ assert len(result) == 1
+ assert result[0]["title"] == "Full"
+ assert result[0]["content"] == "Content"
+
+ def test_uses_item_when_no_full_result(self):
+ """Uses item directly when no _full_result key."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [{"title": "Preview", "snippet": "Snippet"}]
+ result = engine._get_full_content(items)
+ assert len(result) == 1
+ assert result[0]["title"] == "Preview"
+ assert result[0]["snippet"] == "Snippet"
+
+ def test_removes_internal_key(self):
+ """Removes _full_result key from output."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [
+ {
+ "title": "Preview",
+ "_full_result": {"title": "Full", "content": "Content"},
+ }
+ ]
+ result = engine._get_full_content(items)
+ assert "_full_result" not in result[0]
+
+ def test_handles_nested_data(self):
+ """Handles nested data structures."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [
+ {
+ "title": "Preview",
+ "_full_result": {
+ "title": "Full",
+ "metadata": {"author": "Test", "date": "2024-01-01"},
+ },
+ }
+ ]
+ result = engine._get_full_content(items)
+ assert result[0]["metadata"]["author"] == "Test"
+
+ def test_multiple_items(self):
+ """Handles multiple items correctly."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [
+ {"title": "A", "_full_result": {"title": "A Full"}},
+ {"title": "B", "_full_result": {"title": "B Full"}},
+ {"title": "C"}, # No _full_result
+ ]
+ result = engine._get_full_content(items)
+ assert len(result) == 3
+ assert result[0]["title"] == "A Full"
+ assert result[1]["title"] == "B Full"
+ assert result[2]["title"] == "C"
+
+
+class TestSanitizeErrorMessage:
+ """Tests for _sanitize_error_message method."""
+
+ def test_masks_bearer_tokens(self):
+ """Masks Bearer tokens."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Error with Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
+ )
+ assert "Bearer [REDACTED]" in result
+ assert "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" not in result
+
+ def test_masks_api_keys_in_urls(self):
+ """Masks API keys in URL parameters."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Failed to call https://api.example.com?api_key=secret123"
+ )
+ assert "api_key=[REDACTED]" in result
+ assert "secret123" not in result
+
+ def test_masks_url_credentials(self):
+ """Masks credentials in URLs."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Error connecting to https://user:[email protected]"
+ )
+ assert "[REDACTED]:[REDACTED]@" in result
+ assert "user" not in result or result.count("user") == 0
+ assert "password" not in result
+
+ def test_preserves_safe_content(self):
+ """Preserves non-sensitive content."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Connection timeout after 30 seconds"
+ )
+ assert result == "Connection timeout after 30 seconds"
+
+ def test_masks_sk_prefixed_keys(self):
+ """Masks sk- prefixed API keys."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Invalid API key: sk-abcdefghijklmnop1234567890"
+ )
+ assert "[REDACTED_KEY]" in result
+ assert "sk-abcdefghijklmnop1234567890" not in result
+
+ def test_masks_pk_prefixed_keys(self):
+ """Masks pk- prefixed API keys."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Invalid key: pk-test123456789012345678"
+ )
+ assert "[REDACTED_KEY]" in result
+
+ def test_empty_message(self):
+ """Empty message returns empty."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message("")
+ assert result == ""
+
+ def test_none_message(self):
+ """None message returns None."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(None)
+ assert result is None
+
+
+class TestMaskApiKey:
+ """Tests for _mask_api_key method."""
+
+ def test_masks_long_key(self):
+ """Masks long API key with visible chars at start and end."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._mask_api_key("sk-abcdefghijklmnop123456")
+ assert result == "sk-a...3456"
+ assert "bcdefghijklmnop12" not in result
+
+ def test_short_key_returns_stars(self):
+ """Short key returns ***."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._mask_api_key("short")
+ assert result == "***"
+
+ def test_empty_key_returns_stars(self):
+ """Empty key returns ***."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._mask_api_key("")
+ assert result == "***"
+
+ def test_none_key_returns_stars(self):
+ """None key returns ***."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._mask_api_key(None)
+ assert result == "***"
+
+ def test_custom_visible_chars(self):
+ """Custom visible_chars parameter works."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._mask_api_key(
+ "sk-abcdefghijklmnop123456", visible_chars=6
+ )
+ assert result == "sk-abc...123456"
+
+ def test_exact_boundary_length(self):
+ """Key at exactly visible_chars * 2 boundary."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ # 8 chars total, visible_chars=4 means 8 chars shown, so boundary case
+ result = engine._mask_api_key("12345678", visible_chars=4)
+ assert result == "***"
+
+ def test_just_over_boundary(self):
+ """Key just over boundary gets masked."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._mask_api_key("123456789", visible_chars=4)
+ assert result == "1234...6789"
+
+
+class TestRateLimitPatterns:
+ """Tests for rate_limit_patterns class attribute."""
+
+ def test_default_patterns_exist(self):
+ """Default patterns are defined."""
+ assert "rate limit" in BaseSearchEngine.rate_limit_patterns
+ assert "throttl" in BaseSearchEngine.rate_limit_patterns
+ assert "too many requests" in BaseSearchEngine.rate_limit_patterns
+
+ def test_subclass_can_extend_patterns(self):
+ """Subclass can extend patterns."""
+
+ class CustomEngine(BaseSearchEngine):
+ rate_limit_patterns = BaseSearchEngine.rate_limit_patterns | {
+ "custom limit",
+ "engine specific",
+ }
+
+ def _get_previews(self, query):
+ return []
+
+ assert "custom limit" in CustomEngine.rate_limit_patterns
+ assert "engine specific" in CustomEngine.rate_limit_patterns
+ # Original patterns still present
+ assert "rate limit" in CustomEngine.rate_limit_patterns
+
+ def test_patterns_are_case_insensitive_in_matching(self):
+ """Pattern matching is case insensitive."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ # All these should match due to case-insensitive comparison
+ assert engine._is_rate_limit_error("RATE LIMIT") is True
+ assert engine._is_rate_limit_error("Rate Limit") is True
+ assert engine._is_rate_limit_error("rate limit") is True
+
+
+class TestExtractFullResult:
+ """Tests for _extract_full_result helper method."""
+
+ def test_extracts_from_full_result(self):
+ """Extracts data from _full_result key."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ item = {
+ "title": "Preview",
+ "_full_result": {"title": "Full Title", "content": "Full Content"},
+ }
+ result = engine._extract_full_result(item)
+ assert result["title"] == "Full Title"
+ assert result["content"] == "Full Content"
+
+ def test_uses_item_when_no_full_result(self):
+ """Uses item directly when no _full_result."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ item = {"title": "Preview", "snippet": "Snippet"}
+ result = engine._extract_full_result(item)
+ assert result["title"] == "Preview"
+ assert result["snippet"] == "Snippet"
+
+ def test_removes_full_result_key(self):
+ """Removes _full_result from output."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ item = {
+ "title": "Preview",
+ "_full_result": {"title": "Full", "content": "Content"},
+ }
+ result = engine._extract_full_result(item)
+ assert "_full_result" not in result
+
+ def test_preserves_all_other_keys(self):
+ """Preserves all keys from source."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ item = {
+ "title": "Preview",
+ "_full_result": {
+ "title": "Full",
+ "content": "Content",
+ "url": "https://example.com",
+ "metadata": {"key": "value"},
+ },
+ }
+ result = engine._extract_full_result(item)
+ assert "url" in result
+ assert "metadata" in result
+ assert result["metadata"]["key"] == "value"
+
+
+# ── Additional coverage tests ──────────────────────────────────────────
+
+
+class TestRaiseIfRateLimitExtended:
+ """Extended tests for _raise_if_rate_limit — sanitization and edge cases."""
+
+ def test_sanitizes_api_key_in_error_message(self):
+ """API keys in error messages are redacted before raising."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ api_key = "sk-abcdefghijklmnop12345678"
+ with pytest.raises(RateLimitError) as exc_info:
+ engine._raise_if_rate_limit(f"Rate limit with key {api_key}")
+ assert api_key not in str(exc_info.value)
+ assert "[REDACTED_KEY]" in str(exc_info.value)
+
+ def test_passes_additional_patterns(self):
+ """Additional patterns are forwarded to detection."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ with pytest.raises(RateLimitError):
+ engine._raise_if_rate_limit(
+ "custom throttle triggered",
+ additional_patterns={"custom throttle"},
+ )
+
+ def test_does_not_raise_for_non_rate_limit(self):
+ """Non-rate-limit errors pass through without raising."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ # Should return None, not raise
+ result = engine._raise_if_rate_limit("Connection refused")
+ assert result is None
+
+ def test_handles_none_error(self):
+ """None error doesn't crash."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ # _is_rate_limit_error converts to string, "None" doesn't match any pattern
+ result = engine._raise_if_rate_limit(None)
+ assert result is None
+
+
+class TestSanitizeErrorMessageExtended:
+ """Extended tests for _sanitize_error_message — regex gaps."""
+
+ def test_preserves_long_alphanumeric_string(self):
+ """Non-secret 32+ char strings (UUIDs, request IDs) are preserved."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ request_id = "a" * 32
+ result = engine._sanitize_error_message(f"Request {request_id} failed")
+ assert request_id in result
+
+ def test_redacts_multiple_url_params(self):
+ """Multiple sensitive URL parameters are all redacted."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ result = engine._sanitize_error_message(
+ "Failed: https://api.example.com?api_key=secret1&token=secret2"
+ )
+ assert "secret1" not in result
+ assert "secret2" not in result
+ assert "api_key=[REDACTED]" in result
+ assert "token=[REDACTED]" in result
+
+ def test_sk_key_boundary_20_chars(self):
+ """sk- key with exactly 20 chars is redacted, 19 chars is not."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ key_20 = "sk-" + "a" * 20
+ key_19 = "sk-" + "a" * 19
+ result_20 = engine._sanitize_error_message(f"key: {key_20}")
+ result_19 = engine._sanitize_error_message(f"key: {key_19}")
+ assert key_20 not in result_20
+ assert "[REDACTED_KEY]" in result_20
+ # 19-char key doesn't match the sk- pattern (requires 20+)
+ assert key_19 in result_19
+
+ def test_multiple_patterns_in_one_message(self):
+ """Bearer token, sk- key, and URL credentials all redacted together."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ message = (
+ "Bearer eyJhbGciOiJIUzI1NiJ9 failed for "
+ "https://user:[email protected] with key "
+ "sk-abcdefghijklmnop123456"
+ )
+ result = engine._sanitize_error_message(message)
+ assert "Bearer [REDACTED]" in result
+ assert "[REDACTED]:[REDACTED]@" in result
+ assert "sk-abcdefghijklmnop123456" not in result
+
+
+class TestIsRateLimitErrorExtended:
+ """Extended tests for _is_rate_limit_error — direct status_code path."""
+
+ def test_direct_status_code_attribute_429(self):
+ """Exception with status_code=429 directly (not on .response)."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+
+ class DirectStatusError(Exception):
+ status_code = 429
+
+ assert engine._is_rate_limit_error(DirectStatusError("error")) is True
+
+ def test_direct_status_code_attribute_500(self):
+ """Exception with status_code=500 returns False."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+
+ class DirectStatusError(Exception):
+ status_code = 500
+
+ assert engine._is_rate_limit_error(DirectStatusError("error")) is False
+
+ def test_status_code_none(self):
+ """Exception with status_code=None doesn't crash."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+
+ class NoneStatusError(Exception):
+ status_code = None
+
+ assert engine._is_rate_limit_error(NoneStatusError("error")) is False
+
+
+class TestResolveApiKeyExtended:
+ """Extended tests for _resolve_api_key — placeholder cascade."""
+
+ def test_settings_returns_placeholder_raises_error(self):
+ """Settings returning a placeholder falls through to ValueError."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "YOUR_API_KEY_HERE"},
+ programmatic_mode=True,
+ )
+ with pytest.raises(ValueError) as exc_info:
+ engine._resolve_api_key(
+ api_key=None,
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+ assert "No valid API key found" in str(exc_info.value)
+
+ def test_both_direct_and_settings_are_placeholders(self):
+ """Both sources having placeholders raises ValueError."""
+ engine = ConcreteSearchEngine(
+ settings_snapshot={"search.api_key": "YOUR_API_KEY_HERE"},
+ programmatic_mode=True,
+ )
+ with pytest.raises(ValueError):
+ engine._resolve_api_key(
+ api_key="PLACEHOLDER",
+ setting_key="search.api_key",
+ engine_name="Test Engine",
+ )
+
+
+class TestGetFullContentExtended:
+ """Extended tests for _get_full_content — mutation safety and edge cases."""
+
+ def test_does_not_mutate_input_dicts(self):
+ """Input dicts remain unchanged after _get_full_content."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [
+ {
+ "title": "Preview",
+ "_full_result": {"title": "Full", "content": "Content"},
+ }
+ ]
+ original = copy.deepcopy(items)
+ engine._get_full_content(items)
+ assert items == original
+
+ def test_full_result_is_none(self):
+ """Item with _full_result=None falls back to the item itself."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [{"_full_result": None, "title": "test"}]
+ result = engine._get_full_content(items)
+ assert len(result) == 1
+ assert result[0]["title"] == "test"
+ assert "_full_result" not in result[0]
+
+ def test_full_result_is_empty_dict(self):
+ """Item with _full_result={} returns empty dict, does not fall back to item."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [{"_full_result": {}, "title": "test"}]
+ result = engine._get_full_content(items)
+ assert len(result) == 1
+ assert result[0] == {}
+
+ def test_conflicting_keys_full_result_wins(self):
+ """When _full_result has same key as item, _full_result's value is used."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ items = [
+ {
+ "title": "outer",
+ "_full_result": {
+ "title": "inner",
+ "url": "https://example.com",
+ },
+ }
+ ]
+ result = engine._get_full_content(items)
+ assert result[0]["title"] == "inner"
+ assert result[0]["url"] == "https://example.com"
+
+
+class TestRunIntegration:
+ """Integration tests for BaseSearchEngine.run() method."""
+
+ def test_search_snippets_only_skips_get_full_content(self):
+ """When search_snippets_only=True, _get_full_content is not called."""
+ engine = ConcreteSearchEngine(
+ search_snippets_only=True,
+ programmatic_mode=True,
+ )
+ previews = [{"title": "Result 1", "snippet": "..."}]
+ with patch.object(engine, "_get_previews", return_value=previews):
+ with patch.object(engine, "_get_full_content") as mock_full:
+ result = engine.run("test query")
+ mock_full.assert_not_called()
+ assert result == previews
+
+ def test_search_snippets_only_false_calls_get_full_content(self):
+ """When search_snippets_only=False, _get_full_content IS called."""
+ engine = ConcreteSearchEngine(
+ search_snippets_only=False,
+ programmatic_mode=True,
+ )
+ previews = [{"title": "Result 1", "snippet": "..."}]
+ full_content = [{"title": "Result 1", "content": "Full text"}]
+ with patch.object(engine, "_get_previews", return_value=previews):
+ with patch.object(
+ engine, "_get_full_content", return_value=full_content
+ ) as mock_full:
+ result = engine.run("test query")
+ mock_full.assert_called_once_with(previews)
+ assert result == full_content
+
+ def test_rate_limit_in_get_previews_returns_empty(self):
+ """RateLimitError in _get_previews returns empty list."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ with patch.object(
+ engine, "_get_previews", side_effect=RateLimitError("rate limited")
+ ):
+ result = engine.run("test query")
+ assert result == []
+
+ def test_non_rate_limit_exception_returns_empty(self):
+ """Non-rate-limit exception in _get_previews returns empty list."""
+ engine = ConcreteSearchEngine(programmatic_mode=True)
+ with patch.object(
+ engine, "_get_previews", side_effect=ConnectionError("failed")
+ ):
+ result = engine.run("test query")
+ assert result == []
diff --git a/tests/search_engines/test_search_engine_brave.py b/tests/search_engines/test_search_engine_brave.py
index 40d8797bce..1221d06c2f 100644
--- a/tests/search_engines/test_search_engine_brave.py
+++ b/tests/search_engines/test_search_engine_brave.py
@@ -65,19 +65,15 @@ class TestBraveSearchEngineInit:
engine_unsafe = BraveSearchEngine(api_key="test_key", safe_search=False)
assert engine_unsafe is not None
- def test_init_without_api_key_raises(self, monkeypatch):
+ def test_init_without_api_key_raises(self):
"""Test that initialization without API key raises ValueError."""
from local_deep_research.web_search_engines.engines.search_engine_brave import (
BraveSearchEngine,
)
- # Mock get_setting_from_snapshot to return None
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
- with pytest.raises(ValueError, match="Brave API key not found"):
+ with pytest.raises(
+ ValueError, match="No valid API key found for Brave Search"
+ ):
BraveSearchEngine()
def test_init_with_language_mapping(self):
diff --git a/tests/search_engines/test_search_engine_guardian.py b/tests/search_engines/test_search_engine_guardian.py
index 8007447109..6b53d3d705 100644
--- a/tests/search_engines/test_search_engine_guardian.py
+++ b/tests/search_engines/test_search_engine_guardian.py
@@ -12,14 +12,6 @@ from unittest.mock import Mock
class TestGuardianSearchEngineInit:
"""Tests for Guardian search engine initialization."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot for API key retrieval."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_init_with_api_key(self):
"""Test initialization with API key."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
@@ -41,13 +33,15 @@ class TestGuardianSearchEngineInit:
engine = GuardianSearchEngine(api_key="test_key", max_results=25)
assert engine.max_results >= 25
- def test_init_without_api_key_raises(self, monkeypatch):
+ def test_init_without_api_key_raises(self):
"""Test that initialization without API key raises ValueError."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
GuardianSearchEngine,
)
- with pytest.raises(ValueError, match="Guardian API key not found"):
+ with pytest.raises(
+ ValueError, match="No valid API key found for Guardian"
+ ):
GuardianSearchEngine()
def test_init_with_section(self):
@@ -81,14 +75,6 @@ class TestGuardianSearchEngineInit:
class TestGuardianDateConfiguration:
"""Tests for Guardian date configuration."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot for API key retrieval."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_default_dates_set(self):
"""Test that default dates are set automatically."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
@@ -140,14 +126,6 @@ class TestGuardianDateConfiguration:
class TestGuardianEngineType:
"""Tests for Guardian engine type identification."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot for API key retrieval."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_engine_type_set(self):
"""Test that engine type is properly set."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
@@ -182,14 +160,6 @@ class TestGuardianEngineType:
class TestGuardianQueryOptimization:
"""Tests for Guardian query optimization settings."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot for API key retrieval."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_optimize_queries_default(self):
"""Test that optimize_queries defaults to True."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
@@ -233,13 +203,8 @@ class TestGuardianSearchExecution:
"""Tests for Guardian search execution."""
@pytest.fixture
- def engine(self, monkeypatch):
- """Create a Guardian engine with mocked settings."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
+ def engine(self):
+ """Create a Guardian engine."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
GuardianSearchEngine,
)
@@ -335,13 +300,8 @@ class TestGuardianQueryOptimizationLogic:
"""Tests for Guardian query optimization logic."""
@pytest.fixture
- def engine(self, monkeypatch):
- """Create a Guardian engine with mocked settings."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
+ def engine(self):
+ """Create a Guardian engine."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
GuardianSearchEngine,
)
@@ -373,13 +333,8 @@ class TestGuardianDateAdaptation:
"""Tests for Guardian date adaptation logic."""
@pytest.fixture
- def engine(self, monkeypatch):
- """Create a Guardian engine with mocked settings."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
+ def engine(self):
+ """Create a Guardian engine."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
GuardianSearchEngine,
)
@@ -409,13 +364,8 @@ class TestGuardianSpecialMethods:
"""Tests for Guardian special methods."""
@pytest.fixture
- def engine(self, monkeypatch):
- """Create a Guardian engine with mocked settings."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
+ def engine(self):
+ """Create a Guardian engine."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
GuardianSearchEngine,
)
@@ -436,14 +386,6 @@ class TestGuardianSpecialMethods:
class TestGuardianOrderBySettings:
"""Tests for Guardian order_by settings."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot for API key retrieval."""
- monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_order_by_relevance(self):
"""Test order_by set to relevance."""
from local_deep_research.web_search_engines.engines.search_engine_guardian import (
diff --git a/tests/search_engines/test_search_engine_scaleserp.py b/tests/search_engines/test_search_engine_scaleserp.py
index e7b70d7f80..795ee170ce 100644
--- a/tests/search_engines/test_search_engine_scaleserp.py
+++ b/tests/search_engines/test_search_engine_scaleserp.py
@@ -9,15 +9,6 @@ import pytest
from unittest.mock import Mock
[email protected](autouse=True)
-def mock_settings(monkeypatch):
- """Mock settings to provide API key."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- Mock(return_value="test_api_key"),
- )
-
-
class TestScaleSerpSearchEngineInit:
"""Tests for ScaleSERP search engine initialization."""
@@ -67,7 +58,9 @@ class TestScaleSerpSearchEngineInit:
Mock(return_value=None),
)
- with pytest.raises(ValueError, match="ScaleSerp API key not found"):
+ with pytest.raises(
+ ValueError, match="No valid API key found for ScaleSerp"
+ ):
ScaleSerpSearchEngine()
def test_init_with_location(self):
@@ -187,7 +180,7 @@ class TestScaleSerpSearchExecution:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -218,7 +211,7 @@ class TestScaleSerpSearchExecution:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -250,7 +243,7 @@ class TestScaleSerpSearchExecution:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -272,7 +265,7 @@ class TestScaleSerpSearchExecution:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -291,7 +284,7 @@ class TestScaleSerpSearchExecution:
mock_response.text = "Rate limit exceeded"
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -303,7 +296,7 @@ class TestScaleSerpSearchExecution:
import requests
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(
side_effect=requests.exceptions.RequestException(
"Network error"
@@ -350,7 +343,7 @@ class TestScaleSerpRichSnippets:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -384,7 +377,7 @@ class TestScaleSerpRichSnippets:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
@@ -466,7 +459,7 @@ class TestScaleSerpURLParsing:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_scaleserp.requests.get",
+ "local_deep_research.web_search_engines.engines.search_engine_scaleserp.safe_get",
Mock(return_value=mock_response),
)
diff --git a/tests/search_engines/test_search_engine_serpapi.py b/tests/search_engines/test_search_engine_serpapi.py
index 08b010aa51..8ede7a5bfa 100644
--- a/tests/search_engines/test_search_engine_serpapi.py
+++ b/tests/search_engines/test_search_engine_serpapi.py
@@ -21,15 +21,6 @@ def mock_serpapi_wrapper(monkeypatch):
return mock_wrapper
[email protected](autouse=True)
-def mock_settings(monkeypatch):
- """Mock settings to provide API key."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- Mock(return_value="test_api_key"),
- )
-
-
class TestSerpAPISearchEngineInit:
"""Tests for SerpAPI search engine initialization."""
@@ -65,7 +56,9 @@ class TestSerpAPISearchEngineInit:
Mock(return_value=None),
)
- with pytest.raises(ValueError, match="SerpAPI key not found"):
+ with pytest.raises(
+ ValueError, match="No valid API key found for SerpAPI"
+ ):
SerpAPISearchEngine()
def test_init_with_region(self):
diff --git a/tests/search_engines/test_search_engine_serper.py b/tests/search_engines/test_search_engine_serper.py
index 2bb61381ce..4374f2d4e4 100644
--- a/tests/search_engines/test_search_engine_serper.py
+++ b/tests/search_engines/test_search_engine_serper.py
@@ -9,15 +9,6 @@ import pytest
from unittest.mock import Mock
[email protected](autouse=True)
-def mock_settings(monkeypatch):
- """Mock settings to provide API key."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- Mock(return_value="test_api_key"),
- )
-
-
class TestSerperSearchEngineInit:
"""Tests for Serper search engine initialization."""
@@ -65,7 +56,9 @@ class TestSerperSearchEngineInit:
Mock(return_value=None),
)
- with pytest.raises(ValueError, match="API key not found"):
+ with pytest.raises(
+ ValueError, match="No valid API key found for Serper"
+ ):
SerperSearchEngine()
def test_init_with_region(self):
@@ -182,7 +175,7 @@ class TestSerperSearchExecution:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -216,7 +209,7 @@ class TestSerperSearchExecution:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -233,7 +226,7 @@ class TestSerperSearchExecution:
mock_response.json = Mock(return_value={"organic": []})
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -252,7 +245,7 @@ class TestSerperSearchExecution:
mock_response.text = "Rate limit exceeded"
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -264,7 +257,7 @@ class TestSerperSearchExecution:
import requests
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(
side_effect=requests.exceptions.RequestException(
"Network error"
@@ -278,7 +271,7 @@ class TestSerperSearchExecution:
def test_get_previews_handles_general_exception(self, engine, monkeypatch):
"""Test that general exceptions are handled gracefully."""
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(side_effect=Exception("Unexpected error")),
)
@@ -421,7 +414,7 @@ class TestSerperURLParsing:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -439,7 +432,7 @@ class TestSerperURLParsing:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -484,7 +477,7 @@ class TestSerperAdditionalFeatures:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -512,7 +505,7 @@ class TestSerperAdditionalFeatures:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
@@ -540,7 +533,7 @@ class TestSerperAdditionalFeatures:
)
monkeypatch.setattr(
- "local_deep_research.web_search_engines.engines.search_engine_serper.requests.post",
+ "local_deep_research.web_search_engines.engines.search_engine_serper.safe_post",
Mock(return_value=mock_response),
)
diff --git a/tests/search_engines/test_search_engine_tavily.py b/tests/search_engines/test_search_engine_tavily.py
index b5a243d87b..4401b30f14 100644
--- a/tests/search_engines/test_search_engine_tavily.py
+++ b/tests/search_engines/test_search_engine_tavily.py
@@ -55,7 +55,9 @@ class TestTavilySearchEngineInit:
TavilySearchEngine,
)
- with pytest.raises(ValueError, match="Tavily API key not found"):
+ with pytest.raises(
+ ValueError, match="No valid API key found for Tavily"
+ ):
TavilySearchEngine()
def test_init_with_search_depth(self, monkeypatch):
@@ -97,14 +99,6 @@ class TestTavilySearchEngineInit:
class TestTavilyDomainFiltering:
"""Tests for Tavily domain filtering."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_include_domains_default(self):
"""Test that include_domains defaults to empty list."""
from local_deep_research.web_search_engines.engines.search_engine_tavily import (
@@ -149,14 +143,6 @@ class TestTavilyDomainFiltering:
class TestTavilyEngineType:
"""Tests for Tavily engine type identification."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_engine_type_set(self):
"""Test that engine type is properly set."""
from local_deep_research.web_search_engines.engines.search_engine_tavily import (
@@ -327,14 +313,6 @@ class TestTavilyRateLimiting:
class TestTavilyFullContent:
"""Tests for Tavily full content retrieval."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_include_full_content_flag_true(self):
"""Test include_full_content flag is set correctly when True."""
from local_deep_research.web_search_engines.engines.search_engine_tavily import (
@@ -386,14 +364,6 @@ class TestTavilyFullContent:
class TestTavilySearchDepth:
"""Tests for Tavily search depth configuration."""
- @pytest.fixture(autouse=True)
- def mock_get_setting(self, monkeypatch):
- """Mock get_setting_from_snapshot."""
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- lambda *args, **kwargs: None,
- )
-
def test_search_depth_default(self):
"""Test that search_depth defaults to basic."""
from local_deep_research.web_search_engines.engines.search_engine_tavily import (
diff --git a/tests/web_search_engines/engines/test_search_engine_brave.py b/tests/web_search_engines/engines/test_search_engine_brave.py
index 91b902e7f3..d3fd9de662 100644
--- a/tests/web_search_engines/engines/test_search_engine_brave.py
+++ b/tests/web_search_engines/engines/test_search_engine_brave.py
@@ -146,14 +146,10 @@ class TestBraveSearchEngineInit:
BraveSearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=None,
+ with pytest.raises(
+ ValueError, match="No valid API key found for Brave Search"
):
- with pytest.raises(ValueError) as exc_info:
- BraveSearchEngine()
-
- assert "Brave API key not found" in str(exc_info.value)
+ BraveSearchEngine()
def test_init_with_api_key_from_settings(self):
"""Initialize with API key from settings snapshot."""
@@ -162,17 +158,17 @@ class TestBraveSearchEngineInit:
)
with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value="settings-api-key",
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.search_engine_brave.BraveSearch"
- ) as mock_brave:
- mock_brave.from_api_key.return_value = Mock()
- BraveSearchEngine()
+ "local_deep_research.web_search_engines.engines.search_engine_brave.BraveSearch"
+ ) as mock_brave:
+ mock_brave.from_api_key.return_value = Mock()
+ BraveSearchEngine(
+ settings_snapshot={
+ "search.engine.web.brave.api_key": "settings-api-key"
+ }
+ )
- call_kwargs = mock_brave.from_api_key.call_args[1]
- assert call_kwargs["api_key"] == "settings-api-key"
+ call_kwargs = mock_brave.from_api_key.call_args[1]
+ assert call_kwargs["api_key"] == "settings-api-key"
def test_init_with_llm(self):
"""Initialize with LLM."""
@@ -546,44 +542,6 @@ class TestGetFullContent:
assert len(results) == 1
assert results[0]["title"] == "Result"
- def test_get_full_content_snippets_only_mode(self):
- """Get full content in snippets only mode."""
- from local_deep_research.web_search_engines.engines.search_engine_brave import (
- BraveSearchEngine,
- )
- from local_deep_research.web_search_engines.engines import (
- search_engine_brave,
- )
-
- with patch(
- "local_deep_research.web_search_engines.engines.search_engine_brave.BraveSearch"
- ) as mock_brave:
- mock_brave.from_api_key.return_value = Mock()
- engine = BraveSearchEngine(
- api_key="test-key", include_full_content=False
- )
-
- # Mock SEARCH_SNIPPETS_ONLY
- with patch.object(
- search_engine_brave.search_config,
- "SEARCH_SNIPPETS_ONLY",
- True,
- create=True,
- ):
- items = [
- {
- "title": "Result",
- "_full_result": {
- "title": "Result",
- "snippet": "Full snippet",
- },
- }
- ]
-
- results = engine._get_full_content(items)
-
- assert len(results) == 1
-
class TestRun:
"""Tests for run method."""
diff --git a/tests/web_search_engines/engines/test_search_engine_guardian.py b/tests/web_search_engines/engines/test_search_engine_guardian.py
index aa651ce643..d2e5988c6e 100644
--- a/tests/web_search_engines/engines/test_search_engine_guardian.py
+++ b/tests/web_search_engines/engines/test_search_engine_guardian.py
@@ -97,14 +97,10 @@ class TestGuardianSearchEngineInit:
GuardianSearchEngine,
)
- with patch(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- return_value=None,
+ with pytest.raises(
+ ValueError, match="No valid API key found for Guardian"
):
- with pytest.raises(ValueError) as exc_info:
- GuardianSearchEngine()
-
- assert "Guardian API key not found" in str(exc_info.value)
+ GuardianSearchEngine()
def test_init_with_api_key_from_settings(self):
"""Initialize with API key from settings."""
@@ -112,13 +108,13 @@ class TestGuardianSearchEngineInit:
GuardianSearchEngine,
)
- with patch(
- "local_deep_research.web_search_engines.engines.search_engine_guardian.get_setting_from_snapshot",
- return_value="settings-api-key",
- ):
- engine = GuardianSearchEngine()
+ engine = GuardianSearchEngine(
+ settings_snapshot={
+ "search.engine.web.guardian.api_key": "settings-api-key"
+ }
+ )
- assert engine.api_key == "settings-api-key"
+ assert engine.api_key == "settings-api-key"
def test_init_with_llm(self):
"""Initialize with LLM."""
@@ -318,6 +314,42 @@ class TestGetAllData:
assert articles == []
+ def test_get_all_data_rate_limit_error(self):
+ """Get all data raises RateLimitError for rate limit exceptions."""
+ from local_deep_research.web_search_engines.engines.search_engine_guardian import (
+ GuardianSearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ side_effect=Exception("429 Too Many Requests: rate limit exceeded"),
+ ):
+ engine = GuardianSearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError):
+ engine._get_all_data("test query")
+
+ def test_get_all_data_rate_limit_error_reraise(self):
+ """Get all data re-raises RateLimitError directly."""
+ from local_deep_research.web_search_engines.engines.search_engine_guardian import (
+ GuardianSearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_guardian.safe_get",
+ side_effect=RateLimitError("Rate limit hit"),
+ ):
+ engine = GuardianSearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError, match="Rate limit hit"):
+ engine._get_all_data("test query")
+
class TestGetPreviews:
"""Tests for _get_previews method."""
diff --git a/tests/web_search_engines/engines/test_search_engine_scaleserp.py b/tests/web_search_engines/engines/test_search_engine_scaleserp.py
index 559454b1e2..6e5385bf59 100644
--- a/tests/web_search_engines/engines/test_search_engine_scaleserp.py
+++ b/tests/web_search_engines/engines/test_search_engine_scaleserp.py
@@ -103,14 +103,10 @@ class TestScaleSerpSearchEngineInit:
ScaleSerpSearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=None,
+ with pytest.raises(
+ ValueError, match="No valid API key found for ScaleSerp"
):
- with pytest.raises(ValueError) as exc_info:
- ScaleSerpSearchEngine()
-
- assert "ScaleSerp API key not found" in str(exc_info.value)
+ ScaleSerpSearchEngine()
def test_init_with_api_key_from_settings(self):
"""Initialize with API key from settings."""
@@ -118,13 +114,13 @@ class TestScaleSerpSearchEngineInit:
ScaleSerpSearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value="settings-api-key",
- ):
- engine = ScaleSerpSearchEngine()
+ engine = ScaleSerpSearchEngine(
+ settings_snapshot={
+ "search.engine.web.scaleserp.api_key": "settings-api-key"
+ }
+ )
- assert engine.api_key == "settings-api-key"
+ assert engine.api_key == "settings-api-key"
def test_init_with_llm(self):
"""Initialize with LLM."""
@@ -376,6 +372,61 @@ class TestGetFullContent:
assert "knowledge_graph" in results[0]
assert results[0]["knowledge_graph"]["title"] == "Test Entity"
+ def test_get_full_content_extracts_full_result_with_knowledge_graph(self):
+ """Get full content extracts _full_result via super() and adds knowledge graph."""
+ from local_deep_research.web_search_engines.engines.search_engine_scaleserp import (
+ ScaleSerpSearchEngine,
+ )
+
+ engine = ScaleSerpSearchEngine(api_key="test-key")
+ engine._knowledge_graph = {
+ "title": "Test Entity",
+ "type": "Organization",
+ }
+
+ items = [
+ {
+ "title": "Result",
+ "link": "https://example.com",
+ "_full_result": {
+ "title": "Result",
+ "link": "https://example.com",
+ "snippet": "Full snippet",
+ "position": 1,
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ # Verify _full_result extraction from base class
+ assert results[0]["snippet"] == "Full snippet"
+ assert results[0]["position"] == 1
+ assert "_full_result" not in results[0]
+ # Verify knowledge graph added by override
+ assert results[0]["knowledge_graph"]["title"] == "Test Entity"
+ assert results[0]["knowledge_graph"]["type"] == "Organization"
+
+ def test_get_full_content_no_knowledge_graph_on_second_result(self):
+ """Get full content only adds knowledge graph to first result."""
+ from local_deep_research.web_search_engines.engines.search_engine_scaleserp import (
+ ScaleSerpSearchEngine,
+ )
+
+ engine = ScaleSerpSearchEngine(api_key="test-key")
+ engine._knowledge_graph = {"title": "Test Entity"}
+
+ items = [
+ {"title": "Result 1", "link": "https://example1.com"},
+ {"title": "Result 2", "link": "https://example2.com"},
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert "knowledge_graph" in results[0]
+ assert "knowledge_graph" not in results[1]
+
class TestRun:
"""Tests for run method."""
diff --git a/tests/web_search_engines/engines/test_search_engine_serpapi.py b/tests/web_search_engines/engines/test_search_engine_serpapi.py
index d36e30c863..83f630d462 100644
--- a/tests/web_search_engines/engines/test_search_engine_serpapi.py
+++ b/tests/web_search_engines/engines/test_search_engine_serpapi.py
@@ -106,14 +106,10 @@ class TestSerpAPISearchEngineInit:
SerpAPISearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=None,
+ with pytest.raises(
+ ValueError, match="No valid API key found for SerpAPI"
):
- with pytest.raises(ValueError) as exc_info:
- SerpAPISearchEngine()
-
- assert "SerpAPI key not found" in str(exc_info.value)
+ SerpAPISearchEngine()
def test_init_with_api_key_from_settings(self):
"""Initialize with API key from settings."""
@@ -122,16 +118,16 @@ class TestSerpAPISearchEngineInit:
)
with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value="settings-api-key",
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.search_engine_serpapi.SerpAPIWrapper"
- ) as mock_wrapper:
- SerpAPISearchEngine()
+ "local_deep_research.web_search_engines.engines.search_engine_serpapi.SerpAPIWrapper"
+ ) as mock_wrapper:
+ SerpAPISearchEngine(
+ settings_snapshot={
+ "search.engine.web.serpapi.api_key": "settings-api-key"
+ }
+ )
- call_kwargs = mock_wrapper.call_args[1]
- assert call_kwargs["serpapi_api_key"] == "settings-api-key"
+ call_kwargs = mock_wrapper.call_args[1]
+ assert call_kwargs["serpapi_api_key"] == "settings-api-key"
def test_init_with_llm(self):
"""Initialize with LLM."""
@@ -246,6 +242,50 @@ class TestGetPreviews:
assert previews == []
+ def test_get_previews_rate_limit_error(self):
+ """Get previews raises RateLimitError for rate limit exceptions."""
+ from local_deep_research.web_search_engines.engines.search_engine_serpapi import (
+ SerpAPISearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ mock_engine = MagicMock()
+ mock_engine.results.side_effect = Exception(
+ "429 Too Many Requests: rate limit exceeded"
+ )
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_serpapi.SerpAPIWrapper",
+ return_value=mock_engine,
+ ):
+ engine = SerpAPISearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError):
+ engine._get_previews("test query")
+
+ def test_get_previews_rate_limit_error_reraise(self):
+ """Get previews re-raises RateLimitError directly."""
+ from local_deep_research.web_search_engines.engines.search_engine_serpapi import (
+ SerpAPISearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+
+ mock_engine = MagicMock()
+ mock_engine.results.side_effect = RateLimitError("Rate limit hit")
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_serpapi.SerpAPIWrapper",
+ return_value=mock_engine,
+ ):
+ engine = SerpAPISearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError, match="Rate limit hit"):
+ engine._get_previews("test query")
+
class TestGetFullContent:
"""Tests for _get_full_content method."""
diff --git a/tests/web_search_engines/engines/test_search_engine_serper.py b/tests/web_search_engines/engines/test_search_engine_serper.py
index f8444e5651..6361bab2f9 100644
--- a/tests/web_search_engines/engines/test_search_engine_serper.py
+++ b/tests/web_search_engines/engines/test_search_engine_serper.py
@@ -78,14 +78,10 @@ class TestSerperSearchEngineInit:
SerperSearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=None,
+ with pytest.raises(
+ ValueError, match="No valid API key found for Serper"
):
- with pytest.raises(ValueError) as exc_info:
- SerperSearchEngine()
-
- assert "Serper API key not found" in str(exc_info.value)
+ SerperSearchEngine()
def test_init_with_api_key_from_settings(self):
"""Initialize with API key from settings."""
@@ -93,13 +89,13 @@ class TestSerperSearchEngineInit:
SerperSearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value="settings-api-key",
- ):
- engine = SerperSearchEngine()
+ engine = SerperSearchEngine(
+ settings_snapshot={
+ "search.engine.web.serper.api_key": "settings-api-key"
+ }
+ )
- assert engine.api_key == "settings-api-key"
+ assert engine.api_key == "settings-api-key"
def test_init_with_llm(self):
"""Initialize with LLM."""
@@ -327,6 +323,61 @@ class TestGetFullContent:
assert "knowledge_graph" in results[0]
assert results[0]["knowledge_graph"]["title"] == "Test Entity"
+ def test_get_full_content_extracts_full_result_with_knowledge_graph(self):
+ """Get full content extracts _full_result via super() and adds knowledge graph."""
+ from local_deep_research.web_search_engines.engines.search_engine_serper import (
+ SerperSearchEngine,
+ )
+
+ engine = SerperSearchEngine(api_key="test-key")
+ engine._knowledge_graph = {
+ "title": "Test Entity",
+ "type": "Organization",
+ }
+
+ items = [
+ {
+ "title": "Result",
+ "link": "https://example.com",
+ "_full_result": {
+ "title": "Result",
+ "link": "https://example.com",
+ "snippet": "Full snippet",
+ "position": 1,
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ # Verify _full_result extraction from base class
+ assert results[0]["snippet"] == "Full snippet"
+ assert results[0]["position"] == 1
+ assert "_full_result" not in results[0]
+ # Verify knowledge graph added by override
+ assert results[0]["knowledge_graph"]["title"] == "Test Entity"
+ assert results[0]["knowledge_graph"]["type"] == "Organization"
+
+ def test_get_full_content_no_knowledge_graph_on_second_result(self):
+ """Get full content only adds knowledge graph to first result."""
+ from local_deep_research.web_search_engines.engines.search_engine_serper import (
+ SerperSearchEngine,
+ )
+
+ engine = SerperSearchEngine(api_key="test-key")
+ engine._knowledge_graph = {"title": "Test Entity"}
+
+ items = [
+ {"title": "Result 1", "link": "https://example1.com"},
+ {"title": "Result 2", "link": "https://example2.com"},
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert "knowledge_graph" in results[0]
+ assert "knowledge_graph" not in results[1]
+
class TestRun:
"""Tests for run method."""
diff --git a/tests/web_search_engines/engines/test_search_engine_tavily.py b/tests/web_search_engines/engines/test_search_engine_tavily.py
index 4786102f64..d6ba7a65db 100644
--- a/tests/web_search_engines/engines/test_search_engine_tavily.py
+++ b/tests/web_search_engines/engines/test_search_engine_tavily.py
@@ -71,14 +71,10 @@ class TestTavilySearchEngineInit:
TavilySearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value=None,
+ with pytest.raises(
+ ValueError, match="No valid API key found for Tavily"
):
- with pytest.raises(ValueError) as exc_info:
- TavilySearchEngine()
-
- assert "Tavily API key not found" in str(exc_info.value)
+ TavilySearchEngine()
def test_init_with_api_key_from_settings(self):
"""Initialize with API key from settings snapshot."""
@@ -86,13 +82,13 @@ class TestTavilySearchEngineInit:
TavilySearchEngine,
)
- with patch(
- "local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value="settings-api-key",
- ):
- engine = TavilySearchEngine()
+ engine = TavilySearchEngine(
+ settings_snapshot={
+ "search.engine.web.tavily.api_key": "settings-api-key"
+ }
+ )
- assert engine.api_key == "settings-api-key"
+ assert engine.api_key == "settings-api-key"
def test_init_with_llm(self):
"""Initialize with LLM."""
@@ -242,6 +238,27 @@ class TestGetPreviews:
assert previews == []
+ def test_get_previews_request_exception_with_rate_limit(self):
+ """Get previews raises RateLimitError when RequestException contains rate limit message."""
+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (
+ TavilySearchEngine,
+ )
+ from local_deep_research.web_search_engines.rate_limiting import (
+ RateLimitError,
+ )
+ import requests
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_tavily.safe_post",
+ side_effect=requests.exceptions.RequestException(
+ "rate limit exceeded"
+ ),
+ ):
+ engine = TavilySearchEngine(api_key="test-key")
+
+ with pytest.raises(RateLimitError):
+ engine._get_previews("test query")
+
def test_get_previews_unexpected_error(self):
"""Get previews handles unexpected errors."""
from local_deep_research.web_search_engines.engines.search_engine_tavily import (
@@ -310,6 +327,63 @@ class TestGetFullContent:
assert len(results) == 1
assert results[0]["title"] == "Result"
+ def test_get_full_content_uses_raw_content_when_enabled(self):
+ """Get full content maps raw_content to content when include_full_content=True."""
+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (
+ TavilySearchEngine,
+ )
+
+ engine = TavilySearchEngine(
+ api_key="test-key", include_full_content=True
+ )
+
+ items = [
+ {
+ "title": "Result",
+ "link": "https://example.com",
+ "_full_result": {
+ "title": "Result",
+ "url": "https://example.com",
+ "content": "Short snippet",
+ "raw_content": "Full raw content from Tavily API",
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ assert results[0]["content"] == "Full raw content from Tavily API"
+
+ def test_get_full_content_ignores_raw_content_when_disabled(self):
+ """Get full content does NOT map raw_content when include_full_content=False."""
+ from local_deep_research.web_search_engines.engines.search_engine_tavily import (
+ TavilySearchEngine,
+ )
+
+ engine = TavilySearchEngine(
+ api_key="test-key", include_full_content=False
+ )
+
+ items = [
+ {
+ "title": "Result",
+ "link": "https://example.com",
+ "_full_result": {
+ "title": "Result",
+ "url": "https://example.com",
+ "content": "Short snippet",
+ "raw_content": "Full raw content from Tavily API",
+ },
+ }
+ ]
+
+ results = engine._get_full_content(items)
+
+ assert len(results) == 1
+ # raw_content should be in the result (from _full_result extraction) but NOT mapped to content
+ assert results[0]["content"] == "Short snippet"
+
class TestRun:
"""Tests for run method."""