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 ScaleSerp search engine integration with caching

LearningCircuit1abeef65715d
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 2fd3102ce7..80e6955c67 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1012,6 +1012,10 @@
"label": "SerpAPI (Google)",
"value": "serpapi"
},
+ {
+ "label": "ScaleSerp (Google + Caching)",
+ "value": "scaleserp"
+ },
{
"label": "SearXNG (Self-hosted)",
"value": "searxng"
diff --git a/src/local_deep_research/defaults/settings/search_engines/scaleserp.json b/src/local_deep_research/defaults/settings/search_engines/scaleserp.json
new file mode 100644
index 0000000000..f79d79c772
--- /dev/null
+++ b/src/local_deep_research/defaults/settings/search_engines/scaleserp.json
@@ -0,0 +1,261 @@
+{
+ "search.engine.web.scaleserp.display_name": {
+ "category": "scaleserp",
+ "description": "Display name to use in the U.I. for this search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Display Name",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "ScaleSerp",
+ "visible": false
+ },
+ "search.engine.web.scaleserp.description": {
+ "category": "scaleserp",
+ "description": "Human-readable description of the search engine.",
+ "editable": false,
+ "max_value": null,
+ "min_value": null,
+ "name": "Description",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "Cost-effective Google Search API with 1-hour free caching that can reduce costs by 40-70% for repeated searches.",
+ "visible": false
+ },
+ "search.engine.web.scaleserp.api_key": {
+ "category": "scaleserp",
+ "description": "The ScaleSerp API key to use. Get yours at https://scaleserp.com",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Api Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
+ "search.engine.web.scaleserp.class_name": {
+ "category": "scaleserp",
+ "description": "Class name for the ScaleSerp search engine",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Class Name",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "ScaleSerpSearchEngine",
+ "visible": true
+ },
+ "search.engine.web.scaleserp.module_path": {
+ "category": "scaleserp",
+ "description": "Module path for the ScaleSerp search engine",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Module Path",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "local_deep_research.web_search_engines.engines.search_engine_scaleserp",
+ "visible": true
+ },
+ "search.engine.web.scaleserp.default_params.location": {
+ "category": "scaleserp",
+ "description": "Location for localized results (e.g., 'United States', 'London,England,United Kingdom')",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Location",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "United States",
+ "visible": true
+ },
+ "search.engine.web.scaleserp.default_params.language": {
+ "category": "scaleserp",
+ "description": "Language code for search results (e.g., 'en', 'es', 'fr')",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Language",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "text",
+ "value": "en",
+ "visible": true
+ },
+ "search.engine.web.scaleserp.default_params.device": {
+ "category": "scaleserp",
+ "description": "Device type for search results",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Device",
+ "options": [
+ {
+ "label": "Desktop",
+ "value": "desktop"
+ },
+ {
+ "label": "Mobile",
+ "value": "mobile"
+ }
+ ],
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "dropdown",
+ "value": "desktop",
+ "visible": true
+ },
+ "search.engine.web.scaleserp.default_params.safe_search": {
+ "category": "scaleserp",
+ "description": "Enable or disable safe search filtering",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Safe Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.scaleserp.default_params.enable_cache": {
+ "category": "scaleserp",
+ "description": "Enable 1-hour caching to save API credits (cached searches are FREE within 1 hour)",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Enable Caching",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
+ },
+ "search.engine.web.scaleserp.default_params.include_full_content": {
+ "category": "scaleserp",
+ "description": "Include full webpage content in results (may slow down search)",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Include Full Content",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "search.engine.web.scaleserp.reliability": {
+ "category": "scaleserp",
+ "description": "Reliability of the ScaleSerp search engine",
+ "editable": true,
+ "max_value": 1.0,
+ "min_value": 0.0,
+ "name": "Reliability",
+ "options": null,
+ "step": 0.05,
+ "type": "SEARCH",
+ "ui_element": "range",
+ "value": 0.95,
+ "visible": true
+ },
+ "search.engine.web.scaleserp.requires_api_key": {
+ "category": "scaleserp",
+ "description": "Whether this search engine requires an API key",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires Api Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": false
+ },
+ "search.engine.web.scaleserp.requires_llm": {
+ "category": "scaleserp",
+ "description": "Whether this search engine requires an LLM for relevance filtering",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Requires LLM",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": false
+ },
+ "search.engine.web.scaleserp.supports_full_search": {
+ "category": "scaleserp",
+ "description": "Whether this search engine supports full document search",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Supports Full Search",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": false
+ },
+ "search.engine.web.scaleserp.strengths": {
+ "category": "scaleserp",
+ "description": "Strengths of this search engine",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Strengths",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "1-hour free caching can reduce costs by 40-70%",
+ "Best pricing at scale ($0.29/1k at 5M tier)",
+ "125 free searches per month",
+ "High-quality Google search results",
+ "Real-time results with knowledge graph",
+ "Cached searches don't count against quota",
+ "Rich snippets and related questions"
+ ],
+ "visible": false
+ },
+ "search.engine.web.scaleserp.weaknesses": {
+ "category": "scaleserp",
+ "description": "Weaknesses of this search engine",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Weaknesses",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "json",
+ "value": [
+ "Requires API key with usage limits",
+ "Not specialized for academic content",
+ "Cache only lasts 1 hour"
+ ],
+ "visible": false
+ }
+}
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
new file mode 100644
index 0000000000..f4425707d5
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_scaleserp.py
@@ -0,0 +1,359 @@
+from loguru import logger
+from typing import Any, Dict, List, Optional
+import requests
+from urllib.parse import urlparse
+
+from langchain_core.language_models import BaseLLM
+
+from ..search_engine_base import BaseSearchEngine
+from ..rate_limiting import RateLimitError
+
+
+class ScaleSerpSearchEngine(BaseSearchEngine):
+ """Google search engine implementation using ScaleSerp API with caching support"""
+
+ # Mark as public search engine
+ is_public = True
+ # Mark as generic search engine (general web search via Google)
+ is_generic = True
+
+ def __init__(
+ self,
+ max_results: int = 10,
+ location: str = "United States",
+ language: str = "en",
+ device: str = "desktop",
+ safe_search: bool = True,
+ api_key: Optional[str] = None,
+ llm: Optional[BaseLLM] = None,
+ include_full_content: bool = False,
+ max_filtered_results: Optional[int] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+ enable_cache: bool = True,
+ **kwargs,
+ ):
+ """
+ Initialize the ScaleSerp search engine.
+
+ Args:
+ max_results: Maximum number of search results (default 10, max 100)
+ location: Location for localized results (e.g., 'United States', 'London,England,United Kingdom')
+ language: Language code for results (e.g., 'en', 'es', 'fr')
+ device: Device type for search ('desktop' or 'mobile')
+ safe_search: Whether to enable safe search
+ api_key: ScaleSerp API key (can also be set in settings)
+ llm: Language model for relevance filtering
+ include_full_content: Whether to include full webpage content in results
+ max_filtered_results: Maximum number of results to keep after filtering
+ settings_snapshot: Settings snapshot for thread context
+ enable_cache: Whether to use ScaleSerp's 1-hour caching (saves costs for repeated searches)
+ **kwargs: Additional parameters (ignored but accepted for compatibility)
+ """
+ # Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_results
+ super().__init__(
+ llm=llm,
+ max_filtered_results=max_filtered_results,
+ max_results=max_results,
+ )
+ self.include_full_content = include_full_content
+ self.location = location
+ self.language = language
+ self.device = device
+ 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."
+ )
+
+ self.api_key = scaleserp_api_key
+ self.base_url = "https://api.scaleserp.com/search"
+ self.engine_type = "scaleserp" # Required for rate limiting
+
+ # If full content is requested, initialize FullSearchResults
+ if include_full_content:
+ # Import FullSearchResults only if needed
+ try:
+ from .full_search import FullSearchResults
+
+ self.full_search = FullSearchResults(
+ llm=llm,
+ web_search=None, # We'll handle the search ourselves
+ language=language,
+ max_results=max_results,
+ region=location,
+ time=None,
+ safesearch="Moderate" if safe_search else "Off",
+ )
+ except ImportError:
+ logger.warning(
+ "Warning: FullSearchResults not available. Full content retrieval disabled."
+ )
+ self.include_full_content = False
+
+ def _get_previews(self, query: str) -> List[Dict[str, Any]]:
+ """
+ Get preview information from ScaleSerp API.
+
+ Args:
+ query: The search query
+
+ Returns:
+ List of preview dictionaries
+ """
+ logger.info("Getting search results from ScaleSerp API")
+
+ try:
+ # Build request parameters
+ params = {
+ "api_key": self.api_key,
+ "q": query,
+ "num": min(self.max_results, 100), # ScaleSerp max is 100
+ "location": self.location,
+ "hl": self.language,
+ "device": self.device,
+ }
+
+ # Add safe search if enabled
+ if self.safe_search:
+ params["safe"] = "on"
+
+ # Add caching parameter if enabled - this is ScaleSerp's key feature!
+ # Cached results don't count against quota and are free for 1 hour
+ if self.enable_cache:
+ params["output"] = "json" # Ensure JSON output
+ # ScaleSerp automatically caches for 1 hour, no special param needed
+ logger.info(
+ "Using ScaleSerp caching - repeated searches within 1 hour are free"
+ )
+
+ # Apply rate limiting before request
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+
+ # Make API request
+ response = requests.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}"
+ )
+
+ response.raise_for_status()
+
+ data = response.json()
+
+ # Extract organic results
+ organic_results = data.get("organic_results", [])
+
+ # Format results as previews
+ previews = []
+ for idx, result in enumerate(organic_results):
+ # Extract display link safely using urlparse
+ display_link = ""
+ link = result.get("link", "")
+ if link:
+ try:
+ parsed_url = urlparse(link)
+ display_link = parsed_url.netloc or parsed_url.path
+ except Exception:
+ display_link = link[:50] if link else ""
+
+ preview = {
+ "id": idx,
+ "title": result.get("title", ""),
+ "link": link,
+ "snippet": result.get("snippet", ""),
+ "displayed_link": display_link,
+ "position": result.get("position", idx + 1),
+ }
+
+ # Store full ScaleSerp result for later
+ preview["_full_result"] = result
+
+ # Include rich snippets if available
+ if "rich_snippet" in result:
+ preview["rich_snippet"] = result["rich_snippet"]
+
+ # Include date if available
+ if "date" in result:
+ preview["date"] = result["date"]
+
+ # Include sitelinks if available
+ if "sitelinks" in result:
+ preview["sitelinks"] = result["sitelinks"]
+
+ previews.append(preview)
+
+ # Store the previews for potential full content retrieval
+ self._search_results = previews
+
+ # Store knowledge graph if available
+ if "knowledge_graph" in data:
+ self._knowledge_graph = data["knowledge_graph"]
+ logger.info(
+ f"Found knowledge graph for query: {data['knowledge_graph'].get('title', 'Unknown')}"
+ )
+
+ # Store related searches
+ if "related_searches" in data:
+ self._related_searches = data["related_searches"]
+
+ # Store related questions (People Also Ask)
+ if "related_questions" in data:
+ self._related_questions = data["related_questions"]
+
+ # Check if result was served from cache
+ if "request_info" in data and data["request_info"].get("cached"):
+ logger.info(
+ "Result served from ScaleSerp cache - no API credit used!"
+ )
+
+ return previews
+
+ 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 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}")
+
+ return []
+ except Exception:
+ logger.exception("Unexpected error getting ScaleSerp API results")
+ 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
+ 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 hasattr(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)
+
+ # Include knowledge graph and other metadata if this is the first call
+ if results and hasattr(self, "_knowledge_graph"):
+ results[0]["knowledge_graph"] = self._knowledge_graph
+
+ return results
+
+ def run(
+ self, query: str, research_context: Dict[str, Any] | None = None
+ ) -> List[Dict[str, Any]]:
+ """
+ Execute a search using ScaleSerp API with the two-phase approach.
+
+ Args:
+ query: The search query
+ research_context: Context from previous research to use.
+
+ Returns:
+ List of search results
+ """
+ logger.info("---Execute a search using ScaleSerp API (Google)---")
+
+ # Use the implementation from the parent class which handles all phases
+ results = super().run(query, research_context=research_context)
+
+ # Clean up
+ if hasattr(self, "_search_results"):
+ del self._search_results
+ if hasattr(self, "_knowledge_graph"):
+ del self._knowledge_graph
+ if hasattr(self, "_related_searches"):
+ del self._related_searches
+ if hasattr(self, "_related_questions"):
+ del self._related_questions
+
+ return results