feat(search): add WebRouter as a keyless search provider (#3001)

This commit is contained in:
Bingxi Zhao (Frank)
2026-12-02 05:40:19 -05:00
11 changed files with 350 additions and 0 deletions

View File

@@ -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": []

View File

@@ -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,

View File

@@ -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,
)

View File

@@ -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",
)

View File

@@ -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",

View File

@@ -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

View File

@@ -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

View File

@@ -569,6 +569,7 @@ const PROVIDER_LABELS: Record<string, string> = {
zhipu: "Zhipu",
deepseek: "DeepSeek",
specstream: "SpecStream",
webrouter: "WebRouter",
};
function providerLabel(slug: string): string {

View File

@@ -70,6 +70,7 @@ export const PROVIDER_ICONS: Readonly<Record<string, ProviderIconSpec>> = {
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" },
};

View File

@@ -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",

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB