Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(search): add Serply provider with web, news and scholar modes

serply6c1a615ed100
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 24c84ab0b..fdb24566e 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -87,6 +87,7 @@ SEARCH_PROVIDERS: dict[str, SearchProviderSpec] = {
supports_answer=True,
),
"serper": SearchProviderSpec(label="Serper", requires_api_key=True, soft_fallback=False),
+ "serply": SearchProviderSpec(label="Serply", requires_api_key=True, soft_fallback=False),
"firecrawl": SearchProviderSpec(label="Firecrawl", requires_api_key=True, soft_fallback=False),
# China-hosted engines. Doubao is the one that writes its own answer: Ark
# exposes web search only as a tool on a Doubao model, never standalone.
diff --git a/deeptutor/services/search/consolidation.py b/deeptutor/services/search/consolidation.py
index b417feabb..0ee3f033d 100644
--- a/deeptutor/services/search/consolidation.py
+++ b/deeptutor/services/search/consolidation.py
@@ -147,6 +147,7 @@ class AnswerConsolidator:
"serper": "serper",
"jina": "jina",
"serper_scholar": "serper_scholar",
+ "serply_scholar": "serper_scholar",
}
def __init__(
diff --git a/deeptutor/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.py
index ca09b25c2..c0cf7e134 100644
--- a/deeptutor/services/search/providers/__init__.py
+++ b/deeptutor/services/search/providers/__init__.py
@@ -181,6 +181,7 @@ def _register_builtin_providers() -> None:
qianfan,
searxng,
serper,
+ serply,
tavily,
zhipu,
)
@@ -197,6 +198,7 @@ def _register_builtin_providers() -> None:
qianfan,
searxng,
serper,
+ serply,
tavily,
zhipu,
)
diff --git a/deeptutor/services/search/providers/serply.py b/deeptutor/services/search/providers/serply.py
new file mode 100644
index 000000000..45713477b
--- /dev/null
+++ b/deeptutor/services/search/providers/serply.py
@@ -0,0 +1,159 @@
+"""Serply search provider.
+
+API: https://serply.io
+Docs: https://serply.io/docs
+Endpoints: https://api.serply.io/v1/{search,news,scholar}/
+
+Serply serves live Google SERP rows plus the Google News and Google Scholar
+verticals behind one key, so a study session can go from "what is X" to
+"what do the papers say about X" without switching providers. Every mode
+returns plain rows with no model-written answer, so consolidation still
+supplies the answer.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+import html
+import re
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+# mode -> (URL path segment, key that holds the result rows)
+_MODES: dict[str, tuple[str, str]] = {
+ "search": ("search", "results"),
+ "news": ("news", "entries"),
+ "scholar": ("scholar", "articles"),
+}
+_TAG = re.compile(r"<[^>]+>")
+
+
+@register_provider("serply")
+class SerplyProvider(BaseSearchProvider):
+ """Serply Google SERP / News / Scholar provider."""
+
+ description = "Google SERP, News and Scholar results"
+ BASE_URL = "https://api.serply.io/v1"
+ API_KEY_ENV_VARS = ("SERPLY_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ mode: str = "search",
+ max_results: int = 5,
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search Serply.
+
+ Args:
+ query: Search query.
+ mode: ``search`` (Google web), ``news`` (Google News) or ``scholar``
+ (Google Scholar).
+ max_results: Result cap. Serply's own ``num`` accepts 1-100; the
+ news feed ignores it server-side, so rows are also cut here.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options, including ``base_url``, the API root
+ (``/search/`` etc. is appended) for a self-hosted gateway.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ if mode not in _MODES:
+ raise ValueError(f"Serply mode must be one of {sorted(_MODES)}, got {mode!r}.")
+ path, rows_key = _MODES[mode]
+ root = str(kwargs.get("base_url") or self.BASE_URL).rstrip("/")
+ num = max(1, min(int(max_results), 100))
+ headers = {
+ "X-Api-Key": self.api_key,
+ "Accept": "application/json",
+ "User-Agent": "deeptutor",
+ }
+ request_kwargs: dict[str, Any] = {"headers": headers, "params": {"q": query, "num": num}}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.get(f"{root}/{path}/", timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Serply API error: {resp.status_code} - {resp.text}")
+ payload = resp.json()
+ rows = (payload.get(rows_key) or [])[:num]
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ for idx, row in enumerate(rows, 1):
+ result = _parse_row(mode, row)
+ search_results.append(result)
+ citations.append(
+ Citation(
+ id=idx,
+ reference=f"[{idx}]",
+ url=result.url,
+ title=result.title,
+ snippet=result.snippet,
+ date=result.date,
+ source=result.source,
+ )
+ )
+
+ metadata: dict[str, Any] = {"finish_reason": "stop", "mode": mode}
+ if payload.get("related_searches"):
+ metadata["relatedSearches"] = payload["related_searches"]
+ if payload.get("knowledge_graph"):
+ metadata["knowledgeGraph"] = payload["knowledge_graph"]
+
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider="serply_scholar" if mode == "scholar" else "serply",
+ timestamp=datetime.now().isoformat(),
+ model=f"serply-{mode}",
+ citations=citations,
+ search_results=search_results,
+ metadata=metadata,
+ )
+
+
+def _parse_row(mode: str, row: dict[str, Any]) -> SearchResult:
+ """Map one Serply row onto ``SearchResult``; each vertical has its own shape."""
+ title = str(row.get("title", ""))
+ url = str(row.get("link", ""))
+ if mode == "news":
+ source = (row.get("source") or {}).get("title") or "Google News"
+ return SearchResult(
+ title=title,
+ url=url,
+ snippet=html.unescape(_TAG.sub("", str(row.get("summary", "") or ""))).strip(),
+ date=str(row.get("published", "") or ""),
+ source=str(source),
+ )
+ if mode == "scholar":
+ # Keyed like Serper's scholar rows so the shared academic template renders them.
+ attributes: dict[str, Any] = {}
+ if (row.get("author") or {}).get("names"):
+ attributes["publicationInfo"] = row["author"]["names"]
+ cited = ((row.get("extras") or {}).get("citations") or {}).get("count")
+ if cited is not None:
+ attributes["citedBy"] = cited
+ if (row.get("doc") or {}).get("link"):
+ attributes["pdfUrl"] = row["doc"]["link"]
+ if row.get("id"):
+ attributes["paperId"] = row["id"]
+ return SearchResult(
+ title=title,
+ url=url,
+ snippet=str(row.get("description", "") or ""),
+ source="Google Scholar",
+ attributes=attributes,
+ )
+ display_url = (row.get("metadata") or {}).get("display_url") or ""
+ return SearchResult(
+ title=title,
+ url=url,
+ snippet=str(row.get("description", "") or ""),
+ source=str(display_url or "Serply"),
+ )
diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.py
index 109280cb2..740062f69 100644
--- a/deeptutor_cli/init_wizard.py
+++ b/deeptutor_cli/init_wizard.py
@@ -169,6 +169,13 @@ SEARCH_PROVIDERS: tuple[SearchProviderSpec, ...] = (
env_keys=("SERPER_API_KEY", "SEARCH_API_KEY"),
hint="Google results · paid",
),
+ SearchProviderSpec(
+ name="serply",
+ label="Serply",
+ requires_api_key=True,
+ env_keys=("SERPLY_API_KEY", "SEARCH_API_KEY"),
+ hint="Google SERP · News & Scholar modes · paid",
+ ),
SearchProviderSpec(
name="perplexity",
label="Perplexity",
diff --git a/tests/services/search/test_search_providers.py b/tests/services/search/test_search_providers.py
index f1155b233..465cfebe1 100644
--- a/tests/services/search/test_search_providers.py
+++ b/tests/services/search/test_search_providers.py
@@ -354,3 +354,144 @@ def test_bocha_surfaces_an_error_carried_inside_a_200(monkeypatch) -> None:
with pytest.raises(Exception, match="quota exhausted"):
BochaProvider(api_key="k").search("q")
+
+
+# --------------------------------------------------------------------------
+# Serply: one key, three Google verticals (web / news / scholar). It is a GET
+# API, so the cap lands in `params`, and the news feed ignores `num` server-side.
+# --------------------------------------------------------------------------
+
+_SERPLY_BODIES: dict[str, dict[str, Any]] = {
+ "search": {
+ "results": [
+ {
+ "title": "Attention Is All You Need - arXiv",
+ "link": "https://arxiv.org/abs/1706.03762",
+ "description": "The dominant sequence transduction models...",
+ "metadata": {"display_url": "arxiv.org"},
+ }
+ ],
+ "related_searches": [{"query": "transformer paper"}],
+ },
+ "news": {
+ "entries": [
+ {
+ "title": f"Story {i}",
+ "link": f"https://news.example/{i}",
+ "summary": "<a href='x'>Genuine</a> attention &amp; chatbots",
+ "published": "Mon, 25 Aug 2026 09:00:00 GMT",
+ "source": {"title": "Example Times"},
+ }
+ for i in range(10)
+ ]
+ },
+ "scholar": {
+ "articles": [
+ {
+ "id": "W2626778328",
+ "title": "Attention Is All You Need",
+ "link": "https://doi.org/10.65215/2q58a426",
+ "description": "We propose a new simple network architecture...",
+ "author": {"names": "A Vaswani, N Shazeer - 2017"},
+ "extras": {"citations": {"count": 120000}},
+ "doc": {"link": "https://example.org/attention.pdf", "type": "PDF"},
+ }
+ ]
+ },
+}
+
+
+def serply_calls(monkeypatch):
+ """Capture Serply GETs and answer each with the fixture body for its mode."""
+ captured: list[dict[str, Any]] = []
+
+ def _get(url: str, **kwargs: Any) -> _FakeResponse:
+ captured.append({"method": "GET", "url": url, **kwargs})
+ mode = url.rstrip("/").rsplit("/", 1)[-1]
+ return _FakeResponse(_SERPLY_BODIES[mode])
+
+ class _FakeRequests:
+ get = staticmethod(_get)
+
+ monkeypatch.setattr("deeptutor.services.search.providers.serply.requests", _FakeRequests)
+ return captured
+
+
+def test_serply_carries_max_results_proxy_and_base_url_root(serply_calls) -> None:
+ from deeptutor.services.search.providers.serply import SerplyProvider
+
+ provider = SerplyProvider(api_key="k", proxy=PROXY)
+ provider.search("q", max_results=3, base_url="https://gateway.example/v1/")
+
+ call = serply_calls[-1]
+ assert call["url"] == "https://gateway.example/v1/search/"
+ assert call["params"] == {"q": "q", "num": 3}
+ assert call["headers"]["X-Api-Key"] == "k"
+ assert call["proxies"] == {"http": PROXY, "https": PROXY}
+
+
+def test_serply_metadata_comes_from_the_spec_table() -> None:
+ from deeptutor.services.config import SEARCH_PROVIDERS
+ from deeptutor.services.search.providers import list_providers
+ from deeptutor.services.search.providers.serply import SerplyProvider
+
+ spec = SEARCH_PROVIDERS["serply"]
+ assert "serply" in list_providers()
+ assert SerplyProvider.display_name == spec.label
+ assert SerplyProvider.requires_api_key is True
+ assert SerplyProvider.supports_answer is False
+ # Paid provider: never quietly turn a billed key into DuckDuckGo.
+ assert spec.soft_fallback is False
+
+
+def test_serply_web_rows_map_onto_search_results(serply_calls) -> None:
+ from deeptutor.services.search.providers.serply import SerplyProvider
+
+ response = SerplyProvider(api_key="k").search("attention is all you need")
+
+ assert response.provider == "serply"
+ assert response.answer == ""
+ (row,) = response.search_results
+ assert row.url == "https://arxiv.org/abs/1706.03762"
+ assert row.source == "arxiv.org"
+ assert response.citations[0].reference == "[1]"
+ assert response.metadata["relatedSearches"] == [{"query": "transformer paper"}]
+
+
+def test_serply_news_trims_client_side_and_strips_html(serply_calls) -> None:
+ from deeptutor.services.search.providers.serply import SerplyProvider
+
+ response = SerplyProvider(api_key="k").search("chatbots", mode="news", max_results=4)
+
+ assert serply_calls[-1]["url"].endswith("/news/")
+ assert len(response.search_results) == 4
+ assert response.search_results[0].snippet == "Genuine attention & chatbots"
+ assert response.search_results[0].source == "Example Times"
+ assert response.search_results[0].date.startswith("Mon, 25 Aug 2026")
+
+
+def test_serply_scholar_rows_render_through_the_academic_template(serply_calls) -> None:
+ from deeptutor.services.search.consolidation import AnswerConsolidator
+ from deeptutor.services.search.providers.serply import SerplyProvider
+
+ response = SerplyProvider(api_key="k").search("attention", mode="scholar")
+
+ assert response.provider == "serply_scholar"
+ (row,) = response.search_results
+ assert row.attributes == {
+ "publicationInfo": "A Vaswani, N Shazeer - 2017",
+ "citedBy": 120000,
+ "pdfUrl": "https://example.org/attention.pdf",
+ "paperId": "W2626778328",
+ }
+ rendered = AnswerConsolidator().consolidate(response).answer
+ assert "Cited by: 120000" in rendered
+ assert "[PDF](https://example.org/attention.pdf)" in rendered
+
+
+def test_serply_rejects_an_unknown_mode() -> None:
+ from deeptutor.services.search.providers.serply import SerplyProvider
+
+ with pytest.raises(ValueError, match="mode"):
+ SerplyProvider(api_key="k").search("q", mode="images")