From c02713832934e6ec3cbcbabdd518d87f857e5928 Mon Sep 17 00:00:00 2001 From: Gabs Ferreira <810549+gabsferreira@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:58:19 -0300 Subject: [PATCH] feat(search): add SearchApi provider with web, news and scholar modes Add SearchApi (searchapi.io) as a web-search provider, following the Serply shape: one key, three modes (search -> google, news -> google_news, scholar -> google_scholar) behind a single GET endpoint selected by the `engine` parameter. Rows are plain SERP results, so consolidation still writes the answer and Scholar rows render through the shared academic template via the `searchapi_scholar` -> `serper_scholar` mapping. - Key travels only as `Authorization: Bearer`, never in the URL; requests carry `Accept: application/json` and `User-Agent: DeepTutor`. - Google retired `num` for web and news results, so those are cut client-side with `max_results`; Scholar still honors `num` (capped at 20). - News sends `link=resolved` so links point at the publisher instead of a Google redirect, and prefers `iso_date` over the relative `date`. - Scholar maps `publication`, `inline_links.cited_by.total`, `resource.link` and `data_cid` onto the Serper attribute keys; a dead `javascript:` PDF badge is dropped. - Non-200 raises with the API's `error` message; a non-JSON body raises too. - Spec table entry (`requires_api_key=True, soft_fallback=False`), registry import, consolidation mapping and `deeptutor init` wizard entry reading `SEARCHAPI_API_KEY` / `SEARCH_API_KEY`. - Nine tests mirroring the Serply block, with fixtures shaped after live responses from each engine. Co-Authored-By: Claude Fable 5.1 --- deeptutor/services/config/provider_runtime.py | 1 + deeptutor/services/search/consolidation.py | 1 + .../services/search/providers/__init__.py | 2 + .../services/search/providers/searchapi.py | 189 +++++++++++++++ deeptutor_cli/init_wizard.py | 7 + .../services/search/test_search_providers.py | 227 ++++++++++++++++++ 6 files changed, 427 insertions(+) create mode 100644 deeptutor/services/search/providers/searchapi.py diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py index 76d7b0065..da50cb023 100644 --- a/deeptutor/services/config/provider_runtime.py +++ b/deeptutor/services/config/provider_runtime.py @@ -104,6 +104,7 @@ SEARCH_PROVIDERS: dict[str, SearchProviderSpec] = { ), "serper": SearchProviderSpec(label="Serper", requires_api_key=True, soft_fallback=False), "serply": SearchProviderSpec(label="Serply", requires_api_key=True, soft_fallback=False), + "searchapi": SearchProviderSpec(label="SearchApi", 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 0ee3f033d..7378b9208 100644 --- a/deeptutor/services/search/consolidation.py +++ b/deeptutor/services/search/consolidation.py @@ -148,6 +148,7 @@ class AnswerConsolidator: "jina": "jina", "serper_scholar": "serper_scholar", "serply_scholar": "serper_scholar", + "searchapi_scholar": "serper_scholar", } def __init__( diff --git a/deeptutor/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.py index 23543b516..9f35b9530 100644 --- a/deeptutor/services/search/providers/__init__.py +++ b/deeptutor/services/search/providers/__init__.py @@ -180,6 +180,7 @@ def _register_builtin_providers() -> None: jina, perplexity, qianfan, + searchapi, searxng, serper, serply, @@ -199,6 +200,7 @@ def _register_builtin_providers() -> None: jina, perplexity, qianfan, + searchapi, searxng, serper, serply, diff --git a/deeptutor/services/search/providers/searchapi.py b/deeptutor/services/search/providers/searchapi.py new file mode 100644 index 000000000..8c90a4176 --- /dev/null +++ b/deeptutor/services/search/providers/searchapi.py @@ -0,0 +1,189 @@ +"""SearchApi search provider. + +API: https://www.searchapi.io +Docs: https://www.searchapi.io/docs/google +Endpoint: https://www.searchapi.io/api/v1/search?engine=&q= + +SearchApi serves live Google SERP rows plus the Google News and Google Scholar +verticals behind one key, selected with the ``engine`` parameter, 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 json +from typing import Any + +import requests + +from ..base import BaseSearchProvider +from ..types import Citation, SearchResult, WebSearchResponse +from . import register_provider + +# mode -> SearchApi engine +_ENGINES: dict[str, str] = { + "search": "google", + "news": "google_news", + "scholar": "google_scholar", +} + + +@register_provider("searchapi") +class SearchApiProvider(BaseSearchProvider): + """SearchApi Google SERP / News / Scholar provider.""" + + description = "Google SERP, News and Scholar results" + BASE_URL = "https://www.searchapi.io/api/v1" + API_KEY_ENV_VARS = ("SEARCHAPI_API_KEY", "SEARCH_API_KEY") + + def search( + self, + query: str, + mode: str = "search", + max_results: int = 5, + timeout: int = 30, + **kwargs: Any, + ) -> WebSearchResponse: + """Search SearchApi. + + Args: + query: Search query. + mode: ``search`` (Google web), ``news`` (Google News) or ``scholar`` + (Google Scholar). + max_results: Result cap. Google retired ``num`` for web and news + results, so those come one page (about 10 rows) at a time and + are cut here; Scholar still honors ``num`` (1-20). + timeout: Request timeout in seconds. + **kwargs: Additional options, including ``base_url``, the API root + (``/search`` is appended) for a self-hosted gateway, and the + optional Google ``gl`` / ``hl`` localisation codes. + + Returns: + WebSearchResponse: Standardized search response. + """ + if mode not in _ENGINES: + raise ValueError(f"SearchApi mode must be one of {sorted(_ENGINES)}, got {mode!r}.") + engine = _ENGINES[mode] + root = str(kwargs.get("base_url") or self.BASE_URL).rstrip("/") + limit = max(1, int(max_results)) + params: dict[str, Any] = {"engine": engine, "q": query} + if mode == "scholar": + params["num"] = min(limit, 20) + elif mode == "news": + # Resolve Google's redirect links to the publisher's own URL. + params["link"] = "resolved" + for key in ("gl", "hl"): + if kwargs.get(key): + params[key] = kwargs[key] + headers = { + # The key travels only in the header, never in the URL. + "Authorization": f"Bearer {self.api_key}", + "Accept": "application/json", + "User-Agent": "DeepTutor", + } + request_kwargs: dict[str, Any] = {"headers": headers, "params": params} + if self.proxy: + request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy} + self.logger.debug(f"Calling SearchApi engine={engine}, max_results={limit}") + resp = requests.get(f"{root}/search", timeout=timeout, **request_kwargs) + if resp.status_code != 200: + try: + detail = resp.json().get("error") or resp.text + except (json.JSONDecodeError, ValueError, AttributeError): + detail = resp.text + self.logger.error(f"SearchApi error: {resp.status_code} - {detail}") + raise Exception(f"SearchApi API error: {resp.status_code} - {detail}") + try: + payload = resp.json() + except (json.JSONDecodeError, ValueError) as exc: + raise Exception("SearchApi API error: response was not valid JSON") from exc + if not isinstance(payload, dict): + payload = {} + rows = [row for row in payload.get("organic_results") or [] if isinstance(row, dict)] + rows = rows[:limit] + + 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="searchapi_scholar" if mode == "scholar" else "searchapi", + timestamp=datetime.now().isoformat(), + model=f"searchapi-{engine}", + citations=citations, + search_results=search_results, + metadata=metadata, + ) + + +def _parse_row(mode: str, row: dict[str, Any]) -> SearchResult: + """Map one SearchApi row onto ``SearchResult``; each engine has its own shape.""" + title = str(row.get("title", "")) + url = str(row.get("link", "")) + snippet = str(row.get("snippet", "") or "") + if mode == "news": + return SearchResult( + title=title, + url=url, + snippet=snippet, + # ``iso_date`` is absolute; ``date`` is Google's "8 hours ago". + date=str(row.get("iso_date") or row.get("date") or ""), + source=str(row.get("source") or "Google News"), + ) + if mode == "scholar": + # Keyed like Serper's scholar rows so the shared academic template renders them. + attributes: dict[str, Any] = {} + authors = [ + author.get("name") + for author in row.get("authors") or [] + if isinstance(author, dict) and author.get("name") + ] + publication = row.get("publication") or ", ".join(authors) + if publication: + attributes["publicationInfo"] = publication + cited = ((row.get("inline_links") or {}).get("cited_by") or {}).get("total") + if cited is not None: + attributes["citedBy"] = cited + pdf_url = (row.get("resource") or {}).get("link") or "" + if pdf_url.startswith("http") and "javascript:" not in pdf_url: + attributes["pdfUrl"] = pdf_url + if row.get("data_cid"): + attributes["paperId"] = row["data_cid"] + return SearchResult( + title=title, + url=url, + snippet=snippet, + source="Google Scholar", + attributes=attributes, + ) + return SearchResult( + title=title, + url=url, + snippet=snippet, + date=str(row.get("date", "") or ""), + source=str(row.get("source") or row.get("domain") or "Google"), + ) diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.py index 543540cd1..a5bbb7270 100644 --- a/deeptutor_cli/init_wizard.py +++ b/deeptutor_cli/init_wizard.py @@ -175,6 +175,13 @@ SEARCH_PROVIDERS: tuple[SearchProviderSpec, ...] = ( env_keys=("SERPLY_API_KEY", "SEARCH_API_KEY"), hint="Google SERP · News & Scholar modes · paid", ), + SearchProviderSpec( + name="searchapi", + label="SearchApi", + requires_api_key=True, + env_keys=("SEARCHAPI_API_KEY", "SEARCH_API_KEY"), + hint="Google SERP · News & Scholar modes · 100 free requests", + ), SearchProviderSpec( name="perplexity", label="Perplexity", diff --git a/tests/services/search/test_search_providers.py b/tests/services/search/test_search_providers.py index 004940837..a59a88311 100644 --- a/tests/services/search/test_search_providers.py +++ b/tests/services/search/test_search_providers.py @@ -499,6 +499,233 @@ def test_serply_rejects_an_unknown_mode() -> None: SerplyProvider(api_key="k").search("q", mode="images") +# -------------------------------------------------------------------------- +# SearchApi: one key, three Google engines (google / google_news / +# google_scholar) behind a single GET endpoint selected by `engine`. Google no +# longer honors `num` for web and news, so those rows are cut client-side. +# -------------------------------------------------------------------------- + +_SEARCHAPI_BODIES: dict[str, dict[str, Any]] = { + "google": { + "organic_results": [ + { + "position": i + 1, + "title": f"Result {i}" if i else "[1706.03762] Attention Is All You Need", + "link": f"https://example.org/{i}" if i else "https://arxiv.org/abs/1706.03762", + "source": "arXiv", + "domain": "arxiv.org", + "snippet": "We propose a new simple network architecture, the Transformer...", + "date": "Jun 12, 2017", + } + for i in range(10) + ], + "related_searches": [{"query": "transformer paper"}], + "knowledge_graph": {"title": "Attention Is All You Need"}, + }, + "google_news": { + "organic_results": [ + { + "position": i + 1, + "title": f"Story {i}", + "link": f"https://news.example/{i}", + "source": "Example Times", + "date": "8 hours ago", + "iso_date": "2026-11-10T11:00:00Z", + "snippet": "Genuine attention & chatbots", + } + for i in range(10) + ] + }, + "google_scholar": { + "organic_results": [ + { + "position": 1, + "title": "Attention is all you need", + "data_cid": "5Gohgn6QFikJ", + "link": "https://proceedings.neurips.cc/paper/7181-attention-is-all-you-need", + "publication": "A Vaswani, N Shazeer, N Parmar - Advances in neural ..., 2017", + "snippet": "The dominant sequence transduction models...", + "inline_links": { + "cited_by": {"total": 281445, "link": "https://scholar.google.com/x"} + }, + "resource": {"name": "[PDF]", "link": "https://example.org/attention.pdf"}, + "authors": [{"name": "A Vaswani"}, {"name": "N Shazeer"}], + }, + { + "position": 2, + "title": "Is Attention All You Need?", + "data_cid": "QEhbjTxy5DIJ", + "link": "https://link.springer.com/chapter/10.1007/978-3-031-84300-6_13", + "snippet": "We show how transformers...", + "inline_links": {"cited_by": {"total": 14}}, + # Scholar renders a dead "[PDF]" badge as a javascript: href. + "resource": { + "name": "[PDF]", + "link": "https://scholar.google.comjavascript:void(0)", + }, + "authors": [{"name": "P Mineault"}], + }, + ] + }, +} + + +@pytest.fixture +def searchapi_calls(monkeypatch): + """Capture SearchApi GETs and answer each with the fixture body for its engine.""" + captured: list[dict[str, Any]] = [] + + def _get(url: str, **kwargs: Any) -> _FakeResponse: + captured.append({"method": "GET", "url": url, **kwargs}) + return _FakeResponse(_SEARCHAPI_BODIES[kwargs["params"]["engine"]]) + + class _FakeRequests: + get = staticmethod(_get) + + monkeypatch.setattr("deeptutor.services.search.providers.searchapi.requests", _FakeRequests) + return captured + + +def test_searchapi_sends_bearer_header_params_proxy_and_base_url_root(searchapi_calls) -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + provider = SearchApiProvider(api_key="k", proxy=PROXY) + provider.search("attention & focus", max_results=3, base_url="https://gateway.example/v1/") + + call = searchapi_calls[-1] + assert call["url"] == "https://gateway.example/v1/search" + assert call["params"] == {"engine": "google", "q": "attention & focus"} + assert "num" not in call["params"] + assert "api_key" not in call["params"] and "k" not in call["url"] + assert call["headers"]["Authorization"] == "Bearer k" + assert call["headers"]["User-Agent"] == "DeepTutor" + assert call["proxies"] == {"http": PROXY, "https": PROXY} + + +def test_searchapi_forwards_gl_and_hl_only_when_given(searchapi_calls) -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + SearchApiProvider(api_key="k").search("q", gl="br", hl="pt") + assert searchapi_calls[-1]["params"]["gl"] == "br" + assert searchapi_calls[-1]["params"]["hl"] == "pt" + assert "proxies" not in searchapi_calls[-1] + + +def test_searchapi_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.searchapi import SearchApiProvider + + spec = SEARCH_PROVIDERS["searchapi"] + assert "searchapi" in list_providers() + assert SearchApiProvider.display_name == spec.label == "SearchApi" + assert SearchApiProvider.requires_api_key is True + assert SearchApiProvider.supports_answer is False + # Paid provider: never quietly turn a billed key into DuckDuckGo. + assert spec.soft_fallback is False + + +def test_searchapi_web_rows_map_and_are_cut_to_max_results(searchapi_calls) -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + response = SearchApiProvider(api_key="k").search("attention is all you need", max_results=3) + + assert response.provider == "searchapi" + assert response.model == "searchapi-google" + assert response.answer == "" + assert len(response.search_results) == len(response.citations) == 3 + row = response.search_results[0] + assert row.url == "https://arxiv.org/abs/1706.03762" + assert row.source == "arXiv" + assert row.date == "Jun 12, 2017" + assert response.citations[0].reference == "[1]" + assert response.metadata["relatedSearches"] == [{"query": "transformer paper"}] + assert response.metadata["knowledgeGraph"] == {"title": "Attention Is All You Need"} + + +def test_searchapi_news_resolves_links_and_trims_client_side(searchapi_calls) -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + response = SearchApiProvider(api_key="k").search("chatbots", mode="news", max_results=4) + + params = searchapi_calls[-1]["params"] + assert params["engine"] == "google_news" + assert params["link"] == "resolved" + assert "num" not in params + 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 == "2026-11-10T11:00:00Z" + + +def test_searchapi_scholar_rows_render_through_the_academic_template(searchapi_calls) -> None: + from deeptutor.services.search.consolidation import AnswerConsolidator + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + response = SearchApiProvider(api_key="k").search("attention", mode="scholar", max_results=50) + + params = searchapi_calls[-1]["params"] + assert params["engine"] == "google_scholar" + assert params["num"] == 20 # Scholar still honors num, capped at its 20 + assert response.provider == "searchapi_scholar" + first, second = response.search_results + assert first.attributes == { + "publicationInfo": "A Vaswani, N Shazeer, N Parmar - Advances in neural ..., 2017", + "citedBy": 281445, + "pdfUrl": "https://example.org/attention.pdf", + "paperId": "5Gohgn6QFikJ", + } + # No publication string: fall back to the author names; dead PDF badge dropped. + assert second.attributes == { + "publicationInfo": "P Mineault", + "citedBy": 14, + "paperId": "QEhbjTxy5DIJ", + } + rendered = AnswerConsolidator().consolidate(response).answer + assert "Cited by: 281445" in rendered + assert "[PDF](https://example.org/attention.pdf)" in rendered + assert "javascript:" not in rendered + + +def test_searchapi_surfaces_the_api_error_message(monkeypatch) -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + class _Unauthorized(_FakeResponse): + status_code = 401 + text = '{"error":"Invalid API key."}' + + class _FakeRequests: + get = staticmethod(lambda url, **kwargs: _Unauthorized({"error": "Invalid API key."})) + + monkeypatch.setattr("deeptutor.services.search.providers.searchapi.requests", _FakeRequests) + with pytest.raises(Exception, match="401 - Invalid API key."): + SearchApiProvider(api_key="bad").search("q") + + +def test_searchapi_rejects_a_non_json_body(monkeypatch) -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + class _Garbled(_FakeResponse): + text = "upstream timeout" + + def json(self) -> dict[str, Any]: + raise ValueError("No JSON object could be decoded") + + class _FakeRequests: + get = staticmethod(lambda url, **kwargs: _Garbled({})) + + monkeypatch.setattr("deeptutor.services.search.providers.searchapi.requests", _FakeRequests) + with pytest.raises(Exception, match="not valid JSON"): + SearchApiProvider(api_key="k").search("q") + + +def test_searchapi_rejects_an_unknown_mode() -> None: + from deeptutor.services.search.providers.searchapi import SearchApiProvider + + with pytest.raises(ValueError, match="mode"): + SearchApiProvider(api_key="k").search("q", mode="images") + + # -------------------------------------------------------------------------- # You.com: authenticated Search API. # --------------------------------------------------------------------------