DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(search): align Serply requests with documented API
Bingxi Zhao (Frank)57a26318044a
diff --git a/deeptutor/services/search/providers/serply.py b/deeptutor/services/search/providers/serply.pyindex 45713477b..914fdad6a 100644--- a/deeptutor/services/search/providers/serply.py+++ b/deeptutor/services/search/providers/serply.py@@ -2,7 +2,7 @@API: https://serply.ioDocs: https://serply.io/docs-Endpoints: https://api.serply.io/v1/{search,news,scholar}/+Endpoints: https://api.serply.io/v1/{search,news,scholar}/q=<encoded query>Serply serves live Google SERP rows plus the Google News and Google Scholarverticals behind one key, so a study session can go from "what is X" to@@ -17,6 +17,7 @@ from datetime import datetimeimport htmlimport refrom typing import Any+from urllib.parse import urlencodeimport requests@@ -24,11 +25,11 @@ from ..base import BaseSearchProviderfrom ..types import Citation, SearchResult, WebSearchResponsefrom . 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"),+# mode -> URL path segment+_MODES: dict[str, str] = {+ "search": "search",+ "news": "news",+ "scholar": "scholar",}_TAG = re.compile(r"<[^>]+>")@@ -59,14 +60,14 @@ class SerplyProvider(BaseSearchProvider):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.+ (``/search/q=...`` 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]+ path = _MODES[mode]root = str(kwargs.get("base_url") or self.BASE_URL).rstrip("/")num = max(1, min(int(max_results), 100))headers = {@@ -74,14 +75,15 @@ class SerplyProvider(BaseSearchProvider):"Accept": "application/json","User-Agent": "deeptutor",}- request_kwargs: dict[str, Any] = {"headers": headers, "params": {"q": query, "num": num}}+ request_kwargs: dict[str, Any] = {"headers": headers}if self.proxy:request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}- resp = requests.get(f"{root}/{path}/", timeout=timeout, **request_kwargs)+ encoded_query = urlencode({"q": query, "num": num})+ resp = requests.get(f"{root}/{path}/{encoded_query}", 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]+ rows = _result_rows(mode, payload)[:num]citations: list[Citation] = []search_results: list[SearchResult] = []@@ -123,7 +125,10 @@ def _parse_row(mode: str, row: dict[str, Any]) -> SearchResult:title = str(row.get("title", ""))url = str(row.get("link", ""))if mode == "news":- source = (row.get("source") or {}).get("title") or "Google News"+ raw_source = row.get("source")+ source = (+ raw_source.get("title") if isinstance(raw_source, dict) else raw_source+ ) or "Google News"return SearchResult(title=title,url=url,@@ -157,3 +162,13 @@ def _parse_row(mode: str, row: dict[str, Any]) -> SearchResult:snippet=str(row.get("description", "") or ""),source=str(display_url or "Serply"),)+++def _result_rows(mode: str, payload: dict[str, Any]) -> list[dict[str, Any]]:+ """Read each vertical's documented response envelope."""+ if mode == "news":+ feed = payload.get("feed")+ rows = feed.get("entries") if isinstance(feed, dict) else None+ else:+ rows = payload.get("articles" if mode == "scholar" else "results")+ return [row for row in rows or [] if isinstance(row, dict)]diff --git a/tests/services/search/test_search_providers.py b/tests/services/search/test_search_providers.pyindex 465cfebe1..bee43fc56 100644--- a/tests/services/search/test_search_providers.py+++ b/tests/services/search/test_search_providers.py@@ -374,16 +374,18 @@ _SERPLY_BODIES: dict[str, dict[str, Any]] = {"related_searches": [{"query": "transformer paper"}],},"news": {- "entries": [- {- "title": f"Story {i}",- "link": f"https://news.example/{i}",- "summary": "<a href='x'>Genuine</a> attention & chatbots",- "published": "Mon, 25 Aug 2026 09:00:00 GMT",- "source": {"title": "Example Times"},- }- for i in range(10)- ]+ "feed": {+ "entries": [+ {+ "title": f"Story {i}",+ "link": f"https://news.example/{i}",+ "summary": "<a href='x'>Genuine</a> attention & chatbots",+ "published": "Mon, 25 Aug 2026 09:00:00 GMT",+ "source": "Example Times",+ }+ for i in range(10)+ ]+ }},"scholar": {"articles": [@@ -408,7 +410,7 @@ def serply_calls(monkeypatch):def _get(url: str, **kwargs: Any) -> _FakeResponse:captured.append({"method": "GET", "url": url, **kwargs})- mode = url.rstrip("/").rsplit("/", 1)[-1]+ mode = url.rsplit("/", 2)[-2]return _FakeResponse(_SERPLY_BODIES[mode])class _FakeRequests:@@ -422,11 +424,11 @@ def test_serply_carries_max_results_proxy_and_base_url_root(serply_calls) -> Nonfrom deeptutor.services.search.providers.serply import SerplyProviderprovider = SerplyProvider(api_key="k", proxy=PROXY)- provider.search("q", max_results=3, base_url="https://gateway.example/v1/")+ provider.search("attention & focus", 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["url"] == ("https://gateway.example/v1/search/q=attention+%26+focus&num=3")+ assert "params" not in callassert call["headers"]["X-Api-Key"] == "k"assert call["proxies"] == {"http": PROXY, "https": PROXY}@@ -464,7 +466,7 @@ def test_serply_news_trims_client_side_and_strips_html(serply_calls) -> None:response = SerplyProvider(api_key="k").search("chatbots", mode="news", max_results=4)- assert serply_calls[-1]["url"].endswith("/news/")+ assert "/news/q=chatbots&num=4" in serply_calls[-1]["url"]assert len(response.search_results) == 4assert response.search_results[0].snippet == "Genuine attention & chatbots"assert response.search_results[0].source == "Example Times"