diff --git a/deeptutor/modules/manifests/providers.json b/deeptutor/modules/manifests/providers.json index 2d61f40e5..14dcf2f8a 100644 --- a/deeptutor/modules/manifests/providers.json +++ b/deeptutor/modules/manifests/providers.json @@ -16,6 +16,7 @@ "anthropic>=0.30.0", "dashscope>=1.14.0", "perplexityai>=0.1.0", + "webrouter>=0.17", "oauth-cli-kit>=0.1.1" ], "executables": [] diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py index d7a226e30..518fabd61 100644 --- a/deeptutor/services/config/provider_runtime.py +++ b/deeptutor/services/config/provider_runtime.py @@ -101,6 +101,7 @@ SEARCH_PROVIDERS: dict[str, SearchProviderSpec] = { ), "duckduckgo": SearchProviderSpec(label="DuckDuckGo"), "you": SearchProviderSpec(label="You.com", requires_api_key=True), + "webrouter": SearchProviderSpec(label="WebRouter (no proxy support)"), "perplexity": SearchProviderSpec( label="Perplexity", requires_api_key=True, diff --git a/deeptutor/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.py index 9f420c9c3..e6fa55db0 100644 --- a/deeptutor/services/search/providers/__init__.py +++ b/deeptutor/services/search/providers/__init__.py @@ -187,6 +187,7 @@ def _register_builtin_providers() -> None: serply, specstream, tavily, + webrouter, youcom, zhipu, ) @@ -209,6 +210,7 @@ def _register_builtin_providers() -> None: serply, specstream, tavily, + webrouter, youcom, zhipu, ) diff --git a/deeptutor/services/search/providers/webrouter.py b/deeptutor/services/search/providers/webrouter.py new file mode 100644 index 000000000..dc835cc65 --- /dev/null +++ b/deeptutor/services/search/providers/webrouter.py @@ -0,0 +1,98 @@ +"""WebRouter search provider (no API key required). + +WebRouter (https://github.com/Nimbleway/webrouter) is an open-source library +that sends one search to whichever of its backends can serve it, falling back +from one to the next when a backend fails. The default uses only keyless +backends and ignores process-environment credentials. Programmatic callers +can select a backend and pass its key explicitly, for example +``WebRouterProvider(backend="brave", api_key=key)``. Settings and the setup +wizard use the keyless default; their proxy is not forwarded. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any +from urllib.parse import urlsplit + +from ..base import BaseSearchProvider +from ..types import Citation, SearchResult, WebSearchResponse +from . import register_provider + + +@register_provider("webrouter") +class WebRouterProvider(BaseSearchProvider): + """Search through WebRouter's automatic backend routing.""" + + description = "WebRouter search with backend fallback (no API key required)" + API_KEY_ENV_VARS = () + + def search( + self, + query: str, + max_results: int = 5, + timeout: int = 30, + **kwargs: Any, + ) -> WebSearchResponse: + """Search through WebRouter and return its rows as citations.""" + try: + from web_router import WebRouter + except ImportError as e: + raise ImportError( + "webrouter module is not installed. To use WebRouter search, please install: " + "pip install webrouter" + ) from e + + if self.proxy: + raise ValueError("WebRouter does not support the configured search proxy.") + count = max(1, min(int(max_results), 20)) + backend = self.config.get("backend", "auto") + if self.api_key and backend == "auto": + raise ValueError("An explicit WebRouter api_key also requires a backend name.") + provider_config = {backend: {"api_key": self.api_key}} if self.api_key else {} + with WebRouter( + provider=backend, provider_config=provider_config, use_environment=False + ) as router: + response = router.search( + query, max_results=count, timeout=float(timeout), data_apis=False + ) + + search_results = [_parse_row(row) for row in response.results[:count]] + citations = [ + Citation( + id=idx, + reference=f"[{idx}]", + url=result.url, + title=result.title, + snippet=result.snippet, + date=result.date, + source=result.source, + ) + for idx, result in enumerate(search_results, 1) + ] + metadata: dict[str, Any] = {"finish_reason": "stop", "backend": response.provider} + if response.request_id: + metadata["request_id"] = response.request_id + + return WebSearchResponse( + query=query, + answer="", + provider="webrouter", + timestamp=datetime.now().isoformat(), + model=f"webrouter:{response.provider}", + citations=citations, + search_results=search_results, + metadata=metadata, + ) + + +def _parse_row(row: Any) -> SearchResult: + url = str(row.url or "") + host = urlsplit(url).hostname if url.startswith(("http://", "https://")) else "" + return SearchResult( + title=str(row.title or ""), + url=url, + snippet=str(row.description or row.content or ""), + date=str(row.published_date or ""), + source=host or "WebRouter", + ) diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.py index 2ecebae8a..f75a97021 100644 --- a/deeptutor_cli/init_wizard.py +++ b/deeptutor_cli/init_wizard.py @@ -261,6 +261,12 @@ SEARCH_PROVIDERS: tuple[SearchProviderSpec, ...] = ( env_keys=("YDC_API_KEY", "SEARCH_API_KEY"), hint="You.com Search API key", ), + SearchProviderSpec( + name="webrouter", + label="WebRouter", + requires_api_key=False, + hint="no API key needed ยท falls back across backends", + ), SearchProviderSpec( name="searxng", label="SearXNG", diff --git a/requirements/modules/providers.txt b/requirements/modules/providers.txt index 89eed23d3..4a93f5936 100644 --- a/requirements/modules/providers.txt +++ b/requirements/modules/providers.txt @@ -3,4 +3,5 @@ anthropic>=0.30.0 dashscope>=1.14.0 perplexityai>=0.1.0 +webrouter>=0.17 oauth-cli-kit>=0.1.1 diff --git a/tests/services/search/test_search_providers.py b/tests/services/search/test_search_providers.py index 2734f9e63..8eb4abc01 100644 --- a/tests/services/search/test_search_providers.py +++ b/tests/services/search/test_search_providers.py @@ -9,6 +9,8 @@ passed `proxies`) and Jina used to return every result it got. from __future__ import annotations import logging +import sys +from types import SimpleNamespace from typing import Any import pytest @@ -1002,6 +1004,238 @@ def test_youcom_surfaces_http_errors(monkeypatch) -> None: YouComProvider(api_key="k").search("q") +# -------------------------------------------------------------------------- +# WebRouter: keyless, routes one search across its backends with fallback. +# The library is faked at the module boundary, like `requests` above; one +# contract test runs the real library over an httpx mock transport. +# -------------------------------------------------------------------------- + + +def _wr_row(**fields: Any) -> SimpleNamespace: + row = {"url": "", "title": "", "description": "", "content": "", "published_date": None} + return SimpleNamespace(**{**row, **fields}) + + +_WEBROUTER_ROWS = [ + _wr_row( + title="Example Guide", + url="https://example.com/guide", + description="Guide snippet.", + content="Full page body.", + published_date="2026-10-01", + ), + _wr_row(title="Body only", url="https://example.org/body", content="Body text."), + _wr_row(title="Third", url="https://example.net/third", description="Third snippet."), +] + + +@pytest.fixture +def webrouter_calls(monkeypatch): + """Install a fake ``web_router`` module and record every router it builds.""" + captured: list[dict[str, Any]] = [] + + class _FakeRouter: + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.call: dict[str, Any] = {"init": (args, kwargs), "closed": False} + captured.append(self.call) + + def __enter__(self) -> _FakeRouter: + return self + + def __exit__(self, *exc: Any) -> None: + self.call["closed"] = True + + def search(self, query: str, **kwargs: Any) -> SimpleNamespace: + self.call.update(query=query, **kwargs) + return SimpleNamespace( + provider="tavily", request_id="req-1", results=list(_WEBROUTER_ROWS) + ) + + monkeypatch.setitem(sys.modules, "web_router", SimpleNamespace(WebRouter=_FakeRouter)) + return captured + + +def test_webrouter_sends_capped_count_timeout_and_skips_data_apis(webrouter_calls) -> None: + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + WebRouterProvider().search("attention", max_results=50, timeout=12) + + (call,) = webrouter_calls + assert call["init"] == ( + (), + {"provider": "auto", "provider_config": {}, "use_environment": False}, + ) + assert call["query"] == "attention" + assert call["max_results"] == 20 + assert call["timeout"] == 12.0 + assert call["data_apis"] is False + assert call["closed"] is True + + +def test_webrouter_maps_rows_and_names_the_serving_backend(webrouter_calls) -> None: + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + response = WebRouterProvider().search("attention", max_results=2) + + assert response.provider == "webrouter" + assert response.answer == "" + assert response.model == "webrouter:tavily" + assert response.metadata == { + "finish_reason": "stop", + "backend": "tavily", + "request_id": "req-1", + } + first, second = response.search_results + assert first.title == "Example Guide" + assert first.url == "https://example.com/guide" + assert first.snippet == "Guide snippet." + assert first.date == "2026-10-01" + assert first.source == "example.com" + # No backend snippet: fall back to the page body. + assert second.snippet == "Body text." + assert second.date == "" + assert [c.reference for c in response.citations] == ["[1]", "[2]"] + assert response.citations[0].url == "https://example.com/guide" + + +def test_webrouter_closes_the_router_when_the_search_fails(monkeypatch, webrouter_calls) -> None: + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + router_cls = sys.modules["web_router"].WebRouter + + def _fail(self, query: str, **kwargs: Any) -> None: + raise RuntimeError("every backend failed") + + monkeypatch.setattr(router_cls, "search", _fail) + with pytest.raises(RuntimeError, match="every backend failed"): + WebRouterProvider().search("attention") + assert webrouter_calls[-1]["closed"] is True + + +def test_webrouter_explains_a_missing_package(monkeypatch) -> None: + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + monkeypatch.setitem(sys.modules, "web_router", None) + with pytest.raises(ImportError, match="pip install webrouter"): + WebRouterProvider().search("attention") + + +def test_webrouter_metadata_comes_from_the_spec_table() -> None: + from deeptutor.services.config import SEARCH_PROVIDERS + from deeptutor.services.search.providers import get_available_providers, list_providers + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + spec = SEARCH_PROVIDERS["webrouter"] + assert "webrouter" in list_providers() + assert "webrouter" in get_available_providers() + assert WebRouterProvider.display_name == spec.label == "WebRouter (no proxy support)" + assert WebRouterProvider.requires_api_key is False + assert WebRouterProvider.supports_answer is False + assert spec.soft_fallback is True + + +def test_webrouter_maps_a_real_library_response(monkeypatch) -> None: + """Contract check against the installed library: Brave pinned, HTTP mocked.""" + httpx = pytest.importorskip("httpx") + web_router = pytest.importorskip("web_router") + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + sent: list[Any] = [] + + def _brave(request: Any) -> Any: + sent.append(request) + body = { + "web": { + "results": [ + { + "title": "Attention Is All You Need", + "url": "https://arxiv.org/abs/1706.03762", + "description": "The Transformer paper.", + } + ] + } + } + return httpx.Response(200, json=body) + + real_router = web_router.WebRouter + transport = httpx.MockTransport(_brave) + monkeypatch.setenv("BRAVE_SEARCH_API_KEY", "ambient-key-must-not-be-used") + monkeypatch.setattr( + web_router, + "WebRouter", + lambda **kwargs: real_router( + **{ + **kwargs, + "provider_config": { + "brave": {**kwargs["provider_config"]["brave"], "transport": transport} + }, + } + ), + ) + + response = WebRouterProvider(backend="brave", api_key="test-key").search( + "attention", max_results=3 + ) + + assert sent and sent[0].url.host == "api.search.brave.com" + assert sent[0].headers["X-Subscription-Token"] == "test-key" + assert sent[0].url.params["q"] == "attention" + assert response.model == "webrouter:brave" + (row,) = response.search_results + assert row.title == "Attention Is All You Need" + assert row.url == "https://arxiv.org/abs/1706.03762" + assert row.snippet == "The Transformer paper." + assert row.source == "arxiv.org" + + +def test_webrouter_real_auto_members_ignore_environment_keys(monkeypatch, tmp_path) -> None: + web_router = pytest.importorskip("web_router") + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("BRAVE_SEARCH_API_KEY", "synthetic-ambient-brave") + monkeypatch.setenv("EXA_API_KEY", "synthetic-ambient-exa") + real_router = web_router.WebRouter + + class CheckedMembers(Exception): + pass + + def inspect_router(**kwargs): + with real_router(**kwargs) as router: + members = router.get_provider().members + assert "brave" not in members + assert "exa" not in members + assert members + raise CheckedMembers + + monkeypatch.setattr(web_router, "WebRouter", inspect_router) + with pytest.raises(CheckedMembers): + WebRouterProvider().search("attention") + + +def test_webrouter_real_selected_backend_refuses_environment_key(monkeypatch, tmp_path) -> None: + httpx = pytest.importorskip("httpx") + web_router = pytest.importorskip("web_router") + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("BRAVE_SEARCH_API_KEY", "synthetic-ambient-brave") + + def forbid_network(*args, **kwargs): + pytest.fail("An environment-only key must not reach HTTP") + + monkeypatch.setattr(httpx.Client, "send", forbid_network) + with pytest.raises(web_router.ConfigurationError, match="api_key"): + WebRouterProvider(backend="brave").search("attention") + + +def test_webrouter_explicit_key_requires_a_backend() -> None: + from deeptutor.services.search.providers.webrouter import WebRouterProvider + + with pytest.raises(ValueError, match="backend name"): + WebRouterProvider(api_key="synthetic-explicit-key").search("attention") + + # -------------------------------------------------------------------------- # DeepSeek: the standalone SERP engine (`POST /v1/tools/search`), separate # from DeepSeek's model-side web_search tool. Billed per request, so a missing diff --git a/web/features/chat/trace/TracePresentation.tsx b/web/features/chat/trace/TracePresentation.tsx index 169c7d340..789e0c052 100644 --- a/web/features/chat/trace/TracePresentation.tsx +++ b/web/features/chat/trace/TracePresentation.tsx @@ -569,6 +569,7 @@ const PROVIDER_LABELS: Record = { zhipu: "Zhipu", deepseek: "DeepSeek", specstream: "SpecStream", + webrouter: "WebRouter", }; function providerLabel(slug: string): string { diff --git a/web/lib/provider-branding.ts b/web/lib/provider-branding.ts index 9858bc5b7..6f8f50884 100644 --- a/web/lib/provider-branding.ts +++ b/web/lib/provider-branding.ts @@ -70,6 +70,7 @@ export const PROVIDER_ICONS: Readonly> = { volcengine: { file: "volcengine-color.svg" }, volcengine_coding_plan: { file: "volcengine-color.svg" }, volcengine_speech: { file: "volcengine-color.svg" }, + webrouter: { file: "webrouter.png" }, xiaomi_mimo: { file: "xiaomimimo.svg", mono: true }, zhipu: { file: "zhipu-color.svg" }, }; diff --git a/web/public/provider-icons/sources.json b/web/public/provider-icons/sources.json index f6263407d..5fc6dece0 100644 --- a/web/public/provider-icons/sources.json +++ b/web/public/provider-icons/sources.json @@ -172,6 +172,11 @@ "sha256": "c2b68886b5e696508b40203a6779bb01d0709d225b4bfbe933714f2d6bd00578", "source": "Official website asset" }, + "webrouter.png": { + "url": "https://docs.webrouter.net/logo/favicon.png", + "sha256": "53270f6873b1cc1f46467e0f744542a28bc8b90a0cc3d93d168c725678a4758c", + "source": "Official website asset" + }, "searchapi.svg": { "url": "https://www.searchapi.io/favicon.svg", "sha256": "5ef13fedc55abb407621cb0219a563ab400735b8ba6228b52d0629990d922ca0", diff --git a/web/public/provider-icons/webrouter.png b/web/public/provider-icons/webrouter.png new file mode 100644 index 000000000..43cfecb77 Binary files /dev/null and b/web/public/provider-icons/webrouter.png differ