~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(search): add Serply search engine (#5834)
Serply8d736fffc610
diff --git a/changelog.d/5834.feature.md b/changelog.d/5834.feature.mdnew file mode 100644index 0000000000..d3ce5b0cb0--- /dev/null+++ b/changelog.d/5834.feature.md@@ -0,0 +1 @@+**Serply search engine** - Added [Serply](https://serply.io) as an optional hosted Google SERP engine alongside SerpAPI, Serper and ScaleSERP. A `search_type` setting picks Google web search (default), Google News or Google Scholar; Scholar mode is flagged scientific so its results join the academic pipeline next to OpenAlex, Semantic Scholar, arXiv and PubMed. Configure your API key under Settings > Search > Serply (`search.engine.web.serply.api_key`) or the `LDR_SEARCH_ENGINE_WEB_SERPLY_API_KEY` environment variable.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 6df1f78350..36809f1d78 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -503,6 +503,18 @@ They are not available in the Web UI because they are needed to start the applic| `search.engine.web.serper.strengths` | `LDR_SEARCH_ENGINE_WEB_SERPER_STRENGTHS` | ``["Lightning-fast response times (1-2 seconds)", "Very affordable pricing", "High-quality Google search results", "Real-time results", "Knowledge graph and related searches", "People Also Ask data", "Simple pay-per-use pricing"]`` | Strengths of this search engine | SEARCH || `search.engine.web.serper.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_SERPER_SUPPORTS_FULL_SEARCH` | `true` | Whether this search engine supports full document search | SEARCH || `search.engine.web.serper.weaknesses` | `LDR_SEARCH_ENGINE_WEB_SERPER_WEAKNESSES` | ``["Requires API key with usage limits", "Not specialized for academic content"]`` | Weaknesses of this search engine | SEARCH |+| `search.engine.web.serply.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_SERPLY_AGENT_ENABLED` | `true` | Include Serply as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool; this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections. | SEARCH |+| `search.engine.web.serply.api_key` | `LDR_SEARCH_ENGINE_WEB_SERPLY_API_KEY` | `` | The Serply API key to use. Get yours at https://serply.io | SEARCH |+| `search.engine.web.serply.default_params.search_type` | `LDR_SEARCH_ENGINE_WEB_SERPLY_DEFAULT_PARAMS_SEARCH_TYPE` | `web` | Which Google index to search: 'web' for general web search, 'news' for Google News, 'scholar' for Google Scholar. See https://serply.io/docs | SEARCH |+| `search.engine.web.serply.description` | `LDR_SEARCH_ENGINE_WEB_SERPLY_DESCRIPTION` | `Google search results via the Serply API, with Google News and Google Scholar as alternative search types.` | Human-readable description of the search engine. | SEARCH |+| `search.engine.web.serply.display_name` | `LDR_SEARCH_ENGINE_WEB_SERPLY_DISPLAY_NAME` | `Serply` | Display name to use in the U.I. for this search engine. | SEARCH |+| `search.engine.web.serply.reliability` | `LDR_SEARCH_ENGINE_WEB_SERPLY_RELIABILITY` | `0.85` | Reliability of the Serply search engine | SEARCH |+| `search.engine.web.serply.requires_api_key` | `LDR_SEARCH_ENGINE_WEB_SERPLY_REQUIRES_API_KEY` | `true` | Whether this search engine requires an API key | SEARCH |+| `search.engine.web.serply.requires_llm` | `LDR_SEARCH_ENGINE_WEB_SERPLY_REQUIRES_LLM` | `false` | Whether this search engine requires an LLM for relevance filtering | SEARCH |+| `search.engine.web.serply.strengths` | `LDR_SEARCH_ENGINE_WEB_SERPLY_STRENGTHS` | ``["Google web search results", "Google News and Google Scholar available as search types", "Scholar results include author, venue and citation metadata"]`` | Strengths of this search engine | SEARCH |+| `search.engine.web.serply.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_SERPLY_SUPPORTS_FULL_SEARCH` | `false` | Whether this search engine supports full document search | SEARCH |+| `search.engine.web.serply.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_SERPLY_USE_IN_AUTO_SEARCH` | `false` | Whether to include this engine in auto/meta search selection | SEARCH |+| `search.engine.web.serply.weaknesses` | `LDR_SEARCH_ENGINE_WEB_SERPLY_WEAKNESSES` | ``["Requires API key with usage limits", "One search type per configured engine"]`` | Weaknesses of this search engine | SEARCH || `search.engine.web.sofya.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_SOFYA_AGENT_ENABLED` | `true` | Include Sofya as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections. | SEARCH || `search.engine.web.sofya.api_key` | `LDR_SEARCH_ENGINE_WEB_SOFYA_API_KEY` | `` | The Sofya API key to use. Get yours at https://sofya.co/dashboard (GitHub sign-up grants 1000 free credits/month). | SEARCH || `search.engine.web.sofya.default_params.freshness` | `LDR_SEARCH_ENGINE_WEB_SOFYA_DEFAULT_PARAMS_FRESHNESS` | `null` | Filter results by recency ('day', 'week', 'month', 'year', or null for all time). | SEARCH |diff --git a/src/local_deep_research/defaults/settings/search_engines/serply.json b/src/local_deep_research/defaults/settings/search_engines/serply.jsonnew file mode 100644index 0000000000..8fde6e19a9--- /dev/null+++ b/src/local_deep_research/defaults/settings/search_engines/serply.json@@ -0,0 +1,190 @@+{+ "search.engine.web.serply.display_name": {+ "category": "serply",+ "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": "Serply",+ "visible": false+ },+ "search.engine.web.serply.description": {+ "category": "serply",+ "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": "Google search results via the Serply API, with Google News and Google Scholar as alternative search types.",+ "visible": false+ },+ "search.engine.web.serply.api_key": {+ "category": "serply",+ "description": "The Serply API key to use. Get yours at https://serply.io",+ "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.serply.default_params.search_type": {+ "category": "serply",+ "description": "Which Google index to search: 'web' for general web search, 'news' for Google News, 'scholar' for Google Scholar. See https://serply.io/docs",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Search Type",+ "options": [+ {+ "label": "Web",+ "value": "web"+ },+ {+ "label": "News",+ "value": "news"+ },+ {+ "label": "Scholar",+ "value": "scholar"+ }+ ],+ "step": null,+ "type": "SEARCH",+ "ui_element": "select",+ "value": "web",+ "visible": true+ },+ "search.engine.web.serply.reliability": {+ "category": "serply",+ "description": "Reliability of the Serply 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.85,+ "visible": true+ },+ "search.engine.web.serply.requires_api_key": {+ "category": "serply",+ "description": "Whether this search engine requires an API key",+ "editable": false,+ "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.serply.requires_llm": {+ "category": "serply",+ "description": "Whether this search engine requires an LLM for relevance filtering",+ "editable": false,+ "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.serply.supports_full_search": {+ "category": "serply",+ "description": "Whether this search engine supports full document search",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Supports Full Search",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.serply.strengths": {+ "category": "serply",+ "description": "Strengths of this search engine",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Strengths",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "Google web search results",+ "Google News and Google Scholar available as search types",+ "Scholar results include author, venue and citation metadata"+ ],+ "visible": false+ },+ "search.engine.web.serply.weaknesses": {+ "category": "serply",+ "description": "Weaknesses of this search engine",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Weaknesses",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "Requires API key with usage limits",+ "One search type per configured engine"+ ],+ "visible": false+ },+ "search.engine.web.serply.use_in_auto_search": {+ "category": "serply",+ "description": "Whether to include this engine in auto/meta search selection",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Use In Auto Search",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "search.engine.web.serply.agent_enabled": {+ "category": "serply",+ "description": "Include Serply as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool; this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Available to Research Agent",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ }+}diff --git a/src/local_deep_research/security/module_whitelist.py b/src/local_deep_research/security/module_whitelist.pyindex badf23ed2b..7620168199 100644--- a/src/local_deep_research/security/module_whitelist.py+++ b/src/local_deep_research/security/module_whitelist.py@@ -50,6 +50,7 @@ ALLOWED_MODULE_PATHS: frozenset[str] = frozenset(".engines.search_engine_semantic_scholar",".engines.search_engine_serper",".engines.search_engine_serpapi",+ ".engines.search_engine_serply",".engines.search_engine_sofya",".engines.search_engine_tavily",".engines.search_engine_tinyfish",@@ -100,6 +101,7 @@ ALLOWED_CLASS_NAMES: frozenset[str] = frozenset("SemanticScholarSearchEngine","SerpAPISearchEngine","SerperSearchEngine",+ "SerplySearchEngine","SofyaSearchEngine","StackExchangeSearchEngine","TavilySearchEngine",diff --git a/src/local_deep_research/web_search_engines/engine_registry.py b/src/local_deep_research/web_search_engines/engine_registry.pyindex 645ff3ada2..75e5351d6f 100644--- a/src/local_deep_research/web_search_engines/engine_registry.py+++ b/src/local_deep_research/web_search_engines/engine_registry.py@@ -109,6 +109,10 @@ ENGINE_REGISTRY: Dict[str, EngineEntry] = {module_path=".engines.search_engine_serper",class_name="SerperSearchEngine",),+ "serply": EngineEntry(+ module_path=".engines.search_engine_serply",+ class_name="SerplySearchEngine",+ ),"sofya": EngineEntry(module_path=".engines.search_engine_sofya",class_name="SofyaSearchEngine",diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serply.py b/src/local_deep_research/web_search_engines/engines/search_engine_serply.pynew file mode 100644index 0000000000..936d4192e0--- /dev/null+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serply.py@@ -0,0 +1,192 @@+"""Serply search engine implementation for Local Deep Research.++Serply (https://serply.io) is a hosted Google SERP API. Its ``/v1/search``,+``/v1/news`` and ``/v1/scholar`` endpoints return Google web results, Google+News entries and Google Scholar articles, so one engine covers general web+search plus the two verticals. API reference: https://serply.io/docs.+"""++import html+import re+from typing import Any, Dict, List, Literal, Optional++import requests+from langchain_core.language_models import BaseLLM++from ...constants import USER_AGENT+from ...security.safe_requests import safe_get+from ...security.secure_logging import logger+from ..rate_limiting import RateLimitError+from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity+++class SerplySearchEngine(BaseSearchEngine):+ """Google search engine implementation using the Serply API."""++ # Mark as a public, generic (general web) search engine.+ is_public = True+ egress_sensitivity = Sensitivity.NON_SENSITIVE+ egress_exposure = Exposure.EXPOSING+ is_generic = True++ #: Base URL for the Serply REST API.+ BASE_URL = "https://api.serply.io/v1"+ #: Endpoint path and result list key for each supported search type.+ SEARCH_TYPES = {+ "web": ("search", "results"),+ "news": ("news", "entries"),+ "scholar": ("scholar", "articles"),+ }+ #: Serply returns at most 100 results per request.+ MAX_RESULTS_CAP = 100+ #: HTTP request timeout in seconds.+ REQUEST_TIMEOUT = 30++ def __init__(+ self,+ max_results: int = 10,+ search_type: Literal["web", "news", "scholar"] = "web",+ api_key: Optional[str] = None,+ llm: Optional[BaseLLM] = None,+ max_filtered_results: Optional[int] = None,+ settings_snapshot: Optional[Dict[str, Any]] = None,+ **kwargs,+ ):+ """Initialize the Serply search engine.++ Args:+ max_results: Maximum number of search results to request.+ search_type: ``"web"`` (Google web search), ``"news"`` (Google+ News) or ``"scholar"`` (Google Scholar).+ api_key: Serply API key. May also be supplied via the+ ``search.engine.web.serply.api_key`` setting or the+ ``LDR_SEARCH_ENGINE_WEB_SERPLY_API_KEY`` environment variable.+ llm: Language model for relevance filtering.+ max_filtered_results: Maximum number of results to keep after+ relevance filtering.+ settings_snapshot: Settings snapshot for thread context.+ **kwargs: Remaining ``BaseSearchEngine`` parameters+ (``programmatic_mode``, ``include_full_content``, filters),+ forwarded to ``super().__init__``.+ """+ super().__init__(+ llm=llm,+ max_filtered_results=max_filtered_results,+ max_results=max_results,+ settings_snapshot=settings_snapshot,+ **kwargs,+ )+ if search_type not in self.SEARCH_TYPES:+ logger.warning(+ f"Unknown Serply search_type '{search_type}'; falling back "+ f"to 'web' (valid: {', '.join(self.SEARCH_TYPES)})"+ )+ search_type = "web"+ self.search_type = search_type+ # Scholar results are academic papers, so route them through the+ # scientific pipeline (DOI enrichment, journal reputation filter)+ # instead of treating them as generic web pages. Instance-level so+ # one class can serve all three verticals.+ self.is_scientific = search_type == "scholar"++ # Resolve API key from params, settings snapshot, or env var.+ self.api_key = self._resolve_api_key(+ api_key,+ "search.engine.web.serply.api_key",+ engine_name="Serply",+ settings_snapshot=settings_snapshot,+ )++ def _snippet(self, result: Dict[str, Any]) -> str:+ """Return the preview snippet for one Serply result."""+ if self.search_type == "news":+ # Google News entries carry the summary as an HTML fragment.+ # Unescape entities first so encoded markup (``<b>``)+ # is also removed by the tag strip instead of surviving it.+ text = html.unescape(result.get("summary") or "")+ text = re.sub(r"<[^>]+>", "", text)+ return " ".join(text.split())+ # Web results describe the page; Scholar results describe the+ # authors, venue and year.+ return result.get("description") or ""++ def _get_previews(self, query: str) -> List[Dict[str, Any]]:+ """Get preview information from the Serply API.++ Args:+ query: The search query.++ Returns:+ List of preview dictionaries.+ """+ logger.info("Getting search results from Serply API")++ path, results_key = self.SEARCH_TYPES[self.search_type]++ try:+ params = {+ "q": query,+ "num": min(self.max_results, self.MAX_RESULTS_CAP),+ }++ # Apply rate limiting before the request.+ self._last_wait_time = self.rate_tracker.apply_rate_limit(+ self.engine_type+ )++ response = safe_get(+ f"{self.BASE_URL}/{path}/",+ params=params,+ headers={+ "X-Api-Key": self.api_key,+ "Accept": "application/json",+ # Serply is fronted by Cloudflare, which can reject the+ # default python-requests User-Agent.+ "User-Agent": USER_AGENT,+ },+ timeout=self.REQUEST_TIMEOUT,+ )++ # Detect rate limiting from the status code.+ self._raise_if_rate_limit(response.status_code)+ response.raise_for_status()++ data = response.json()+ # The news endpoint ignores ``num``, so cap client-side too.+ items = (data.get(results_key) or [])[: self.max_results]++ previews = []+ for idx, result in enumerate(items):+ link = result.get("link") or ""+ preview = {+ "id": idx,+ "title": result.get("title", ""),+ "link": link,+ "snippet": self._snippet(result),+ "displayed_link": self._extract_display_link(link),+ "position": idx + 1,+ }+ if result.get("published"):+ preview["date"] = result["published"]+ previews.append(preview)++ self._search_results = previews+ return previews++ except RateLimitError:+ raise # Re-raise rate limit errors+ except requests.exceptions.RequestException as e:+ safe_msg = self._scrub_error(e)+ logger.warning(f"Error getting Serply API results: {safe_msg}")+ status_code = getattr(+ getattr(e, "response", None), "status_code", None+ )+ if status_code is not None:+ self._raise_if_rate_limit(status_code)+ return []+ except Exception as e:+ safe_msg = self._scrub_error(e)+ logger.warning(+ f"Unexpected error getting Serply API results: {safe_msg}"+ )+ return []diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex d924fd7ef2..454314554f 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -6996,6 +6996,194 @@],"visible": false},+ "search.engine.web.serply.agent_enabled": {+ "category": "serply",+ "description": "Include Serply as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool; this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Available to Research Agent",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": true,+ "visible": true+ },+ "search.engine.web.serply.api_key": {+ "category": "serply",+ "description": "The Serply API key to use. Get yours at https://serply.io",+ "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.serply.default_params.search_type": {+ "category": "serply",+ "description": "Which Google index to search: 'web' for general web search, 'news' for Google News, 'scholar' for Google Scholar. See https://serply.io/docs",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Search Type",+ "options": [+ {+ "label": "Web",+ "value": "web"+ },+ {+ "label": "News",+ "value": "news"+ },+ {+ "label": "Scholar",+ "value": "scholar"+ }+ ],+ "step": null,+ "type": "SEARCH",+ "ui_element": "select",+ "value": "web",+ "visible": true+ },+ "search.engine.web.serply.description": {+ "category": "serply",+ "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": "Google search results via the Serply API, with Google News and Google Scholar as alternative search types.",+ "visible": false+ },+ "search.engine.web.serply.display_name": {+ "category": "serply",+ "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": "Serply",+ "visible": false+ },+ "search.engine.web.serply.reliability": {+ "category": "serply",+ "description": "Reliability of the Serply 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.85,+ "visible": true+ },+ "search.engine.web.serply.requires_api_key": {+ "category": "serply",+ "description": "Whether this search engine requires an API key",+ "editable": false,+ "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.serply.requires_llm": {+ "category": "serply",+ "description": "Whether this search engine requires an LLM for relevance filtering",+ "editable": false,+ "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.serply.strengths": {+ "category": "serply",+ "description": "Strengths of this search engine",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Strengths",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "Google web search results",+ "Google News and Google Scholar available as search types",+ "Scholar results include author, venue and citation metadata"+ ],+ "visible": false+ },+ "search.engine.web.serply.supports_full_search": {+ "category": "serply",+ "description": "Whether this search engine supports full document search",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Supports Full Search",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": false+ },+ "search.engine.web.serply.use_in_auto_search": {+ "category": "serply",+ "description": "Whether to include this engine in auto/meta search selection",+ "editable": true,+ "max_value": null,+ "min_value": null,+ "name": "Use In Auto Search",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "checkbox",+ "value": false,+ "visible": true+ },+ "search.engine.web.serply.weaknesses": {+ "category": "serply",+ "description": "Weaknesses of this search engine",+ "editable": false,+ "max_value": null,+ "min_value": null,+ "name": "Weaknesses",+ "options": null,+ "step": null,+ "type": "SEARCH",+ "ui_element": "json",+ "value": [+ "Requires API key with usage limits",+ "One search type per configured engine"+ ],+ "visible": false+ },"search.engine.web.sofya.agent_enabled": {"category": "sofya","description": "Include Sofya as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",diff --git a/tests/web_search_engines/engines/test_search_engine_serply.py b/tests/web_search_engines/engines/test_search_engine_serply.pynew file mode 100644index 0000000000..4333d9862a--- /dev/null+++ b/tests/web_search_engines/engines/test_search_engine_serply.py@@ -0,0 +1,299 @@+"""+Tests for the SerplySearchEngine class.++Tests cover:+- Initialization and configuration+- API key handling+- Request construction per search type+- Preview generation for web, news and scholar results+- Rate limit error handling+- Class attributes+"""++from unittest.mock import Mock, patch++import pytest+import requests++MODULE = "local_deep_research.web_search_engines.engines.search_engine_serply"+++def _make_engine(**kwargs):+ from local_deep_research.web_search_engines.engines.search_engine_serply import (+ SerplySearchEngine,+ )++ kwargs.setdefault("api_key", "test-api-key")+ return SerplySearchEngine(**kwargs)+++def _mock_response(payload):+ response = Mock()+ response.status_code = 200+ response.json.return_value = payload+ response.raise_for_status = Mock()+ return response+++class TestSerplySearchEngineInit:+ """Tests for SerplySearchEngine initialization."""++ def test_init_with_api_key(self):+ """Initialize with API key and defaults."""+ engine = _make_engine()++ assert engine.api_key == "test-api-key"+ assert engine.max_results == 10+ assert engine.search_type == "web"+ assert engine.include_full_content is False++ def test_init_invalid_search_type_falls_back_to_web(self):+ """An unsupported search_type falls back to 'web' and logs a+ warning so a config typo does not silently change verticals."""+ with patch(f"{MODULE}.logger") as mock_logger:+ engine = _make_engine(search_type="images")++ assert engine.search_type == "web"+ mock_logger.warning.assert_called_once()+ assert "images" in mock_logger.warning.call_args[0][0]++ def test_init_valid_search_type_does_not_warn(self):+ """A supported search_type is accepted without a warning."""+ with patch(f"{MODULE}.logger") as mock_logger:+ engine = _make_engine(search_type="scholar")++ assert engine.search_type == "scholar"+ mock_logger.warning.assert_not_called()++ def test_scholar_search_type_is_scientific(self):+ """Scholar mode joins the academic pipeline (DOI enrichment,+ journal reputation) while web and news stay generic."""+ assert _make_engine(search_type="scholar").is_scientific is True+ assert _make_engine(search_type="web").is_scientific is False+ assert _make_engine(search_type="news").is_scientific is False++ def test_base_kwargs_are_forwarded(self):+ """Base-class parameters passed through **kwargs reach+ BaseSearchEngine instead of being dropped."""+ engine = _make_engine(programmatic_mode=True, include_full_content=True)++ assert engine.programmatic_mode is True+ assert engine.include_full_content is True++ def test_init_without_api_key_raises(self):+ """Initialize without API key raises ValueError."""+ from local_deep_research.web_search_engines.engines.search_engine_serply import (+ SerplySearchEngine,+ )++ with pytest.raises(+ ValueError, match="No valid API key found for Serply"+ ):+ SerplySearchEngine()++ def test_init_with_api_key_from_settings(self):+ """Initialize with API key from settings snapshot."""+ from local_deep_research.web_search_engines.engines.search_engine_serply import (+ SerplySearchEngine,+ )++ engine = SerplySearchEngine(+ settings_snapshot={+ "search.engine.web.serply.api_key": "settings-api-key"+ }+ )++ assert engine.api_key == "settings-api-key"+++class TestGetPreviews:+ """Tests for _get_previews across the three search types."""++ def test_web_previews(self):+ """Web results map title/description/link to previews and the+ request carries the API key header and capped num."""+ payload = {+ "results": [+ {+ "title": "Result 1",+ "description": "First description",+ "link": "https://example.com/1",+ "position": "1",+ },+ {+ "title": "Result 2",+ "description": "Second description",+ "link": "https://example.org/2",+ "position": "2",+ },+ ]+ }++ with patch(+ f"{MODULE}.safe_get", return_value=_mock_response(payload)+ ) as mock_get:+ engine = _make_engine(max_results=150)+ previews = engine._get_previews("test query")++ assert len(previews) == 2+ assert previews[0]["title"] == "Result 1"+ assert previews[0]["snippet"] == "First description"+ assert previews[0]["link"] == "https://example.com/1"+ assert previews[0]["displayed_link"] == "example.com"+ assert previews[1]["position"] == 2+ assert "_full_result" not in previews[0]++ call_kwargs = mock_get.call_args[1]+ assert mock_get.call_args[0][0] == "https://api.serply.io/v1/search/"+ assert call_kwargs["params"] == {"q": "test query", "num": 100}+ assert call_kwargs["headers"]["X-Api-Key"] == "test-api-key"+ assert "User-Agent" in call_kwargs["headers"]++ def test_news_previews_strip_html_and_cap_results(self):+ """News entries come from the /news/ endpoint; the HTML summary is+ flattened to text and the list is capped since Serply ignores num."""+ payload = {+ "entries": [+ {+ "title": f"Story {i}",+ "link": f"https://news.example.com/{i}",+ "summary": (+ '<a href="https://x">Story</a> '+ '<font color="#6f6f6f">Some Source</font>'+ ),+ "published": "Wed, 20 May 2026 07:00:00 GMT",+ }+ for i in range(5)+ ]+ }++ with patch(+ f"{MODULE}.safe_get", return_value=_mock_response(payload)+ ) as mock_get:+ engine = _make_engine(search_type="news", max_results=2)+ previews = engine._get_previews("test query")++ assert mock_get.call_args[0][0] == "https://api.serply.io/v1/news/"+ assert len(previews) == 2+ assert previews[0]["snippet"] == "Story Some Source"+ assert previews[0]["date"] == "Wed, 20 May 2026 07:00:00 GMT"++ def test_news_snippet_strips_entity_encoded_markup(self):+ """Entities are decoded before tags are stripped, so encoded markup+ in a summary is removed rather than turned back into live tags."""+ payload = {+ "entries": [+ {+ "title": "Story",+ "link": "https://news.example.com/1",+ "summary": (+ "Plain & simple <img src=x onerror=alert(1)>"+ "<b>bold</b> text"+ ),+ }+ ]+ }++ with patch(f"{MODULE}.safe_get", return_value=_mock_response(payload)):+ engine = _make_engine(search_type="news")+ previews = engine._get_previews("test query")++ assert previews[0]["snippet"] == "Plain & simple bold text"+ assert "<" not in previews[0]["snippet"]++ def test_scholar_previews(self):+ """Scholar articles come from the /scholar/ endpoint and use the+ author/venue description as the snippet."""+ payload = {+ "articles": [+ {+ "title": "A Survey",+ "link": "https://arxiv.org/abs/1234.5678",+ "description": "A Author, B Author - arXiv, 2023",+ "extras": {"citations": {"count": 12}},+ }+ ]+ }++ with patch(+ f"{MODULE}.safe_get", return_value=_mock_response(payload)+ ) as mock_get:+ engine = _make_engine(search_type="scholar")+ previews = engine._get_previews("test query")++ assert mock_get.call_args[0][0] == "https://api.serply.io/v1/scholar/"+ assert previews[0]["title"] == "A Survey"+ assert previews[0]["snippet"] == "A Author, B Author - arXiv, 2023"+ assert "date" not in previews[0]++ def test_empty_results(self):+ """A response without the expected list yields no previews."""+ with patch(+ f"{MODULE}.safe_get", return_value=_mock_response({"results": None})+ ):+ engine = _make_engine()++ assert engine._get_previews("test query") == []++ def test_rate_limit_status_raises(self):+ """A 429 response raises RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ response = _mock_response({})+ response.status_code = 429++ with patch(f"{MODULE}.safe_get", return_value=response):+ engine = _make_engine()++ with pytest.raises(RateLimitError):+ engine._get_previews("test query")++ def test_request_exception_returns_empty(self):+ """A network error is logged and yields no previews."""+ with patch(+ f"{MODULE}.safe_get",+ side_effect=requests.exceptions.RequestException("boom"),+ ):+ engine = _make_engine()++ assert engine._get_previews("test query") == []++ def test_request_exception_with_rate_limit_status(self):+ """A RequestException carrying a 429 response raises RateLimitError."""+ from local_deep_research.web_search_engines.rate_limiting import (+ RateLimitError,+ )++ err = requests.exceptions.RequestException("boom")+ err.response = Mock(status_code=429)++ with patch(f"{MODULE}.safe_get", side_effect=err):+ engine = _make_engine()++ with pytest.raises(RateLimitError):+ engine._get_previews("test query")+++class TestClassAttributes:+ """Tests for class-level attributes."""++ def test_egress_labels(self):+ """Serply is a public, generic engine with NON_SENSITIVE/EXPOSING+ egress labels (enforced by+ test_registered_engines_declare_consistent_labels)."""+ from local_deep_research.web_search_engines.engines.search_engine_serply import (+ SerplySearchEngine,+ )+ from local_deep_research.web_search_engines.search_engine_base import (+ Exposure,+ Sensitivity,+ )++ assert SerplySearchEngine.is_public is True+ assert SerplySearchEngine.is_generic is True+ assert (+ SerplySearchEngine.egress_sensitivity is Sensitivity.NON_SENSITIVE+ )+ assert SerplySearchEngine.egress_exposure is Exposure.EXPOSINGdiff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.pyindex b1670a6959..4cc6afbda9 100644--- a/tests/web_search_engines/test_engine_success_path.py+++ b/tests/web_search_engines/test_engine_success_path.py@@ -140,6 +140,9 @@ from local_deep_research.web_search_engines.engines import (from local_deep_research.web_search_engines.engines import (search_engine_serper as serper_engine,)+from local_deep_research.web_search_engines.engines import (+ search_engine_serply as serply_engine,+)from local_deep_research.web_search_engines.engines import (search_engine_sofya as sofya_engine,)@@ -764,6 +767,34 @@ SERPER_PAYLOAD = {]}+# ``/v1/search/`` returns Google web results under ``results``; each carries+# the page description (not ``snippet``) and a ``published`` date only for+# dated pages.+SERPLY_PAYLOAD = {+ "results": [+ {+ "title": "Transformer architecture - Serply",+ "link": "https://serply-result.example/transformers",+ "description": "Serply's description of the transformer.",+ "realPosition": 1,+ }+ ]+}++# ``/v1/scholar/`` returns Google Scholar articles under ``articles``; the+# description is the author/venue/year line, and the DOI-bearing link is+# what the scientific pipeline's enrichment step keys on.+SERPLY_SCHOLAR_PAYLOAD = {+ "articles": [+ {+ "title": "Attention Is All You Need",+ "link": "https://doi.org/10.48550/arXiv.1706.03762",+ "description": "A Vaswani, N Shazeer - NeurIPS, 2017",+ "extras": {"citations": {"count": 100000}},+ }+ ]+}+SOFYA_PAYLOAD = {"results": [{@@ -1237,6 +1268,37 @@ def _drive_serper(tracker):return engine._get_previews(QUERY)+def _build_serply(tracker, search_type="web"):+ return _wire(+ serply_engine.SerplySearchEngine(+ max_results=3,+ search_type=search_type,+ llm=None,+ api_key=API_KEY,+ settings_snapshot=SNAPSHOT,+ ),+ tracker,+ )+++def _drive_serply(tracker):+ engine = _build_serply(tracker)+ with patch.object(+ serply_engine, "safe_get", const_response(payload=SERPLY_PAYLOAD)+ ):+ return engine._get_previews(QUERY)+++def _drive_serply_scholar(tracker):+ engine = _build_serply(tracker, search_type="scholar")+ with patch.object(+ serply_engine,+ "safe_get",+ const_response(payload=SERPLY_SCHOLAR_PAYLOAD),+ ):+ return engine._get_previews(QUERY)++def _drive_sofya(tracker):engine = _wire(sofya_engine.SofyaSearchEngine(@@ -1644,6 +1706,13 @@ CASES = ["https://serper-result.example/transformers","Serper's snippet",),+ Case(+ "serply",+ _drive_serply,+ "Transformer architecture - Serply",+ "https://serply-result.example/transformers",+ "Serply's description",+ ),Case("sofya",_drive_sofya,@@ -1992,6 +2061,73 @@ class TestEngineSuccessPath:)+class TestSerplyScholarMode:+ """Serply's ``scholar`` vertical is the one case in the table above+ that changes pipeline mid-class: ``is_scientific`` is set per instance,+ so the same engine routes Scholar articles through the DOI enrichment+ step and the journal reputation filter while web and news stay generic.+ """++ def test_scholar_previews_are_usable(self, inert_tracker):+ previews = _drive_serply_scholar(inert_tracker)++ assert previews+ first = previews[0]+ assert first["title"] == "Attention Is All You Need"+ assert first["link"] == "https://doi.org/10.48550/arXiv.1706.03762"+ assert "NeurIPS, 2017" in first["snippet"]++ links = extract_links_from_search_results(previews)+ assert len(links) == len(previews)+ assert links[0]["url"] == first["link"]++ def test_scholar_results_reach_the_scientific_pipeline(+ self, inert_tracker, monkeypatch+ ):+ """``run()`` hands Scholar previews to the DOI enrichment step.++ Web mode must not: the enrichment call costs a network round trip+ and only pays off for results that carry a DOI.+ """+ seen = []++ def fake_enrich(results, email=None):+ seen.append([dict(r) for r in results])+ return results++ monkeypatch.setattr(+ "local_deep_research.utilities.openalex_enrichment."+ "enrich_results_with_source_ids",+ fake_enrich,+ )++ scholar = _build_serply(inert_tracker, search_type="scholar")+ scholar.programmatic_mode = True+ assert scholar.is_scientific is True+ with patch.object(+ serply_engine,+ "safe_get",+ const_response(payload=SERPLY_SCHOLAR_PAYLOAD),+ ):+ results = scholar.run(QUERY)++ assert len(seen) == 1, "scholar results never reached enrichment"+ assert seen[0][0]["link"] == (+ "https://doi.org/10.48550/arXiv.1706.03762"+ )+ assert results and results[0]["title"] == "Attention Is All You Need"++ web = _build_serply(inert_tracker)+ web.programmatic_mode = True+ assert web.is_scientific is False+ with patch.object(+ serply_engine, "safe_get", const_response(payload=SERPLY_PAYLOAD)+ ):+ web.run(QUERY)++ assert len(seen) == 1, "web results must skip DOI enrichment"++# --------------------------------------------------------------------------# 3. Silent-drop defects in the downstream chain# --------------------------------------------------------------------------