diff --git a/graphgen/models/__init__.py b/graphgen/models/__init__.py index 8aefb510..c64fe9e0 100644 --- a/graphgen/models/__init__.py +++ b/graphgen/models/__init__.py @@ -53,6 +53,7 @@ from .searcher.kg.wiki_search import WikiSearch from .searcher.web.bing_search import BingSearch from .searcher.web.google_search import GoogleSearch + from .searcher.web.webrouter_search import WebRouterSearch from .splitter import ChineseRecursiveTextSplitter, RecursiveCharacterSplitter from .tokenizer import Tokenizer @@ -112,6 +113,7 @@ "WikiSearch": ".searcher.kg.wiki_search", "BingSearch": ".searcher.web.bing_search", "GoogleSearch": ".searcher.web.google_search", + "WebRouterSearch": ".searcher.web.webrouter_search", # Splitter "ChineseRecursiveTextSplitter": ".splitter", "RecursiveCharacterSplitter": ".splitter", diff --git a/graphgen/models/searcher/web/webrouter_search.py b/graphgen/models/searcher/web/webrouter_search.py new file mode 100644 index 00000000..38bbd56d --- /dev/null +++ b/graphgen/models/searcher/web/webrouter_search.py @@ -0,0 +1,65 @@ +""" +To use WebRouter (https://github.com/Nimbleway/webrouter), +install it with `pip install "webrouter>=0.17"`. +It searches the web with no API key; pass a backend name and its key to use a keyed backend. +""" + +from fastapi import HTTPException + +from graphgen.utils import logger + + +class WebRouterSearch: + """ + WebRouter Search client to search the web with or without an API key. + """ + + def __init__(self, provider: str = "auto", api_key: str = None): + """ + Initialize the WebRouter Search client. + :param provider: The WebRouter search backend. Defaults to "auto", + which uses the keyless backends and falls back between them. + :param api_key: An API key for the backend named in `provider`. + Keys in environment variables are never read. + """ + if api_key and provider == "auto": + raise ValueError("Pass a backend name as `provider` along with `api_key`.") + self.provider = provider + self.provider_config = {provider: {"api_key": api_key}} if api_key else {} + + def search(self, query: str, num_results: int = 1): + """ + Search with WebRouter and return the contexts. + :param query: The searcher query. + :param num_results: The number of results to return. + :return: A list of searcher results with "title", "link" and "snippet" keys. + """ + try: + # pylint: disable=import-outside-toplevel + from web_router import WebRouter + except ImportError as e: + raise ImportError( + 'WebRouterSearch needs webrouter: pip install "webrouter>=0.17"' + ) from e + + try: + with WebRouter( + self.provider, + provider_config=self.provider_config, + use_environment=False, + ) as router: + response = router.search( + query, max_results=num_results, data_apis=False + ) + except Exception as e: # pylint: disable=broad-exception-caught + logger.error("Search engine error: %s", e) + raise HTTPException(502, "Search engine error.") from e + + return [ + { + "title": result.title or "", + "link": result.url or "", + "snippet": result.description or result.content or "", + } + for result in (response.results or [])[:num_results] + ] diff --git a/tests/unit_tests/models/searcher/test_webrouter_search.py b/tests/unit_tests/models/searcher/test_webrouter_search.py new file mode 100644 index 00000000..7f2c6c5d --- /dev/null +++ b/tests/unit_tests/models/searcher/test_webrouter_search.py @@ -0,0 +1,77 @@ +"""Tests for the WebRouter web searcher.""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace + +import pytest +from fastapi import HTTPException + +from graphgen.models import WebRouterSearch + + +class FakeRouter: + instances = [] + + def __init__(self, provider, **kwargs): + self.provider = provider + self.kwargs = kwargs + self.search_calls = [] + FakeRouter.instances.append(self) + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def search(self, query, **kwargs): + self.search_calls.append((query, kwargs)) + if query == "fail": + raise RuntimeError("all backends failed") + results = [ + SimpleNamespace(title="A", url="https://a.example", description="a", content=None), + SimpleNamespace(title=None, url="https://b.example", description=None, content="b"), + SimpleNamespace(title="C", url="https://c.example", description="c", content=None), + ] + return SimpleNamespace(results=results[: kwargs["max_results"]]) + + +@pytest.fixture(name="router") +def fixture_router(monkeypatch): + FakeRouter.instances = [] + monkeypatch.setitem(sys.modules, "web_router", SimpleNamespace(WebRouter=FakeRouter)) + return FakeRouter + + +def test_webrouter_search_is_keyless_by_default(router): + results = WebRouterSearch().search("query", num_results=2) + + assert results == [ + {"title": "A", "link": "https://a.example", "snippet": "a"}, + {"title": "", "link": "https://b.example", "snippet": "b"}, + ] + instance = router.instances[0] + assert instance.provider == "auto" + assert instance.kwargs == {"provider_config": {}, "use_environment": False} + assert instance.search_calls == [("query", {"max_results": 2, "data_apis": False})] + + +def test_webrouter_search_passes_key_to_named_backend(router): + WebRouterSearch(provider="brave", api_key="key").search("query") + + instance = router.instances[0] + assert instance.provider == "brave" + assert instance.kwargs["provider_config"] == {"brave": {"api_key": "key"}} + assert instance.kwargs["use_environment"] is False + + +def test_webrouter_search_needs_backend_name_with_key(): + with pytest.raises(ValueError): + WebRouterSearch(api_key="key") + + +def test_webrouter_search_raises_on_engine_error(router): + with pytest.raises(HTTPException): + WebRouterSearch().search("fail")