Files
DeepTutor/deeptutor/services/search/base.py
Bingxi Zhao (Frank) f4f2a73b2a feat(search): rebuild the search provider layer and add six providers
Two pieces of work land together because the second is built on the
first: the provider layer was consolidated onto one spec table, then six
new providers were registered against it.

Layer overhaul
- Converge seven separate provider lists (backend registry, runtime
  config, settings router, CLI wizard, frontend catalog, i18n, tests)
  onto a single SEARCH_PROVIDERS spec table; every consumer derives from
  it instead of keeping its own copy.
- Fix three silent defects: serper's `num` never reached the API (it was
  swallowed by **kwargs, so max_results did nothing), serper dropped its
  proxies, and jina had no result-count limit at all.
- A runtime failure (rate limit, timeout, unreachable network) no longer
  fails the whole turn. The request walks the user's other credentialed
  search profiles and finally DuckDuckGo, recording the downgrade under
  a top-level `search_fallback` key so the trace shows what happened.
- Drop three provider modules that were never registered (exa, baidu,
  openrouter). They stay in the deprecated list, so a stale config reads
  as outdated rather than as a misspelled name.

Six new providers
doubao, bocha, zhipu, firecrawl, qianfan, aliyun_iqs — selectable under
Settings > Catalog > Search with their credential fields derived from the
spec table, and offered by `deeptutor init`. All six set
`soft_fallback=False`: five are China-hosted and the DuckDuckGo fallback
is unreachable on those networks, so a missing API key has to fail
loudly instead of silently timing out somewhere else.

Baidu returns as `qianfan` on the official Qianfan API; the old `baidu`
key stays deprecated.
2026-08-13 16:41:39 +08:00

90 lines
2.9 KiB
Python

"""
Web Search Base Provider - Abstract base class for all search providers
This module defines the BaseSearchProvider class that all search providers must inherit from.
Providers read credentials from data/user/settings/model_catalog.json.
"""
from abc import ABC, abstractmethod
import logging
from typing import Any
from deeptutor.services.config import search_provider_credentials
from .types import WebSearchResponse
# Legacy name retained for provider metadata only.
SEARCH_API_KEY_ENV = "SEARCH_API_KEY"
class BaseSearchProvider(ABC):
"""Abstract base class for search providers.
Providers use the active Search profile from Settings > Catalog.
Each provider has its own BASE_URL defined as a class constant.
"""
name: str = "base"
display_name: str = "Base Provider"
description: str = ""
requires_api_key: bool = True
supports_answer: bool = False # Whether provider generates LLM answers
BASE_URL: str = "" # Each provider defines its own endpoint
API_KEY_ENV_VARS: tuple[str, ...] = (SEARCH_API_KEY_ENV,)
def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:
"""
Initialize the provider.
Args:
api_key: API key for the provider. If not provided, use the active Search profile.
**kwargs: Additional configuration options.
"""
self.logger = logging.getLogger(__name__)
self.api_key = api_key or self._get_api_key()
self.config = kwargs
self.proxy = kwargs.get("proxy")
def _get_api_key(self) -> str:
"""Get the API key from this provider's own search profile.
Looked up by provider rather than off the active profile, so a provider
that is configured but not currently active still finds its own key
instead of borrowing another vendor's.
"""
key, _ = search_provider_credentials(self.name)
if self.requires_api_key and not key:
raise ValueError(f"{self.name} requires an api_key in Settings > Catalog > Search.")
return key
@abstractmethod
def search(self, query: str, **kwargs: Any) -> WebSearchResponse:
"""
Execute search and return standardized response.
Args:
query: The search query.
**kwargs: Provider-specific options.
Returns:
WebSearchResponse: Standardized search response.
"""
pass
def is_available(self) -> bool:
"""
Check if provider is available (dependencies installed, API key set).
Returns:
bool: True if provider is available, False otherwise.
"""
try:
if self.requires_api_key and not self.api_key:
return False
return True
except (ValueError, ImportError):
return False
__all__ = ["BaseSearchProvider", "SEARCH_API_KEY_ENV"]