Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(search): rebuild the search provider layer and add six providers

Bingxi Zhao (Frank)f4f2a73b2a1d
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 204cc2646..0e50dc506 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -395,8 +395,10 @@ def _codex_http_exception(error: CodexAuthError) -> HTTPException:
def _provider_choices() -> dict[str, list[dict[str, Any]]]:
"""Build dropdown options for provider selection, keyed by service type."""
from deeptutor.services.config.provider_runtime import (
+ DEPRECATED_SEARCH_PROVIDERS,
EMBEDDING_PROVIDERS,
IMAGEGEN_PROVIDERS,
+ SEARCH_PROVIDERS,
STT_PROVIDERS,
TTS_PROVIDERS,
VIDEOGEN_PROVIDERS,
@@ -434,15 +436,36 @@ def _provider_choices() -> dict[str, list[dict[str, Any]]]:
],
key=lambda p: p["label"].lower(),
)
+ # Derived from SEARCH_PROVIDERS so the dropdown, the connection-field form
+ # and the provider warnings the web app renders all follow the backend spec
+ # table. No search provider ships a default base_url — only SearXNG takes
+ # one, and it is the user's own instance.
search = [
- {"value": "none", "label": "None", "base_url": ""},
- {"value": "brave", "label": "Brave", "base_url": ""},
- {"value": "tavily", "label": "Tavily", "base_url": ""},
- {"value": "jina", "label": "Jina", "base_url": ""},
- {"value": "searxng", "label": "SearXNG", "base_url": ""},
- {"value": "duckduckgo", "label": "DuckDuckGo", "base_url": ""},
- {"value": "perplexity", "label": "Perplexity", "base_url": ""},
- {"value": "serper", "label": "Serper", "base_url": ""},
+ {
+ "value": name,
+ "label": spec.label,
+ "base_url": "",
+ "requires_api_key": spec.requires_api_key,
+ "requires_base_url": spec.requires_base_url,
+ "soft_fallback": spec.soft_fallback,
+ "status": "supported",
+ }
+ for name, spec in SEARCH_PROVIDERS.items()
+ ]
+ # Retired providers ride along marked rather than offered, so a stale
+ # catalog can be told apart from a typo without a second name table in the
+ # web app. The dropdown filters them out; only the warning text uses them.
+ search += [
+ {
+ "value": name,
+ "label": name,
+ "base_url": "",
+ "requires_api_key": False,
+ "requires_base_url": False,
+ "soft_fallback": True,
+ "status": "deprecated",
+ }
+ for name in sorted(DEPRECATED_SEARCH_PROVIDERS)
]
tts = sorted(
[
diff --git a/deeptutor/api/routers/system.py b/deeptutor/api/routers/system.py
index f83b06bdc..e92290c89 100644
--- a/deeptutor/api/routers/system.py
+++ b/deeptutor/api/routers/system.py
@@ -12,7 +12,10 @@ from pydantic import BaseModel
from deeptutor.multi_user.context import get_current_user
from deeptutor.runtime import memory_probe
-from deeptutor.services.config import resolve_search_runtime_config
+from deeptutor.services.config import (
+ resolve_search_runtime_config,
+ supported_search_providers_hint,
+)
from deeptutor.services.embedding import get_embedding_client, get_embedding_config
from deeptutor.services.llm import complete as llm_complete
from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs
@@ -110,13 +113,13 @@ async def get_system_status():
result["search"]["status"] = "unsupported"
result["search"]["error"] = (
f"{search_config.requested_provider} is deprecated/unsupported. "
- "Switch to brave/tavily/jina/searxng/duckduckgo/perplexity."
+ f"Switch to {supported_search_providers_hint()}."
)
elif search_config.deprecated_provider:
result["search"]["status"] = "deprecated"
result["search"]["error"] = (
f"{search_config.requested_provider} is deprecated. "
- "Switch to brave/tavily/jina/searxng/duckduckgo/perplexity."
+ f"Switch to {supported_search_providers_hint()}."
)
elif search_config.missing_credentials:
result["search"]["status"] = "not_configured"
@@ -344,7 +347,7 @@ async def test_search_connection():
message=(
f"Search provider `{search_config.requested_provider}` is deprecated/unsupported."
),
- error="Switch to brave/tavily/jina/searxng/duckduckgo/perplexity",
+ error=f"Switch to {supported_search_providers_hint()}",
)
if search_config.missing_credentials:
return TestResponse(
diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.py
index b2167c6c3..c8953d0e5 100644
--- a/deeptutor/services/config/__init__.py
+++ b/deeptutor/services/config/__init__.py
@@ -64,6 +64,14 @@ __all__ = [
"NANOBOT_LLM_PROVIDERS",
"SUPPORTED_SEARCH_PROVIDERS",
"DEPRECATED_SEARCH_PROVIDERS",
+ "SEARCH_PROVIDERS",
+ "SEARCH_FALLBACK_PROVIDER",
+ "SearchProviderSpec",
+ "search_provider_spec",
+ "search_provider_credentials",
+ "search_missing_credential",
+ "search_fallback_candidates",
+ "supported_search_providers_hint",
# From knowledge_base_config.py
"KnowledgeBaseConfigService",
"get_kb_config_service",
@@ -95,14 +103,22 @@ def __getattr__(name: str):
if name in {
"DEPRECATED_SEARCH_PROVIDERS",
"NANOBOT_LLM_PROVIDERS",
+ "SEARCH_FALLBACK_PROVIDER",
+ "SEARCH_PROVIDERS",
"SUPPORTED_SEARCH_PROVIDERS",
"ResolvedLLMConfig",
"ResolvedEmbeddingConfig",
"ResolvedSearchConfig",
+ "SearchProviderSpec",
"resolve_embedding_runtime_config",
"resolve_llm_runtime_config",
"resolve_search_runtime_config",
+ "search_fallback_candidates",
+ "search_missing_credential",
+ "search_provider_credentials",
+ "search_provider_spec",
"search_provider_state",
+ "supported_search_providers_hint",
}:
provider_runtime = importlib.import_module(f"{__name__}.provider_runtime")
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 5e1b2665c..d47377b7d 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -39,17 +39,87 @@ from .embedding_endpoint import (
from .loader import load_config_with_main
from .model_catalog import ModelCatalogService, get_model_catalog_service
-SUPPORTED_SEARCH_PROVIDERS = {
- "brave",
- "tavily",
- "jina",
- "searxng",
- "duckduckgo",
- "perplexity",
- "serper",
- "none",
+
+@dataclass(frozen=True)
+class SearchProviderSpec:
+ """Single web-search-provider metadata entry.
+
+ This table is the ONE place that decides what a search provider is: which
+ connection fields it consumes (``requires_api_key`` / ``requires_base_url``),
+ what happens when one is missing (``soft_fallback``), and whether it writes
+ its own answer or needs :mod:`deeptutor.services.search.consolidation` to
+ synthesize one (``supports_answer``).
+
+ ``soft_fallback=False`` marks the paid providers: when their credentials are
+ missing we raise instead of quietly running the query through a different
+ search engine, so a configured-and-billed provider never turns into
+ DuckDuckGo behind the user's back. It also marks the China-hosted providers,
+ where the fallback is not merely surprising but unreachable — DuckDuckGo is
+ blocked on the networks those are chosen for, so a silent fallback would
+ turn "no API key" into a mystery timeout.
+
+ The provider registry (``deeptutor/services/search/providers``), the
+ Settings dropdown (``deeptutor/api/routers/settings.py``) and the web
+ connection-field form all derive from this table — keep new providers here
+ and they show up everywhere at once.
+ """
+
+ label: str
+ requires_api_key: bool = False
+ requires_base_url: bool = False
+ soft_fallback: bool = True
+ supports_answer: bool = False
+
+
+# Insertion order is the Settings dropdown order.
+SEARCH_PROVIDERS: dict[str, SearchProviderSpec] = {
+ "none": SearchProviderSpec(label="None"),
+ "brave": SearchProviderSpec(label="Brave", requires_api_key=True),
+ "tavily": SearchProviderSpec(label="Tavily", requires_api_key=True, supports_answer=True),
+ "jina": SearchProviderSpec(label="Jina", requires_api_key=True),
+ "searxng": SearchProviderSpec(label="SearXNG", requires_base_url=True),
+ "duckduckgo": SearchProviderSpec(label="DuckDuckGo"),
+ "perplexity": SearchProviderSpec(
+ label="Perplexity",
+ requires_api_key=True,
+ soft_fallback=False,
+ supports_answer=True,
+ ),
+ "serper": SearchProviderSpec(label="Serper", requires_api_key=True, soft_fallback=False),
+ "firecrawl": SearchProviderSpec(label="Firecrawl", requires_api_key=True, soft_fallback=False),
+ # China-hosted engines. Doubao is the one that writes its own answer: Ark
+ # exposes web search only as a tool on a Doubao model, never standalone.
+ "doubao": SearchProviderSpec(
+ label="Doubao",
+ requires_api_key=True,
+ soft_fallback=False,
+ supports_answer=True,
+ ),
+ "bocha": SearchProviderSpec(label="Bocha", requires_api_key=True, soft_fallback=False),
+ "zhipu": SearchProviderSpec(label="Zhipu", requires_api_key=True, soft_fallback=False),
+ "qianfan": SearchProviderSpec(
+ label="Baidu Qianfan", requires_api_key=True, soft_fallback=False
+ ),
+ "aliyun_iqs": SearchProviderSpec(
+ label="Aliyun IQS", requires_api_key=True, soft_fallback=False
+ ),
}
-DEPRECATED_SEARCH_PROVIDERS = {"exa", "baidu", "openrouter"}
+
+# The credential-free provider every soft fallback lands on.
+SEARCH_FALLBACK_PROVIDER = "duckduckgo"
+
+SUPPORTED_SEARCH_PROVIDERS = frozenset(SEARCH_PROVIDERS)
+DEPRECATED_SEARCH_PROVIDERS = frozenset({"exa", "baidu", "openrouter"})
+
+
+def search_provider_spec(provider: str | None) -> SearchProviderSpec | None:
+ """Look up a provider's spec, or ``None`` for unknown/deprecated names."""
+ return SEARCH_PROVIDERS.get((provider or "").strip().lower())
+
+
+def supported_search_providers_hint() -> str:
+ """Human-readable provider list for error messages and CLI output."""
+ return ", ".join(name for name in SEARCH_PROVIDERS if name != "none")
LLM_LOCALHOST_PROVIDERS = ("ollama", "vllm")
@@ -1100,6 +1170,82 @@ def _resolve_search_max_results(catalog: dict[str, Any], default: int = 5) -> in
return default
+def _search_profiles(catalog: dict[str, Any]) -> list[dict[str, Any]]:
+ profiles = catalog.get("services", {}).get("search", {}).get("profiles", [])
+ return [profile for profile in profiles if isinstance(profile, dict)]
+
+
+def search_provider_credentials(
+ provider: str,
+ catalog: dict[str, Any] | None = None,
+ *,
+ service: ModelCatalogService | None = None,
+) -> tuple[str, str]:
+ """Return ``(api_key, base_url)`` from the search profile targeting *provider*.
+
+ Search profiles are a list, so several providers can stay configured side by
+ side with only one active. Looking credentials up by provider is what keeps a
+ non-active provider from reaching for whatever key the active profile holds
+ (which used to send e.g. a Brave key to Tavily). The active profile wins when
+ it matches; otherwise the first profile naming the provider supplies them.
+ """
+ name = (provider or "").strip().lower()
+ if not name:
+ return "", ""
+ catalog_service = service or get_model_catalog_service()
+ loaded = _load_catalog(catalog)
+ active = catalog_service.get_active_profile(loaded, "search") or {}
+ for profile in (active, *_search_profiles(loaded)):
+ if _as_str(profile.get("provider")).lower() == name:
+ return _as_str(profile.get("api_key")), _as_str(profile.get("base_url"))
+ return "", ""
+
+
+def search_missing_credential(provider: str, api_key: str, base_url: str) -> str | None:
+ """Name the connection field *provider* needs but does not have."""
+ spec = search_provider_spec(provider)
+ if spec is None:
+ return None
+ if spec.requires_api_key and not api_key:
+ return "api_key"
+ if spec.requires_base_url and not base_url:
+ return "base_url"
+ return None
+
+
+def search_fallback_candidates(
+ requested: str,
+ catalog: dict[str, Any] | None = None,
+ *,
+ service: ModelCatalogService | None = None,
+) -> list[str]:
+ """Ordered providers to try after *requested* fails at runtime.
+
+ A rate-limited or unreachable search engine should cost the query its first
+ choice, not the whole turn. Candidates are the user's other fully-configured
+ search profiles (they opted into those providers by configuring them), then
+ the credential-free fallback. Providers whose credentials are missing never
+ enter the chain, and ``none`` — an explicit "search is off" — is excluded.
+ """
+ name = (requested or "").strip().lower()
+ catalog_service = service or get_model_catalog_service()
+ loaded = _load_catalog(catalog)
+ candidates: list[str] = []
+ for profile in _search_profiles(loaded):
+ provider = _as_str(profile.get("provider")).lower()
+ spec = search_provider_spec(provider)
+ if spec is None or provider in {"none", name} or provider in candidates:
+ continue
+ if search_missing_credential(
+ provider, _as_str(profile.get("api_key")), _as_str(profile.get("base_url"))
+ ):
+ continue
+ candidates.append(provider)
+ if name != SEARCH_FALLBACK_PROVIDER and SEARCH_FALLBACK_PROVIDER not in candidates:
+ candidates.append(SEARCH_FALLBACK_PROVIDER)
+ return candidates
+
+
def resolve_search_runtime_config(
catalog: dict[str, Any] | None = None,
*,
@@ -1110,17 +1256,25 @@ def resolve_search_runtime_config(
loaded = _load_catalog(catalog)
profile = catalog_service.get_active_profile(loaded, "search") or {}
- requested_provider = (_as_str(profile.get("provider")) or "duckduckgo").lower()
+ requested_provider = (_as_str(profile.get("provider")) or SEARCH_FALLBACK_PROVIDER).lower()
provider = requested_provider
api_key = _as_str(profile.get("api_key"))
base_url = _as_str(profile.get("base_url"))
proxy = _as_str(profile.get("proxy")) or None
max_results = _resolve_search_max_results(loaded)
- deprecated = provider in DEPRECATED_SEARCH_PROVIDERS
- unsupported = provider not in SUPPORTED_SEARCH_PROVIDERS
- fallback_reason: str | None = None
- missing_credentials = False
+ spec = search_provider_spec(provider)
+ if spec is None:
+ return ResolvedSearchConfig(
+ provider=provider,
+ requested_provider=requested_provider,
+ api_key=api_key,
+ base_url=base_url,
+ max_results=max_results,
+ proxy=proxy,
+ unsupported_provider=True,
+ deprecated_provider=provider in DEPRECATED_SEARCH_PROVIDERS,
+ )
if provider == "none":
return ResolvedSearchConfig(
@@ -1132,28 +1286,13 @@ def resolve_search_runtime_config(
proxy=proxy,
)
- if provider in {"perplexity", "serper"} and not api_key:
- missing_credentials = True
-
- if unsupported:
- return ResolvedSearchConfig(
- provider=provider,
- requested_provider=requested_provider,
- api_key=api_key,
- base_url=base_url,
- max_results=max_results,
- proxy=proxy,
- unsupported_provider=True,
- deprecated_provider=deprecated,
- missing_credentials=missing_credentials,
+ missing = search_missing_credential(provider, api_key, base_url)
+ fallback_reason: str | None = None
+ if missing and spec.soft_fallback:
+ fallback_reason = (
+ f"{provider} requires {missing}, falling back to {SEARCH_FALLBACK_PROVIDER}"
)
-
- if provider in {"brave", "tavily", "jina"} and not api_key:
- fallback_reason = f"{provider} requires api_key, falling back to duckduckgo"
- provider = "duckduckgo"
- elif provider == "searxng" and not base_url:
- fallback_reason = "searxng requires base_url, falling back to duckduckgo"
- provider = "duckduckgo"
+ provider = SEARCH_FALLBACK_PROVIDER
return ResolvedSearchConfig(
provider=provider,
@@ -1163,8 +1302,8 @@ def resolve_search_runtime_config(
max_results=max_results,
proxy=proxy,
unsupported_provider=False,
- deprecated_provider=deprecated,
- missing_credentials=missing_credentials,
+ deprecated_provider=False,
+ missing_credentials=bool(missing) and not spec.soft_fallback,
fallback_reason=fallback_reason,
)
@@ -1184,6 +1323,14 @@ def search_provider_state(provider: str | None) -> str:
__all__ = [
"SUPPORTED_SEARCH_PROVIDERS",
"DEPRECATED_SEARCH_PROVIDERS",
+ "SEARCH_PROVIDERS",
+ "SEARCH_FALLBACK_PROVIDER",
+ "SearchProviderSpec",
+ "search_provider_spec",
+ "search_provider_credentials",
+ "search_missing_credential",
+ "search_fallback_candidates",
+ "supported_search_providers_hint",
"NANOBOT_LLM_PROVIDERS",
"EmbeddingProviderSpec",
"EMBEDDING_PROVIDERS",
diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py
index 2018f081b..4aba62406 100644
--- a/deeptutor/services/config/test_runner.py
+++ b/deeptutor/services/config/test_runner.py
@@ -16,6 +16,7 @@ from .provider_runtime import (
resolve_embedding_runtime_config,
resolve_llm_runtime_config,
resolve_search_runtime_config,
+ supported_search_providers_hint,
)
@@ -428,7 +429,7 @@ class ConfigTestRunner:
if resolved.unsupported_provider:
raise ValueError(
f"Search provider `{resolved.requested_provider}` is deprecated/unsupported. "
- "Switch to none/brave/tavily/jina/searxng/duckduckgo/perplexity/serper."
+ f"Switch to none/{supported_search_providers_hint()}."
)
if resolved.missing_credentials:
raise ValueError(
diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py
index a21920aef..4b6b012cf 100644
--- a/deeptutor/services/search/__init__.py
+++ b/deeptutor/services/search/__init__.py
@@ -11,9 +11,16 @@ from typing import Any
from deeptutor.services.config import (
DEPRECATED_SEARCH_PROVIDERS,
PROJECT_ROOT,
+ SEARCH_FALLBACK_PROVIDER,
SUPPORTED_SEARCH_PROVIDERS,
+ ResolvedSearchConfig,
load_config_with_main,
resolve_search_runtime_config,
+ search_fallback_candidates,
+ search_missing_credential,
+ search_provider_credentials,
+ search_provider_spec,
+ supported_search_providers_hint,
)
from .base import SEARCH_API_KEY_ENV, BaseSearchProvider
@@ -51,8 +58,16 @@ def _save_results(result: dict[str, Any], output_dir: str, provider: str) -> str
return str(file_path)
-def _resolve_provider_key(provider_name: str, default_api_key: str) -> str:
- return default_api_key
+def _credentials_for(provider_name: str, resolved: ResolvedSearchConfig) -> tuple[str, str]:
+ """Return ``(api_key, base_url)`` to run *provider_name* with.
+
+ The resolved config already carries the active profile's credentials; any
+ other provider gets its own profile's, so switching providers can't send one
+ vendor's key to another.
+ """
+ if provider_name in {resolved.provider, resolved.requested_provider}:
+ return resolved.api_key, resolved.base_url
+ return search_provider_credentials(provider_name)
def _assert_provider_supported(provider_name: str) -> None:
@@ -61,15 +76,38 @@ def _assert_provider_supported(provider_name: str) -> None:
if provider_name in _DEPRECATED_UNSUPPORTED:
raise ValueError(
f"Search provider `{provider_name}` is deprecated/unsupported. "
- "Please switch to brave, tavily, jina, searxng, duckduckgo, perplexity, or serper."
+ f"Please switch to {supported_search_providers_hint()}."
)
if provider_name not in SUPPORTED_SEARCH_PROVIDERS:
- allowed = ", ".join(sorted(SUPPORTED_SEARCH_PROVIDERS))
raise ValueError(
- f"Unknown search provider `{provider_name}`. Supported providers: {allowed}"
+ f"Unknown search provider `{provider_name}`. "
+ f"Supported providers: {supported_search_providers_hint()}."
)
+def _disabled_result(query: str, provider: str) -> dict[str, Any]:
+ return {
+ "timestamp": datetime.now().isoformat(),
+ "query": query,
+ "answer": "Web search is disabled.",
+ "citations": [],
+ "search_results": [],
+ "provider": provider,
+ }
+
+
+def _run_provider(
+ provider_name: str,
+ query: str,
+ provider_kwargs: dict[str, Any],
+) -> tuple[WebSearchResponse, bool]:
+ """Run one query through *provider_name*, also reporting answer support."""
+ search_provider = get_provider(provider_name, **provider_kwargs)
+ _logger.info(f"[{search_provider.name}] Searching: {query[:50]}...")
+ response = search_provider.search(query, **provider_kwargs)
+ return response, search_provider.supports_answer
+
+
def web_search(
query: str,
output_dir: str | None = None,
@@ -88,64 +126,74 @@ def web_search(
config = _get_web_search_config()
if not config.get("enabled", True):
_logger.warning("Web search is disabled in config")
- return {
- "timestamp": datetime.now().isoformat(),
- "query": query,
- "answer": "Web search is disabled.",
- "citations": [],
- "search_results": [],
- "provider": "disabled",
- }
+ return _disabled_result(query, "disabled")
resolved = resolve_search_runtime_config()
provider_name = (provider or resolved.provider).strip().lower()
_assert_provider_supported(provider_name)
if provider_name == "none":
- return {
- "timestamp": datetime.now().isoformat(),
- "query": query,
- "answer": "Web search is disabled.",
- "citations": [],
- "search_results": [],
- "provider": "none",
- }
-
- if provider_name in {"brave", "tavily", "jina"}:
- api_key = _resolve_provider_key(provider_name, resolved.api_key)
- if not api_key:
- _logger.warning(f"{provider_name} missing API key, falling back to duckduckgo.")
- provider_name = "duckduckgo"
- else:
- provider_kwargs.setdefault("api_key", api_key)
- elif provider_name in {"perplexity", "serper"}:
- api_key = _resolve_provider_key(provider_name, resolved.api_key)
- if not api_key:
+ return _disabled_result(query, "none")
+
+ api_key, base_url = _credentials_for(provider_name, resolved)
+ base_url = provider_kwargs.get("base_url") or base_url
+ missing = search_missing_credential(provider_name, api_key, base_url)
+ if missing:
+ spec = search_provider_spec(provider_name)
+ if spec is not None and not spec.soft_fallback:
raise ValueError(
- f"{provider_name} requires api_key (profile.api_key in Settings > Catalog)."
+ f"{provider_name} requires {missing} (profile.{missing} in Settings > Catalog)."
)
- provider_kwargs.setdefault("api_key", api_key)
- elif provider_name == "searxng":
- base_url = provider_kwargs.get("base_url") or resolved.base_url
- if not base_url:
- _logger.warning("searxng missing base_url, falling back to duckduckgo.")
- provider_name = "duckduckgo"
- else:
- provider_kwargs.setdefault("base_url", base_url)
+ _logger.warning(
+ f"{provider_name} missing {missing}, falling back to {SEARCH_FALLBACK_PROVIDER}."
+ )
+ provider_name = SEARCH_FALLBACK_PROVIDER
+ api_key, base_url = _credentials_for(provider_name, resolved)
+ if api_key:
+ provider_kwargs.setdefault("api_key", api_key)
+ if base_url:
+ provider_kwargs.setdefault("base_url", base_url)
provider_kwargs.setdefault("max_results", resolved.max_results)
if resolved.proxy and "proxy" not in provider_kwargs:
provider_kwargs["proxy"] = resolved.proxy
- search_provider = get_provider(provider_name, **provider_kwargs)
- _logger.info(f"[{search_provider.name}] Searching: {query[:50]}...")
- try:
- response = search_provider.search(query, **provider_kwargs)
- except Exception as exc:
- _logger.error(f"[{search_provider.name}] Search failed: {exc}")
- raise Exception(f"{search_provider.name} search failed: {exc}") from exc
+ # A rate-limited or unreachable engine costs the query its first choice, not
+ # the whole turn: fall through the user's other configured search profiles
+ # and finally the credential-free provider, recording what was skipped.
+ attempts: list[str] = [provider_name, *search_fallback_candidates(provider_name)]
+ failures: list[str] = []
+ response: WebSearchResponse | None = None
+ supports_answer = False
+ for candidate in attempts:
+ candidate_kwargs = dict(provider_kwargs)
+ if candidate != provider_name:
+ candidate_key, candidate_base_url = _credentials_for(candidate, resolved)
+ candidate_kwargs.pop("api_key", None)
+ candidate_kwargs.pop("base_url", None)
+ if candidate_key:
+ candidate_kwargs["api_key"] = candidate_key
+ if candidate_base_url:
+ candidate_kwargs["base_url"] = candidate_base_url
+ try:
+ response, supports_answer = _run_provider(candidate, query, candidate_kwargs)
+ except Exception as exc:
+ _logger.error(f"[{candidate}] Search failed: {exc}")
+ failures.append(f"{candidate}: {exc}")
+ continue
+ if candidate != provider_name:
+ _logger.warning(f"Search fell back from {provider_name} to {candidate}.")
+ response.metadata["search_fallback"] = {
+ "requested": provider_name,
+ "used": candidate,
+ "failures": failures,
+ }
+ provider_name = candidate
+ break
+ if response is None:
+ raise Exception("web search failed: " + "; ".join(failures))
# Auto-consolidate for providers that don't generate their own answers.
- if not search_provider.supports_answer:
+ if not supports_answer:
if consolidation_custom_template is None:
consolidation_custom_template = config.get("consolidation_template") or None
use_llm = bool(consolidation_llm_model)
diff --git a/deeptutor/services/search/base.py b/deeptutor/services/search/base.py
index 4475c78ff..c6e7354ae 100644
--- a/deeptutor/services/search/base.py
+++ b/deeptutor/services/search/base.py
@@ -9,7 +9,7 @@ from abc import ABC, abstractmethod
import logging
from typing import Any
-from deeptutor.services.config import resolve_search_runtime_config
+from deeptutor.services.config import search_provider_credentials
from .types import WebSearchResponse
@@ -46,11 +46,13 @@ class BaseSearchProvider(ABC):
self.proxy = kwargs.get("proxy")
def _get_api_key(self) -> str:
- """Get API key from the active search profile."""
- key = ""
- resolved = resolve_search_runtime_config()
- if resolved.provider == self.name or resolved.requested_provider == self.name:
- key = resolved.api_key
+ """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
@@ -77,10 +79,8 @@ class BaseSearchProvider(ABC):
bool: True if provider is available, False otherwise.
"""
try:
- if self.requires_api_key:
- key = self.api_key or resolve_search_runtime_config().api_key
- if not key:
- return False
+ if self.requires_api_key and not self.api_key:
+ return False
return True
except (ValueError, ImportError):
return False
diff --git a/deeptutor/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.py
index 72794272e..ca09b25c2 100644
--- a/deeptutor/services/search/providers/__init__.py
+++ b/deeptutor/services/search/providers/__init__.py
@@ -6,13 +6,21 @@ This module manages the registration and retrieval of search providers.
from typing import Type
+from deeptutor.services.config import (
+ DEPRECATED_SEARCH_PROVIDERS,
+ SEARCH_FALLBACK_PROVIDER,
+ search_missing_credential,
+ search_provider_credentials,
+ search_provider_spec,
+ supported_search_providers_hint,
+)
+
from ..base import BaseSearchProvider
_PROVIDERS: dict[str, Type[BaseSearchProvider]] = {}
_DEPRECATED_UNSUPPORTED: dict[str, str] = {
- "exa": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity/serper.",
- "baidu": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity/serper.",
- "openrouter": "Deprecated; use brave/tavily/jina/searxng/duckduckgo/perplexity/serper.",
+ name: f"Deprecated; use {supported_search_providers_hint()}."
+ for name in sorted(DEPRECATED_SEARCH_PROVIDERS)
}
@@ -20,6 +28,13 @@ def register_provider(name: str):
"""
Decorator to register a provider.
+ Metadata that the rest of the app reads off the class — display name,
+ which credentials it needs, whether it writes its own answer — is stamped
+ on from ``SEARCH_PROVIDERS`` so the spec table stays the single source of
+ truth. A name absent from that table (a deprecated provider, or one that
+ was never wired up) stays importable but never enters the registry, so it
+ cannot be selected.
+
Args:
name: Name to register the provider under.
@@ -29,11 +44,14 @@ def register_provider(name: str):
def decorator(cls: Type[BaseSearchProvider]):
key = name.lower()
- if key in _DEPRECATED_UNSUPPORTED:
- cls.name = key
+ cls.name = key
+ spec = search_provider_spec(key)
+ if spec is None:
return cls
+ cls.display_name = spec.label
+ cls.requires_api_key = spec.requires_api_key
+ cls.supports_answer = spec.supports_answer
_PROVIDERS[key] = cls
- cls.name = key
return cls
return decorator
@@ -78,31 +96,31 @@ def list_providers() -> list[str]:
def get_available_providers() -> list[str]:
"""
- List providers that are currently available (have API keys set).
+ List providers that can run right now — either they need no credentials, or
+ a configured search profile supplies the ones they do need.
Returns:
list[str]: Sorted list of available provider names.
"""
available = []
- for name, cls in _PROVIDERS.items():
- try:
- instance = cls()
- if instance.is_available():
- available.append(name)
- except Exception:
- pass
+ for name in _PROVIDERS:
+ api_key, base_url = search_provider_credentials(name)
+ if not search_missing_credential(name, api_key, base_url):
+ available.append(name)
return sorted(available)
def get_providers_info() -> list[dict]:
"""
- Get full provider info from class attributes for frontend display.
+ Get full provider info for frontend/CLI display.
Returns:
- list[dict]: List of provider info dicts with id, name, description, supports_answer
+ list[dict]: List of provider info dicts with id, name, description,
+ supports_answer, and which connection fields the provider needs.
"""
providers_info = []
for provider_id, cls in sorted(_PROVIDERS.items()):
+ spec = search_provider_spec(provider_id)
providers_info.append(
{
"id": provider_id,
@@ -110,6 +128,7 @@ def get_providers_info() -> list[dict]:
"description": cls.description,
"supports_answer": cls.supports_answer,
"requires_api_key": cls.requires_api_key,
+ "requires_base_url": bool(spec and spec.requires_base_url),
"status": "supported",
}
)
@@ -121,6 +140,7 @@ def get_providers_info() -> list[dict]:
"description": reason,
"supports_answer": False,
"requires_api_key": False,
+ "requires_base_url": False,
"status": "deprecated",
}
)
@@ -140,16 +160,46 @@ def get_default_provider(**kwargs) -> BaseSearchProvider:
from deeptutor.services.config import resolve_search_runtime_config
provider_name = resolve_search_runtime_config().provider.lower()
- if provider_name in _DEPRECATED_UNSUPPORTED:
- provider_name = "duckduckgo"
+ if provider_name not in _PROVIDERS and provider_name != "none":
+ # Stale config naming a retired provider still gets a working default;
+ # an explicit "none" keeps raising, since that means search is off.
+ provider_name = SEARCH_FALLBACK_PROVIDER
return get_provider(provider_name, **kwargs)
def _register_builtin_providers() -> None:
# Import for side effects (register_provider decorators).
- from . import brave, duckduckgo, jina, perplexity, searxng, serper, tavily
-
- _ = (brave, duckduckgo, jina, perplexity, searxng, serper, tavily)
+ from . import (
+ aliyun_iqs,
+ bocha,
+ brave,
+ doubao,
+ duckduckgo,
+ firecrawl,
+ jina,
+ perplexity,
+ qianfan,
+ searxng,
+ serper,
+ tavily,
+ zhipu,
+ )
+
+ _ = (
+ aliyun_iqs,
+ bocha,
+ brave,
+ doubao,
+ duckduckgo,
+ firecrawl,
+ jina,
+ perplexity,
+ qianfan,
+ searxng,
+ serper,
+ tavily,
+ zhipu,
+ )
_register_builtin_providers()
diff --git a/deeptutor/services/search/providers/aliyun_iqs.py b/deeptutor/services/search/providers/aliyun_iqs.py
new file mode 100644
index 000000000..19f738b5a
--- /dev/null
+++ b/deeptutor/services/search/providers/aliyun_iqs.py
@@ -0,0 +1,163 @@
+"""Aliyun IQS (信息查询服务) search provider.
+
+API: https://cloud-iqs.aliyuncs.com/search/genericSearch
+
+The unified HTTP entry point, which authenticates with a plain ``X-API-Key``
+header -- the OpenAPI-style host (``iqs.cn-zhangjiakou.aliyuncs.com``) wants
+AK/SK request signing and would drag in the Aliyun SDK for no gain.
+
+IQS returns page bodies and a rerank score alongside the usual SERP fields.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+_TIME_RANGE = ("NoLimit", "OneDay", "OneWeek", "OneMonth", "OneYear")
+# Vertical corpora the engine can bias toward.
+_INDUSTRY = ("finance", "law", "medical", "internet", "tax", "news_province", "news_center")
+# IQS always returns a fixed page of 10; there is no count parameter, so the
+# cap has to be applied here or every query hands the model 10 full page bodies.
+_PAGE_SIZE = 10
+
+
+def _publish_date(value: Any) -> str:
+ """Render IQS's millisecond epoch as an ISO date, or pass text through."""
+ if value in (None, "", 0):
+ return ""
+ try:
+ return datetime.fromtimestamp(int(value) / 1000).strftime("%Y-%m-%d")
+ except (TypeError, ValueError, OSError, OverflowError):
+ return str(value)
+
+
+@register_provider("aliyun_iqs")
+class AliyunIQSProvider(BaseSearchProvider):
+ """Aliyun IQS generic search provider."""
+
+ description = "Aliyun IQS search with rerank (阿里云)"
+ BASE_URL = "https://cloud-iqs.aliyuncs.com/search/genericSearch"
+ API_KEY_ENV_VARS = ("ALIYUN_IQS_API_KEY", "IQS_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ max_results: int = 5,
+ time_range: str = "NoLimit",
+ industry: str | None = None,
+ return_main_text: bool = True,
+ return_markdown_text: bool = False,
+ enable_rerank: bool = True,
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search Aliyun IQS.
+
+ Args:
+ query: Search query (1-500 chars; the engine prefers under 30).
+ max_results: Result cap. Applied client-side -- IQS has no count
+ parameter and always returns a page of 10.
+ time_range: One of ``NoLimit``, ``OneDay``, ``OneWeek``,
+ ``OneMonth``, ``OneYear``.
+ industry: Bias toward a vertical corpus; one of ``finance``,
+ ``law``, ``medical``, ``internet``, ``tax``, ``news_province``,
+ ``news_center``.
+ return_main_text: Include each page's body text.
+ return_markdown_text: Also include a markdown rendering of the body.
+ enable_rerank: Semantic rerank. On by default; turning it off saves
+ roughly 140ms at the cost of ordering quality.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options, including ``base_url`` and ``page``.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ if time_range not in _TIME_RANGE:
+ raise ValueError(
+ f"IQS time_range must be one of {list(_TIME_RANGE)}, got {time_range!r}."
+ )
+ if industry is not None and industry not in _INDUSTRY:
+ raise ValueError(f"IQS industry must be one of {list(_INDUSTRY)}, got {industry!r}.")
+
+ endpoint = str(kwargs.get("base_url") or self.BASE_URL)
+ params: dict[str, Any] = {
+ "query": query,
+ "timeRange": time_range,
+ "page": int(kwargs.get("page", 1)),
+ # requests serializes bools as "True"/"False"; the API wants lowercase.
+ "returnMainText": str(return_main_text).lower(),
+ "returnMarkdownText": str(return_markdown_text).lower(),
+ "enableRerank": str(enable_rerank).lower(),
+ }
+ if industry:
+ params["industry"] = industry
+
+ headers = {"X-API-Key": self.api_key, "Accept": "application/json"}
+ request_kwargs: dict[str, Any] = {"headers": headers, "params": params}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.get(endpoint, timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Aliyun IQS API error: {resp.status_code} - {resp.text}")
+
+ data = resp.json()
+ rows = (data.get("pageItems") or [])[: max(1, min(int(max_results), _PAGE_SIZE))]
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ for idx, row in enumerate(rows, 1):
+ title = str(row.get("title", "") or "")
+ url = str(row.get("link", "") or "")
+ snippet = str(row.get("snippet", "") or "")
+ content = str(row.get("markdownText") or row.get("mainText") or "")
+ page_map = row.get("pageMap") or {}
+ site = str(row.get("displayLink") or page_map.get("hostname") or "")
+ date = _publish_date(row.get("publishTime"))
+ search_results.append(
+ SearchResult(
+ title=title,
+ url=url,
+ snippet=snippet,
+ date=date,
+ source=site or "Aliyun IQS",
+ content=content,
+ score=float(row.get("score") or 0.0),
+ )
+ )
+ citations.append(
+ Citation(
+ id=idx,
+ reference=f"[{idx}]",
+ url=url,
+ title=title,
+ snippet=snippet,
+ date=date,
+ source=site or "Aliyun IQS",
+ content=content,
+ icon=str(page_map.get("hostLogo", "") or ""),
+ website=site,
+ )
+ )
+
+ info = data.get("searchInformation") or {}
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider="aliyun_iqs",
+ timestamp=datetime.now().isoformat(),
+ model="iqs-generic-search",
+ citations=citations,
+ search_results=search_results,
+ metadata={
+ "finish_reason": "stop",
+ "request_id": data.get("requestId", ""),
+ "total_results": info.get("total", 0),
+ },
+ )
diff --git a/deeptutor/services/search/providers/baidu.py b/deeptutor/services/search/providers/baidu.py
deleted file mode 100644
index 88b2493fa..000000000
--- a/deeptutor/services/search/providers/baidu.py
+++ /dev/null
@@ -1,188 +0,0 @@
-"""
-Baidu AI Search Provider
-
-API: https://qianfan.baidubce.com/v2/ai_search/chat/completions
-
-Features:
-- AI-powered search with ERNIE models
-- Deep search mode for comprehensive results
-- Corner markers for reference citations
-- Follow-up query suggestions
-- Recency filtering
-"""
-
-from datetime import datetime
-from typing import Any
-
-import requests
-
-from ..base import BaseSearchProvider
-from ..types import Citation, SearchResult, WebSearchResponse
-from . import register_provider
-
-
-@register_provider("baidu")
-class BaiduProvider(BaseSearchProvider):
- """Baidu AI Search provider"""
-
- display_name = "Baidu AI"
- description = "百度AI搜索 with ERNIE models"
- supports_answer = True
- BASE_URL = "https://qianfan.baidubce.com/v2/ai_search/chat/completions"
-
- def search(
- self,
- query: str,
- model: str = "ernie-4.5-turbo-32k",
- search_source: str = "baidu_search_v2",
- enable_deep_search: bool = False,
- enable_corner_markers: bool = True,
- enable_followup_queries: bool = False,
- temperature: float = 0.11,
- top_p: float = 0.55,
- search_mode: str = "auto",
- search_recency_filter: str | None = None,
- instruction: str = "",
- timeout: int = 120,
- **kwargs: Any,
- ) -> WebSearchResponse:
- """
- Perform intelligent search using Baidu AI Search API.
-
- Args:
- query: Search query.
- model: Model to use for generation (default: ernie-4.5-turbo-32k).
- search_source: Search engine version (baidu_search_v1 or baidu_search_v2).
- enable_deep_search: Enable deep search for more comprehensive results.
- enable_corner_markers: Enable corner markers for reference citations.
- enable_followup_queries: Enable follow-up query suggestions.
- temperature: Model sampling temperature (0, 1].
- top_p: Model sampling top_p (0, 1].
- search_mode: Search mode (auto, required, disabled).
- search_recency_filter: Filter by recency (week, month, semiyear, year).
- instruction: System instruction for response style.
- timeout: Request timeout in seconds.
- **kwargs: Additional options.
-
- Returns:
- WebSearchResponse: Standardized search response.
- """
- self.logger.debug(f"Calling Baidu API with model={model}, deep_search={enable_deep_search}")
- headers = {
- "Content-Type": "application/json",
- "Authorization": (
- f"Bearer {self.api_key}" if not self.api_key.startswith("Bearer ") else self.api_key
- ),
- }
-
- payload = {
- "messages": [{"role": "user", "content": query}],
- "model": model,
- "search_source": search_source,
- "stream": False,
- "enable_deep_search": enable_deep_search,
- "enable_corner_markers": enable_corner_markers,
- "enable_followup_queries": enable_followup_queries,
- "temperature": temperature,
- "top_p": top_p,
- "search_mode": search_mode,
- }
-
- if search_recency_filter:
- payload["search_recency_filter"] = search_recency_filter
-
- if instruction:
- payload["instruction"] = instruction
-
- response = requests.post(self.BASE_URL, headers=headers, json=payload, timeout=timeout)
-
- if response.status_code != 200:
- try:
- error_data = response.json() if response.text else {}
- except Exception:
- error_data = {}
- raise Exception(
- f"Baidu AI Search API error: {response.status_code} - "
- f"{error_data.get('message', response.text)}"
- )
-
- try:
- data = response.json()
- except Exception as e:
- raise Exception(f"Failed to parse Baidu API response: {e}")
-
- # Extract answer from response
- answer = ""
- finish_reason = ""
- if data.get("choices"):
- choice = data["choices"][0]
- if choice.get("message"):
- answer = choice["message"].get("content", "")
- finish_reason = choice.get("finish_reason", "")
-
- # Extract usage information
- usage_info: dict[str, Any] = {}
- if data.get("usage"):
- usage = data["usage"]
- usage_info = {
- "prompt_tokens": usage.get("prompt_tokens", 0),
- "completion_tokens": usage.get("completion_tokens", 0),
- "total_tokens": usage.get("total_tokens", 0),
- }
-
- # Extract references/citations
- citations: list[Citation] = []
- search_results: list[SearchResult] = []
-
- if data.get("references"):
- for i, ref in enumerate(data["references"], 1):
- citations.append(
- Citation(
- id=ref.get("id", i),
- reference=f"[{ref.get('id', i)}]",
- url=ref.get("url", ""),
- title=ref.get("title", ""),
- snippet=ref.get("content", ""),
- date=ref.get("date", ""),
- source=ref.get("web_anchor", ""),
- type=ref.get("type", "web"),
- icon=ref.get("icon", ""),
- website=ref.get("website", ""),
- web_anchor=ref.get("web_anchor", ""),
- )
- )
-
- search_results.append(
- SearchResult(
- title=ref.get("title", ""),
- url=ref.get("url", ""),
- snippet=ref.get("content", ""),
- date=ref.get("date", ""),
- source=ref.get("web_anchor", ""),
- )
- )
-
- # Build metadata
- metadata: dict[str, Any] = {
- "finish_reason": finish_reason,
- "is_safe": data.get("is_safe", True),
- "request_id": data.get("request_id", ""),
- }
-
- # Add follow-up queries if available
- if data.get("followup_queries"):
- metadata["followup_queries"] = data["followup_queries"]
-
- response_obj = WebSearchResponse(
- query=query,
- answer=answer,
- provider="baidu",
- timestamp=datetime.now().isoformat(),
- model=model,
- citations=citations,
- search_results=search_results,
- usage=usage_info,
- metadata=metadata,
- )
-
- return response_obj
diff --git a/deeptutor/services/search/providers/bocha.py b/deeptutor/services/search/providers/bocha.py
new file mode 100644
index 000000000..593754950
--- /dev/null
+++ b/deeptutor/services/search/providers/bocha.py
@@ -0,0 +1,132 @@
+"""Bocha (博查) search provider.
+
+API: https://api.bochaai.com/v1/web-search
+
+Bocha is a China-hosted search engine built for AI applications. Unlike the
+``/v1/ai-search`` sibling endpoint, ``/v1/web-search`` returns plain SERP rows
+with no model-written answer, so consolidation still supplies the answer.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+# Accepted by the API; anything else is rejected rather than ignored.
+_FRESHNESS = {"noLimit", "oneDay", "oneWeek", "oneMonth", "oneYear"}
+
+
+@register_provider("bocha")
+class BochaProvider(BaseSearchProvider):
+ """Bocha web search provider."""
+
+ description = "China-hosted SERP for AI apps (博查)"
+ BASE_URL = "https://api.bochaai.com/v1/web-search"
+ API_KEY_ENV_VARS = ("BOCHA_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ max_results: int = 5,
+ freshness: str = "noLimit",
+ summary: bool = True,
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search Bocha.
+
+ Args:
+ query: Search query.
+ max_results: Result cap. Bocha's own ``count`` accepts 1-50.
+ freshness: Time window. One of ``noLimit``/``oneDay``/``oneWeek``/
+ ``oneMonth``/``oneYear``, or a ``YYYY-MM-DD`` (optionally
+ ``YYYY-MM-DD..YYYY-MM-DD``) range, which is passed through.
+ summary: Ask for the long-form ``summary`` field per result. Left on
+ because the short ``snippet`` alone is thin context for a model.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options, including ``base_url``.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ # A dated range is legal too, so only bare words are validated.
+ if freshness not in _FRESHNESS and not freshness[:1].isdigit():
+ raise ValueError(
+ f"Bocha freshness must be a date range or one of {sorted(_FRESHNESS)}, got {freshness!r}."
+ )
+ endpoint = str(kwargs.get("base_url") or self.BASE_URL)
+ payload = {
+ "query": query,
+ "summary": summary,
+ "freshness": freshness,
+ "count": max(1, min(int(max_results), 50)),
+ }
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ request_kwargs: dict[str, Any] = {"headers": headers, "json": payload}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.post(endpoint, timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Bocha API error: {resp.status_code} - {resp.text}")
+
+ payload_json = resp.json()
+ # Bocha wraps failures in a 200 with a non-zero code.
+ if payload_json.get("code") not in (200, 0, None):
+ raise Exception(f"Bocha API error: {payload_json.get('msg') or payload_json}")
+ data = payload_json.get("data") or {}
+ rows = ((data.get("webPages") or {}).get("value")) or []
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ for idx, row in enumerate(rows, 1):
+ title = str(row.get("name", ""))
+ url = str(row.get("url", ""))
+ # `snippet` is the SERP blurb; `summary` is the longer extract.
+ snippet = str(row.get("snippet", ""))
+ content = str(row.get("summary", "") or "")
+ site_name = str(row.get("siteName", "") or "")
+ date = str(row.get("datePublished", "") or "")
+ search_results.append(
+ SearchResult(
+ title=title,
+ url=url,
+ snippet=snippet,
+ date=date,
+ source=site_name or "Bocha",
+ content=content,
+ )
+ )
+ citations.append(
+ Citation(
+ id=idx,
+ reference=f"[{idx}]",
+ url=url,
+ title=title,
+ snippet=snippet,
+ date=date,
+ source=site_name or "Bocha",
+ content=content,
+ icon=str(row.get("siteIcon", "") or ""),
+ website=site_name,
+ )
+ )
+
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider="bocha",
+ timestamp=datetime.now().isoformat(),
+ model="bocha-web-search",
+ citations=citations,
+ search_results=search_results,
+ metadata={"finish_reason": "stop"},
+ )
diff --git a/deeptutor/services/search/providers/brave.py b/deeptutor/services/search/providers/brave.py
index a6dac2dce..15900f352 100644
--- a/deeptutor/services/search/providers/brave.py
+++ b/deeptutor/services/search/providers/brave.py
@@ -16,10 +16,7 @@ from . import register_provider
class BraveProvider(BaseSearchProvider):
"""Brave web search provider."""
- display_name = "Brave Search"
description = "Brave web search API"
- supports_answer = False
- requires_api_key = True
BASE_URL = "https://api.search.brave.com/res/v1/web/search"
API_KEY_ENV_VARS = ("BRAVE_API_KEY", "SEARCH_API_KEY")
diff --git a/deeptutor/services/search/providers/doubao.py b/deeptutor/services/search/providers/doubao.py
new file mode 100644
index 000000000..5db7b0624
--- /dev/null
+++ b/deeptutor/services/search/providers/doubao.py
@@ -0,0 +1,166 @@
+"""Doubao (豆包 / Volcengine Ark) search provider.
+
+API: https://ark.cn-beijing.volces.com/api/v3/responses
+
+Ark has no standalone search endpoint -- web search exists only as a built-in
+``web_search`` tool on the Responses API. So a query here runs through a Doubao
+model that searches, reads, and writes the answer itself, which is why this
+provider reports ``supports_answer`` and skips consolidation.
+
+Its ``sources`` knob is the real differentiator: besides the open web it can
+read ByteDance-owned corpora (Toutiao news, Douyin, Moji weather) that no other
+provider indexes.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+_SOURCES = ("search_engine", "toutiao", "douyin", "moji")
+# Ark pins model ids to a dated release; override via the `model` kwarg.
+_DEFAULT_MODEL = "doubao-seed-1-6-251015"
+
+
+@register_provider("doubao")
+class DoubaoProvider(BaseSearchProvider):
+ """Doubao web search provider (Volcengine Ark Responses API)."""
+
+ description = "Doubao AI search with answers (豆包)"
+ BASE_URL = "https://ark.cn-beijing.volces.com/api/v3/responses"
+ API_KEY_ENV_VARS = ("ARK_API_KEY", "DOUBAO_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ max_results: int = 5,
+ model: str = _DEFAULT_MODEL,
+ sources: list[str] | None = None,
+ max_keyword: int | None = None,
+ timeout: int = 60,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search via Doubao's web_search tool.
+
+ Args:
+ query: Search query.
+ max_results: Passed as the tool's ``limit``.
+ model: Ark model id. Ids carry a dated suffix and are retired over
+ time, so this is overridable.
+ sources: Corpora to search; any of ``search_engine``, ``toutiao``,
+ ``douyin``, ``moji``. Defaults to ``["search_engine"]``.
+ max_keyword: Cap on keywords the model expands the query into.
+ timeout: Request timeout in seconds. Higher than the SERP providers
+ because a model reads the pages before answering.
+ **kwargs: Additional options, including ``base_url``.
+
+ Returns:
+ WebSearchResponse: Standardized search response, answer included.
+ """
+ selected = list(sources or ["search_engine"])
+ for source in selected:
+ if source not in _SOURCES:
+ raise ValueError(f"Doubao source must be one of {list(_SOURCES)}, got {source!r}.")
+
+ endpoint = str(kwargs.get("base_url") or self.BASE_URL)
+ tool: dict[str, Any] = {
+ "type": "web_search",
+ "sources": selected,
+ "limit": max(1, int(max_results)),
+ }
+ if max_keyword is not None:
+ tool["max_keyword"] = max(1, int(max_keyword))
+ payload = {"model": model, "input": query, "tools": [tool]}
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ request_kwargs: dict[str, Any] = {"headers": headers, "json": payload}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.post(endpoint, timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Doubao API error: {resp.status_code} - {resp.text}")
+
+ data = resp.json()
+ if data.get("error"):
+ raise Exception(f"Doubao API error: {data['error']}")
+
+ # Walk output[] -> message -> content[] -> output_text, collecting the
+ # answer text and the url_citation annotations hanging off it.
+ answer_parts: list[str] = []
+ annotations: list[dict[str, Any]] = []
+ for item in data.get("output") or []:
+ if item.get("type") != "message":
+ continue
+ for block in item.get("content") or []:
+ if block.get("type") != "output_text":
+ continue
+ if block.get("text"):
+ answer_parts.append(str(block["text"]))
+ for annotation in block.get("annotations") or []:
+ if annotation.get("type") == "url_citation":
+ annotations.append(annotation)
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ seen: set[str] = set()
+ for annotation in annotations:
+ url = str(annotation.get("url", "") or "")
+ # The same source can be cited from several sentences.
+ if not url or url in seen:
+ continue
+ seen.add(url)
+ idx = len(citations) + 1
+ title = str(annotation.get("title", "") or "")
+ summary = str(annotation.get("summary", "") or "")
+ site_name = str(annotation.get("site_name", "") or "")
+ date = str(annotation.get("publish_time", "") or "")
+ search_results.append(
+ SearchResult(
+ title=title,
+ url=url,
+ snippet=summary,
+ date=date,
+ source=site_name or "Doubao",
+ content=summary,
+ )
+ )
+ citations.append(
+ Citation(
+ id=idx,
+ reference=f"[{idx}]",
+ url=url,
+ title=title,
+ snippet=summary,
+ date=date,
+ source=site_name or "Doubao",
+ content=summary,
+ icon=str(annotation.get("logo_url", "") or ""),
+ website=site_name,
+ )
+ )
+
+ usage = data.get("usage") or {}
+ return WebSearchResponse(
+ query=query,
+ answer="".join(answer_parts),
+ provider="doubao",
+ timestamp=datetime.now().isoformat(),
+ model=str(data.get("model") or model),
+ citations=citations,
+ search_results=search_results,
+ usage={
+ "prompt_tokens": usage.get("input_tokens", 0),
+ "completion_tokens": usage.get("output_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ },
+ metadata={"finish_reason": data.get("status") or "stop"},
+ )
diff --git a/deeptutor/services/search/providers/duckduckgo.py b/deeptutor/services/search/providers/duckduckgo.py
index d0448ac10..9cf6b6a57 100644
--- a/deeptutor/services/search/providers/duckduckgo.py
+++ b/deeptutor/services/search/providers/duckduckgo.py
@@ -14,10 +14,7 @@ from . import register_provider
class DuckDuckGoProvider(BaseSearchProvider):
"""DuckDuckGo provider using `ddgs`."""
- display_name = "DuckDuckGo"
description = "DuckDuckGo search (no API key required)"
- supports_answer = False
- requires_api_key = False
API_KEY_ENV_VARS = ()
def search(
diff --git a/deeptutor/services/search/providers/exa.py b/deeptutor/services/search/providers/exa.py
deleted file mode 100644
index bc62f7ba8..000000000
--- a/deeptutor/services/search/providers/exa.py
+++ /dev/null
@@ -1,194 +0,0 @@
-"""
-Exa Neural Search Provider
-
-API Docs: https://exa.ai/docs/reference/search
-Endpoint: https://api.exa.ai/search
-
-Features:
-- Embeddings-based neural search (finds semantically similar content)
-- Multiple search types: auto, neural, keyword
-- Category filtering: research paper, news, company, people, github, tweet, pdf
-- Date filtering (published date and crawl date)
-- Domain include/exclude lists
-- Full text extraction with highlights and summaries
-- Cost tracking in response
-
-Pricing:
-- Neural search (1-25 results): $0.005/request
-- Neural search (26-100 results): $0.025/request
-- Content text/highlight/summary: $0.001/page
-"""
-
-from datetime import datetime
-from typing import Any
-
-import requests
-
-from ..base import BaseSearchProvider
-from ..types import Citation, SearchResult, WebSearchResponse
-from . import register_provider
-
-
-@register_provider("exa")
-class ExaProvider(BaseSearchProvider):
- """Exa neural/embeddings-based search provider"""
-
- display_name = "Exa"
- description = "Neural/embeddings search"
- supports_answer = True # Provides summaries and context
- BASE_URL = "https://api.exa.ai/search"
-
- def search(
- self,
- query: str,
- search_type: str = "auto", # auto, neural, keyword
- num_results: int = 10,
- include_text: bool = True,
- include_highlights: bool = True,
- include_summary: bool = True,
- max_characters: int | None = None,
- category: str | None = None, # research paper, news, company, etc.
- include_domains: list[str] | None = None,
- exclude_domains: list[str] | None = None,
- start_published_date: str | None = None, # ISO format
- end_published_date: str | None = None,
- timeout: int = 60,
- **kwargs: Any,
- ) -> WebSearchResponse:
- """
- Perform neural search using Exa API.
-
- Args:
- query: Search query.
- search_type: Search type - "auto", "neural", or "keyword".
- num_results: Number of results to return.
- include_text: Include full text content.
- include_highlights: Include relevant highlights.
- include_summary: Include AI-generated summaries.
- max_characters: Maximum characters per result.
- category: Filter by category.
- include_domains: List of domains to include.
- exclude_domains: List of domains to exclude.
- start_published_date: Filter by start date (ISO format).
- end_published_date: Filter by end date (ISO format).
- timeout: Request timeout in seconds.
- **kwargs: Additional options.
-
- Returns:
- WebSearchResponse: Standardized search response.
- """
- self.logger.debug(f"Calling Exa API type={search_type}, num_results={num_results}")
- headers = {
- "Content-Type": "application/json",
- "x-api-key": self.api_key,
- }
-
- # Build contents configuration
- contents: dict[str, Any] = {}
- if include_text:
- contents["text"] = {"maxCharacters": max_characters} if max_characters else True
- if include_highlights:
- contents["highlights"] = True
- if include_summary:
- contents["summary"] = True
-
- payload: dict[str, Any] = {
- "query": query,
- "type": search_type,
- "numResults": num_results,
- "contents": contents,
- }
-
- if category:
- payload["category"] = category
- if include_domains:
- payload["includeDomains"] = include_domains
- if exclude_domains:
- payload["excludeDomains"] = exclude_domains
- if start_published_date:
- payload["startPublishedDate"] = start_published_date
- if end_published_date:
- payload["endPublishedDate"] = end_published_date
-
- response = requests.post(self.BASE_URL, headers=headers, json=payload, timeout=timeout)
-
- if response.status_code != 200:
- try:
- error_data = response.json() if response.text else {}
- except Exception:
- error_data = {}
- self.logger.error(f"Exa API error: {response.status_code}")
- raise Exception(
- f"Exa API error: {response.status_code} - {error_data.get('error', response.text)}"
- )
-
- try:
- data = response.json()
- except Exception as e:
- raise Exception(f"Failed to parse Exa API response: {e}")
- self.logger.debug(f"Exa returned {len(data.get('results', []))} results")
-
- # Build answer from summaries
- summaries = []
- citations: list[Citation] = []
- search_results: list[SearchResult] = []
-
- for i, result in enumerate(data.get("results", []), 1):
- # Extract summary for answer
- summary = result.get("summary", "")
- if summary:
- summaries.append(f"[{i}] {summary}")
-
- # Build search result
- sr = SearchResult(
- title=result.get("title", ""),
- url=result.get("url", ""),
- snippet=summary or result.get("text", "")[:500],
- date=result.get("publishedDate", ""),
- source=result.get("author", ""),
- content=result.get("text", ""),
- score=result.get("score", 0.0),
- )
- search_results.append(sr)
-
- # Build citation
- citations.append(
- Citation(
- id=i,
- reference=f"[{i}]",
- url=result.get("url", ""),
- title=result.get("title", ""),
- snippet=summary or result.get("text", "")[:500],
- date=result.get("publishedDate", ""),
- source=result.get("author", ""),
- content=result.get("text", ""),
- )
- )
-
- # Combine summaries as answer
- answer = "\n\n".join(summaries) if summaries else ""
-
- # Build metadata
- metadata: dict[str, Any] = {
- "finish_reason": "stop",
- "search_type": search_type,
- "autoprompt_string": data.get("autopromptString", ""),
- }
-
- # Add cost info if available
- if data.get("costDollars"):
- metadata["cost_dollars"] = data["costDollars"]
-
- response_obj = WebSearchResponse(
- query=query,
- answer=answer,
- provider="exa",
- timestamp=datetime.now().isoformat(),
- model=f"exa-{search_type}",
- citations=citations,
- search_results=search_results,
- usage={},
- metadata=metadata,
- )
-
- return response_obj
diff --git a/deeptutor/services/search/providers/firecrawl.py b/deeptutor/services/search/providers/firecrawl.py
new file mode 100644
index 000000000..8df39e7d6
--- /dev/null
+++ b/deeptutor/services/search/providers/firecrawl.py
@@ -0,0 +1,136 @@
+"""Firecrawl search provider.
+
+API: https://api.firecrawl.dev/v2/search
+
+Firecrawl searches and scrapes in one call: with ``scrapeOptions`` it returns
+each hit's page body as markdown, so results carry real content rather than a
+SERP blurb. That makes it the expensive-but-rich option next to plain SERP
+providers, and it is why scraping is opt-in per call.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+# Narrow the corpus; `research` and `pdf` are the useful ones for study material.
+_CATEGORIES = ("github", "research", "pdf", "developer")
+
+
+@register_provider("firecrawl")
+class FirecrawlProvider(BaseSearchProvider):
+ """Firecrawl search provider."""
+
+ description = "Search with full-page markdown extraction"
+ BASE_URL = "https://api.firecrawl.dev/v2/search"
+ API_KEY_ENV_VARS = ("FIRECRAWL_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ max_results: int = 5,
+ scrape: bool = False,
+ categories: list[str] | None = None,
+ tbs: str | None = None,
+ timeout: int = 60,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search Firecrawl.
+
+ Args:
+ query: Search query (max 500 chars, enforced by the API).
+ max_results: Result cap (1-100 per source).
+ scrape: Fetch each result's body as markdown. Off by default -- it
+ bills per page scraped and multiplies latency, so the caller
+ opts in when full text is actually wanted.
+ categories: Restrict the corpus; any of ``github``, ``research``,
+ ``pdf``, ``developer``.
+ tbs: Time filter in Google syntax (e.g. ``qdr:w`` for the past week).
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options, including ``base_url``.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ for category in categories or []:
+ if category not in _CATEGORIES:
+ raise ValueError(
+ f"Firecrawl category must be one of {list(_CATEGORIES)}, got {category!r}."
+ )
+ endpoint = str(kwargs.get("base_url") or self.BASE_URL)
+ payload: dict[str, Any] = {
+ "query": query,
+ "limit": max(1, min(int(max_results), 100)),
+ "sources": [{"type": "web"}],
+ # The API's own timeout is milliseconds and bounded at 300s; keep it
+ # just under the transport timeout so it fails on their side first.
+ "timeout": max(1000, min(int(timeout) * 1000 - 1000, 300000)),
+ }
+ if categories:
+ payload["categories"] = list(categories)
+ if tbs:
+ payload["tbs"] = tbs
+ if scrape:
+ payload["scrapeOptions"] = {"formats": [{"type": "markdown"}], "onlyMainContent": True}
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ request_kwargs: dict[str, Any] = {"headers": headers, "json": payload}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.post(endpoint, timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Firecrawl API error: {resp.status_code} - {resp.text}")
+
+ data = resp.json()
+ if not data.get("success", True):
+ raise Exception(f"Firecrawl API error: {data.get('error') or data}")
+ rows = (data.get("data") or {}).get("web") or []
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ for idx, row in enumerate(rows, 1):
+ title = str(row.get("title", "") or "")
+ url = str(row.get("url", "") or "")
+ snippet = str(row.get("description", "") or "")
+ content = str(row.get("markdown", "") or "")
+ search_results.append(
+ SearchResult(
+ title=title,
+ url=url,
+ snippet=snippet,
+ source="Firecrawl",
+ content=content,
+ )
+ )
+ citations.append(
+ Citation(
+ id=idx,
+ reference=f"[{idx}]",
+ url=url,
+ title=title,
+ snippet=snippet,
+ source="Firecrawl",
+ content=content,
+ )
+ )
+
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider="firecrawl",
+ timestamp=datetime.now().isoformat(),
+ model="firecrawl-search",
+ citations=citations,
+ search_results=search_results,
+ usage={"credits_used": data.get("creditsUsed", 0)},
+ metadata={"finish_reason": "stop"},
+ )
diff --git a/deeptutor/services/search/providers/jina.py b/deeptutor/services/search/providers/jina.py
index 62c9ef49e..11ea97ae7 100644
--- a/deeptutor/services/search/providers/jina.py
+++ b/deeptutor/services/search/providers/jina.py
@@ -30,10 +30,7 @@ from . import register_provider
class JinaProvider(BaseSearchProvider):
"""Jina Reader search provider"""
- display_name = "Jina"
description = "SERP with content extraction (free tier)"
- supports_answer = False # Returns raw content, not LLM answers
- requires_api_key = True
API_KEY_ENV_VARS = ("JINA_API_KEY", "SEARCH_API_KEY")
BASE_URL = "https://s.jina.ai"
@@ -41,6 +38,7 @@ class JinaProvider(BaseSearchProvider):
self,
query: str,
enrich: bool = True,
+ max_results: int | None = None,
timeout: int = 60,
**kwargs: Any,
) -> WebSearchResponse:
@@ -50,6 +48,10 @@ class JinaProvider(BaseSearchProvider):
Args:
query: Search query.
enrich: If True, fetch full content + images. If False, basic SERP only.
+ max_results: Result cap from the resolved search config. The search
+ endpoint takes no count parameter, so the response is truncated
+ here — otherwise every result Jina returns (with full page
+ content when ``enrich`` is on) lands in the model's context.
timeout: Request timeout in seconds.
**kwargs: Additional options.
@@ -86,7 +88,10 @@ class JinaProvider(BaseSearchProvider):
raise Exception(f"Jina API error: {response.status_code} - {response.text}")
data = response.json()
- self.logger.debug(f"Jina returned {len(data.get('data', []))} results")
+ rows = data.get("data", []) or []
+ self.logger.debug(f"Jina returned {len(rows)} results")
+ if max_results is not None:
+ rows = rows[: max(1, int(max_results))]
# Extract search results
citations: list[Citation] = []
@@ -95,7 +100,7 @@ class JinaProvider(BaseSearchProvider):
# Jina Search API returns results in 'data' array
# Basic fields: title, url, description, date, content, usage
# Enriched fields (enrich=true): images, publishedTime, metadata, external
- for i, result in enumerate(data.get("data", []), 1):
+ for i, result in enumerate(rows, 1):
# Build attributes dict for enriched fields
attributes: dict[str, Any] = {}
if result.get("images"):
diff --git a/deeptutor/services/search/providers/openrouter.py b/deeptutor/services/search/providers/openrouter.py
deleted file mode 100644
index 2e2b50f02..000000000
--- a/deeptutor/services/search/providers/openrouter.py
+++ /dev/null
@@ -1,165 +0,0 @@
-"""
-OpenRouter Search Provider
-==========================
-
-API: Uses openai Python package with OpenRouter base URL
-Model: perplexity/sonar (or other supported models)
-
-Features:
-- Compatible with OpenRouter's OpenAI-like API
-- Extracts citations from response (supports 'citations' in root or choice)
-- Maps string URLs to Citation objects
-"""
-
-from datetime import datetime
-from typing import Any, List
-
-from deeptutor.services.search.base import BaseSearchProvider
-from deeptutor.services.search.providers import register_provider
-from deeptutor.services.search.types import Citation, SearchResult, WebSearchResponse
-
-
-@register_provider("openrouter")
-class OpenRouterProvider(BaseSearchProvider):
- """OpenRouter search provider (wrapper for Perplexity models via OpenRouter)"""
-
- display_name = "OpenRouter"
- description = "Search via OpenRouter (Perplexity models)"
- supports_answer = True
- requires_api_key = True
-
- def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:
- super().__init__(api_key, **kwargs)
- self._client = None
- # Default base URL for OpenRouter
- # Note: kwargs might override base_url if provided by config
- self.base_url = kwargs.get("base_url", "https://openrouter.ai/api/v1")
-
- @property
- def client(self):
- """Lazy-load the OpenAI client configured for OpenRouter."""
- if self._client is None:
- try:
- from openai import OpenAI
- except ImportError as e:
- raise ImportError(
- "openai module is not installed. To use OpenRouter search, please install: "
- "pip install openai"
- ) from e
-
- if not self.api_key:
- raise ValueError("API Key is required for OpenRouter search provider.")
-
- self._client = OpenAI(
- api_key=self.api_key,
- base_url=self.base_url,
- )
- return self._client
-
- def search(
- self,
- query: str,
- model: str = "perplexity/sonar",
- system_prompt: str = "You are a helpful AI assistant. Provide detailed and accurate answers based on web search results.",
- **kwargs: Any,
- ) -> WebSearchResponse:
- """
- Perform search using OpenRouter API.
-
- Args:
- query: Search query.
- model: Model to use (default: perplexity/sonar).
- system_prompt: System prompt for the model.
- **kwargs: Additional options.
-
- Returns:
- WebSearchResponse: Standardized search response.
- """
- self.logger.debug(f"Calling OpenRouter API with model={model}")
-
- completion = self.client.chat.completions.create(
- model=model,
- messages=[
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": query},
- ],
- # Request citations explicitly
- extra_body={"return_citations": True},
- )
-
- if not completion.choices or len(completion.choices) == 0:
- raise ValueError("OpenRouter API returned no choices")
-
- choice = completion.choices[0]
- answer = choice.message.content or ""
-
- # Build usage info
- usage_info: dict[str, Any] = {}
- if completion.usage:
- usage = completion.usage
- usage_info = {
- "prompt_tokens": usage.prompt_tokens,
- "completion_tokens": usage.completion_tokens,
- "total_tokens": usage.total_tokens,
- }
-
- # Extract citations
- # OpenRouter returns citations in the root of the response object usually
- # But openai library models usage as Pydantic models, so we access via model_extra or dict
-
- citations_data = []
- raw_dict = completion.model_dump()
-
- # Check root level 'citations' (OpenRouter standard for Perplexity models)
- if "citations" in raw_dict:
- citations_data = raw_dict["citations"]
- elif "citations" in raw_dict.get("choices", [{}])[0]:
- citations_data = raw_dict["choices"][0]["citations"]
-
- citations: List[Citation] = []
- search_results: List[SearchResult] = []
-
- if citations_data:
- for i, cite_item in enumerate(citations_data, 1):
- url = ""
- if isinstance(cite_item, str):
- url = cite_item
- elif isinstance(cite_item, dict):
- url = cite_item.get("url", "")
-
- if url:
- citations.append(
- Citation(
- id=i,
- reference=f"[{i}]",
- url=url,
- title=f"Source {i}", # Fallback as we don't get title
- snippet="Content not available from meta-data.", # Fallback
- source="OpenRouter",
- )
- )
- # Also populate search_results as some UI components might use it
- search_results.append(
- SearchResult(
- title=f"Source {i}",
- url=url,
- snippet="Content not available from meta-data.",
- source="OpenRouter",
- )
- )
-
- response = WebSearchResponse(
- query=query,
- answer=answer,
- provider="openrouter",
- timestamp=datetime.now().isoformat(),
- model=completion.model,
- citations=citations,
- search_results=search_results,
- usage=usage_info,
- metadata={
- "finish_reason": choice.finish_reason,
- },
- )
-
- return response
diff --git a/deeptutor/services/search/providers/perplexity.py b/deeptutor/services/search/providers/perplexity.py
index 54e989333..5fe79d779 100644
--- a/deeptutor/services/search/providers/perplexity.py
+++ b/deeptutor/services/search/providers/perplexity.py
@@ -22,9 +22,7 @@ from . import register_provider
class PerplexityProvider(BaseSearchProvider):
"""Perplexity AI search provider"""
- display_name = "Perplexity"
description = "AI-powered search with answers"
- supports_answer = True
BASE_URL = "https://api.perplexity.ai" # Used by the perplexity package internally
def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:
diff --git a/deeptutor/services/search/providers/qianfan.py b/deeptutor/services/search/providers/qianfan.py
new file mode 100644
index 000000000..efb2fc58b
--- /dev/null
+++ b/deeptutor/services/search/providers/qianfan.py
@@ -0,0 +1,149 @@
+"""Baidu Qianfan (百度千帆) AI search provider.
+
+API: https://qianfan.baidubce.com/v2/ai_search/web_search
+
+Registered as ``qianfan`` rather than ``baidu``: the retired ``baidu`` provider
+sits in ``DEPRECATED_SEARCH_PROVIDERS``, and reusing that key would keep this
+one out of the registry. The name is also the accurate one -- this is Qianfan's
+official search endpoint, not a scrape of baidu.com.
+
+The response shape is where :class:`~deeptutor.services.search.types.Citation`
+got its ``web_anchor`` / ``icon`` / ``website`` fields, so rows map across
+one-for-one with no invention.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+_RECENCY = ("week", "month", "semiyear", "year")
+# Longer queries are rejected by the API rather than truncated.
+_QUERY_LIMIT = 72
+# Per-modality ceilings the API enforces.
+_TOP_K_MAX = 50
+
+
+@register_provider("qianfan")
+class QianfanProvider(BaseSearchProvider):
+ """Baidu Qianfan AI search provider."""
+
+ description = "Baidu web search via Qianfan (百度千帆)"
+ BASE_URL = "https://qianfan.baidubce.com/v2/ai_search/web_search"
+ API_KEY_ENV_VARS = ("QIANFAN_API_KEY", "BAIDU_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ max_results: int = 5,
+ search_recency_filter: str | None = None,
+ edition: str = "standard",
+ safe_search: bool = False,
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search Baidu Qianfan.
+
+ Args:
+ query: Search query. Truncated to 72 chars, which the API enforces.
+ max_results: Result cap (``top_k``, max 50 for web).
+ search_recency_filter: Time window; one of ``week``, ``month``,
+ ``semiyear``, ``year``. ``None`` leaves it unbounded.
+ edition: ``standard`` or ``turbo`` (faster, shallower).
+ safe_search: Filter adult content.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options, including ``base_url``.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ if search_recency_filter is not None and search_recency_filter not in _RECENCY:
+ raise ValueError(
+ f"Qianfan search_recency_filter must be one of {list(_RECENCY)}, got {search_recency_filter!r}."
+ )
+ endpoint = str(kwargs.get("base_url") or self.BASE_URL)
+ payload: dict[str, Any] = {
+ "messages": [{"role": "user", "content": query[:_QUERY_LIMIT]}],
+ "search_source": "baidu_search_v2",
+ "resource_type_filter": [
+ {"type": "web", "top_k": max(1, min(int(max_results), _TOP_K_MAX))}
+ ],
+ "edition": edition,
+ "safe_search": safe_search,
+ }
+ if search_recency_filter:
+ payload["search_recency_filter"] = search_recency_filter
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ request_kwargs: dict[str, Any] = {"headers": headers, "json": payload}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.post(endpoint, timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Qianfan API error: {resp.status_code} - {resp.text}")
+
+ data = resp.json()
+ # Errors arrive as a 200 carrying `code`/`message` and no references.
+ # `code` is documented as error-only, but treat the success codes as
+ # success rather than assuming any code at all means failure.
+ if data.get("code") not in (None, 0, 200, "0", "200"):
+ raise Exception(f"Qianfan API error: {data.get('code')} - {data.get('message')}")
+ rows = data.get("references") or []
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ for idx, row in enumerate(rows, 1):
+ title = str(row.get("title", "") or "")
+ url = str(row.get("url", "") or "")
+ snippet = str(row.get("snippet", "") or "")
+ content = str(row.get("content", "") or "")
+ website = str(row.get("website", "") or "")
+ date = str(row.get("date", "") or "")
+ search_results.append(
+ SearchResult(
+ title=title,
+ url=url,
+ snippet=snippet,
+ date=date,
+ source=website or "Baidu",
+ content=content,
+ )
+ )
+ citations.append(
+ Citation(
+ # Qianfan numbers its own references; keep its id so the
+ # markers line up with anything echoing the raw payload.
+ id=int(row.get("id", idx) or idx),
+ reference=f"[{row.get('id', idx)}]",
+ url=url,
+ title=title,
+ snippet=snippet,
+ date=date,
+ source=website or "Baidu",
+ content=content,
+ type=str(row.get("type", "web") or "web"),
+ icon=str(row.get("icon", "") or ""),
+ website=website,
+ web_anchor=str(row.get("web_anchor", "") or ""),
+ )
+ )
+
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider="qianfan",
+ timestamp=datetime.now().isoformat(),
+ model="baidu_search_v2",
+ citations=citations,
+ search_results=search_results,
+ metadata={"finish_reason": "stop", "request_id": data.get("request_id", "")},
+ )
diff --git a/deeptutor/services/search/providers/searxng.py b/deeptutor/services/search/providers/searxng.py
index 10954ad65..c076aa66f 100644
--- a/deeptutor/services/search/providers/searxng.py
+++ b/deeptutor/services/search/providers/searxng.py
@@ -27,10 +27,7 @@ def _validate_base_url(base_url: str) -> str:
class SearxngProvider(BaseSearchProvider):
"""SearXNG provider."""
- display_name = "SearXNG"
description = "Self-hosted SearXNG endpoint"
- supports_answer = False
- requires_api_key = False
API_KEY_ENV_VARS = ()
def search(
diff --git a/deeptutor/services/search/providers/serper.py b/deeptutor/services/search/providers/serper.py
index 9b698269b..ceb330a54 100644
--- a/deeptutor/services/search/providers/serper.py
+++ b/deeptutor/services/search/providers/serper.py
@@ -34,9 +34,7 @@ class SerperAPIError(Exception):
class SerperProvider(BaseSearchProvider):
"""Serper Google SERP provider"""
- display_name = "Serper"
description = "Google SERP results"
- supports_answer = False # Raw SERP results, no LLM answer
BASE_URL = "https://google.serper.dev"
def search(
@@ -44,6 +42,7 @@ class SerperProvider(BaseSearchProvider):
query: str,
mode: str = "search", # search, scholar
num: int = 10,
+ max_results: int | None = None,
gl: str = "us", # Country code
hl: str = "en", # Language code
page: int = 1,
@@ -58,6 +57,8 @@ class SerperProvider(BaseSearchProvider):
query: Search query.
mode: Search mode - "search" or "scholar".
num: Number of results (default 10, max 100).
+ max_results: Result cap from the resolved search config; when set it
+ wins over ``num``, which is Serper's own name for the same knob.
gl: Country code (default "us").
hl: Language code (default "en").
page: Page number for pagination.
@@ -68,6 +69,8 @@ class SerperProvider(BaseSearchProvider):
Returns:
WebSearchResponse: Standardized search response.
"""
+ if max_results is not None:
+ num = max(1, int(max_results))
self.logger.debug(f"Calling Serper API mode={mode}, num={num}")
headers = {
"X-API-KEY": self.api_key,
@@ -84,7 +87,10 @@ class SerperProvider(BaseSearchProvider):
}
url = f"{self.BASE_URL}/{mode}"
- response = requests.post(url, headers=headers, json=payload, timeout=timeout)
+ request_kwargs: dict[str, Any] = {"headers": headers, "json": payload}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ response = requests.post(url, timeout=timeout, **request_kwargs)
if response.status_code != 200:
try:
diff --git a/deeptutor/services/search/providers/tavily.py b/deeptutor/services/search/providers/tavily.py
index d80d64824..5d606f604 100644
--- a/deeptutor/services/search/providers/tavily.py
+++ b/deeptutor/services/search/providers/tavily.py
@@ -27,10 +27,7 @@ from . import register_provider
class TavilyProvider(BaseSearchProvider):
"""Tavily research-focused search provider"""
- name = "tavily"
- display_name = "Tavily"
description = "Research-focused search"
- supports_answer = True
BASE_URL = "https://api.tavily.com/search"
API_KEY_ENV_VARS = ("TAVILY_API_KEY", "SEARCH_API_KEY")
diff --git a/deeptutor/services/search/providers/zhipu.py b/deeptutor/services/search/providers/zhipu.py
new file mode 100644
index 000000000..828c70f57
--- /dev/null
+++ b/deeptutor/services/search/providers/zhipu.py
@@ -0,0 +1,142 @@
+"""Zhipu (智谱 GLM) web search provider.
+
+API: https://open.bigmodel.cn/api/paas/v4/web_search
+
+This is Zhipu's standalone search endpoint, not the ``web_search`` tool bolted
+onto chat completions -- it returns ranked rows and never a model-written
+answer, so consolidation supplies the answer.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+# Four back-ends with different quality/price points; `search_std` is cheapest.
+_ENGINES = ("search_std", "search_pro", "search_pro_sogou", "search_pro_quark")
+_RECENCY = ("noLimit", "oneDay", "oneWeek", "oneMonth", "oneYear")
+# The API rejects longer queries outright rather than truncating them.
+_QUERY_LIMIT = 70
+
+
+@register_provider("zhipu")
+class ZhipuProvider(BaseSearchProvider):
+ """Zhipu GLM web search provider."""
+
+ description = "Zhipu GLM web search (智谱)"
+ BASE_URL = "https://open.bigmodel.cn/api/paas/v4/web_search"
+ API_KEY_ENV_VARS = ("ZHIPU_API_KEY", "ZHIPUAI_API_KEY", "SEARCH_API_KEY")
+
+ def search(
+ self,
+ query: str,
+ max_results: int = 5,
+ search_engine: str = "search_std",
+ content_size: str = "medium",
+ search_recency_filter: str = "noLimit",
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """Search Zhipu.
+
+ Args:
+ query: Search query. Truncated to 70 chars, which the API enforces.
+ max_results: Result cap (1-50).
+ search_engine: One of ``search_std``, ``search_pro``,
+ ``search_pro_sogou``, ``search_pro_quark``.
+ content_size: ``medium`` or ``high`` -- how much body text each row
+ carries.
+ search_recency_filter: Time window; one of ``noLimit``/``oneDay``/
+ ``oneWeek``/``oneMonth``/``oneYear``.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options, including ``base_url`` and
+ ``search_domain_filter``.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ if search_engine not in _ENGINES:
+ raise ValueError(
+ f"Zhipu search_engine must be one of {list(_ENGINES)}, got {search_engine!r}."
+ )
+ if search_recency_filter not in _RECENCY:
+ raise ValueError(
+ f"Zhipu search_recency_filter must be one of {list(_RECENCY)}, got {search_recency_filter!r}."
+ )
+ endpoint = str(kwargs.get("base_url") or self.BASE_URL)
+ payload: dict[str, Any] = {
+ "search_query": query[:_QUERY_LIMIT],
+ "search_engine": search_engine,
+ "search_intent": False,
+ "count": max(1, min(int(max_results), 50)),
+ "search_recency_filter": search_recency_filter,
+ "content_size": content_size,
+ }
+ domain_filter = kwargs.get("search_domain_filter")
+ if domain_filter:
+ payload["search_domain_filter"] = domain_filter
+
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ request_kwargs: dict[str, Any] = {"headers": headers, "json": payload}
+ if self.proxy:
+ request_kwargs["proxies"] = {"http": self.proxy, "https": self.proxy}
+ resp = requests.post(endpoint, timeout=timeout, **request_kwargs)
+ if resp.status_code != 200:
+ raise Exception(f"Zhipu API error: {resp.status_code} - {resp.text}")
+
+ data = resp.json()
+ rows = data.get("search_result") or []
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+ for idx, row in enumerate(rows, 1):
+ title = str(row.get("title", ""))
+ url = str(row.get("link", ""))
+ # Zhipu returns one body field; it doubles as snippet and content.
+ content = str(row.get("content", "") or "")
+ media = str(row.get("media", "") or "")
+ date = str(row.get("publish_date", "") or "")
+ search_results.append(
+ SearchResult(
+ title=title,
+ url=url,
+ snippet=content,
+ date=date,
+ source=media or "Zhipu",
+ content=content,
+ )
+ )
+ citations.append(
+ Citation(
+ id=idx,
+ reference=f"[{idx}]",
+ url=url,
+ title=title,
+ snippet=content,
+ date=date,
+ source=media or "Zhipu",
+ content=content,
+ icon=str(row.get("icon", "") or ""),
+ website=media,
+ )
+ )
+
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider="zhipu",
+ timestamp=datetime.now().isoformat(),
+ model=search_engine,
+ citations=citations,
+ search_results=search_results,
+ metadata={"finish_reason": "stop", "request_id": data.get("request_id", "")},
+ )
diff --git a/deeptutor/tools/web_search.py b/deeptutor/tools/web_search.py
index 31c443ccd..5de84f5c3 100644
--- a/deeptutor/tools/web_search.py
+++ b/deeptutor/tools/web_search.py
@@ -17,12 +17,9 @@ Configuration:
Search profiles live in data/user/settings/model_catalog.json.
Available Providers:
- - brave: Brave web search API
- - tavily: Research-focused with optional answers
- - jina: SERP with full content extraction
- - searxng: Self-hosted SearXNG endpoint
- - duckduckgo: Zero-config search
- - perplexity: AI-powered search with answers
+ Defined once in ``SEARCH_PROVIDERS``
+ (``deeptutor/services/config/provider_runtime.py``); call
+ ``get_providers_info()`` for the live list with its credential requirements.
"""
# Re-export from services layer
diff --git a/deeptutor_cli/init_wizard.py b/deeptutor_cli/init_wizard.py
index a725732fd..109280cb2 100644
--- a/deeptutor_cli/init_wizard.py
+++ b/deeptutor_cli/init_wizard.py
@@ -176,6 +176,51 @@ SEARCH_PROVIDERS: tuple[SearchProviderSpec, ...] = (
env_keys=("PERPLEXITY_API_KEY", "SEARCH_API_KEY"),
hint="answer-style search",
),
+ SearchProviderSpec(
+ name="firecrawl",
+ label="Firecrawl",
+ requires_api_key=True,
+ env_keys=("FIRECRAWL_API_KEY", "SEARCH_API_KEY"),
+ hint="search + full-page markdown",
+ ),
+ # China-hosted engines. Worth calling out separately in the wizard: they are
+ # the ones that stay reachable on mainland networks, where the DuckDuckGo
+ # default does not.
+ SearchProviderSpec(
+ name="doubao",
+ label="Doubao (豆包)",
+ requires_api_key=True,
+ env_keys=("ARK_API_KEY", "DOUBAO_API_KEY", "SEARCH_API_KEY"),
+ hint="writes its own answer · Toutiao/Douyin sources",
+ ),
+ SearchProviderSpec(
+ name="bocha",
+ label="Bocha (博查)",
+ requires_api_key=True,
+ env_keys=("BOCHA_API_KEY", "SEARCH_API_KEY"),
+ hint="China-hosted SERP · paid",
+ ),
+ SearchProviderSpec(
+ name="zhipu",
+ label="Zhipu GLM (智谱)",
+ requires_api_key=True,
+ env_keys=("ZHIPU_API_KEY", "ZHIPUAI_API_KEY", "SEARCH_API_KEY"),
+ hint="China-hosted · four engine tiers",
+ ),
+ SearchProviderSpec(
+ name="qianfan",
+ label="Baidu Qianfan (百度千帆)",
+ requires_api_key=True,
+ env_keys=("QIANFAN_API_KEY", "BAIDU_API_KEY", "SEARCH_API_KEY"),
+ hint="Baidu index · China-hosted",
+ ),
+ SearchProviderSpec(
+ name="aliyun_iqs",
+ label="Aliyun IQS (阿里云)",
+ requires_api_key=True,
+ env_keys=("ALIYUN_IQS_API_KEY", "IQS_API_KEY", "SEARCH_API_KEY"),
+ hint="China-hosted · reranked results",
+ ),
SearchProviderSpec(
name="duckduckgo",
label="DuckDuckGo",
diff --git a/tests/cli/test_init_wizard_probe.py b/tests/cli/test_init_wizard_probe.py
index 85d2f8fd0..f445e1c74 100644
--- a/tests/cli/test_init_wizard_probe.py
+++ b/tests/cli/test_init_wizard_probe.py
@@ -297,3 +297,22 @@ def test_probe_llm_keeps_anthropic_native_max_tokens(monkeypatch) -> None:
body = _FakeClient.captured[0]["json"]
assert body["max_tokens"] == 1
assert "max_completion_tokens" not in body
+
+
+def test_wizard_search_providers_match_the_backend_spec_table() -> None:
+ """The wizard's own table may add CLI-only detail, never disagree.
+
+ ``deeptutor_cli.init_wizard.SEARCH_PROVIDERS`` carries what only the wizard
+ needs (env var names, a default SearXNG URL, one-line hints), but the set of
+ providers and which credentials each one needs come from
+ ``SEARCH_PROVIDERS`` in the backend spec table. When those drift, the wizard
+ writes a profile the runtime then rejects or silently downgrades.
+ """
+ from deeptutor.services.config.provider_runtime import SEARCH_PROVIDERS as BACKEND
+ from deeptutor_cli.init_wizard import SEARCH_PROVIDERS as WIZARD
+
+ wizard = {spec.name: spec for spec in WIZARD}
+ assert set(wizard) == set(BACKEND)
+ for name, spec in BACKEND.items():
+ assert wizard[name].requires_api_key == spec.requires_api_key, name
+ assert wizard[name].requires_base_url == spec.requires_base_url, name
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index fb8d3fb18..79a46eb82 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -3,8 +3,12 @@
from __future__ import annotations
from deeptutor.services.config.provider_runtime import (
+ SEARCH_PROVIDERS,
resolve_llm_runtime_config,
resolve_search_runtime_config,
+ search_fallback_candidates,
+ search_missing_credential,
+ search_provider_credentials,
)
@@ -13,6 +17,7 @@ def _build_catalog(
llm_profile: dict | None = None,
llm_model: dict | None = None,
search_profile: dict | None = None,
+ search_profiles: list[dict] | None = None,
) -> dict:
llm_profile = llm_profile or {
"id": "llm-p",
@@ -49,7 +54,7 @@ def _build_catalog(
},
"search": {
"active_profile_id": search_profile["id"],
- "profiles": [search_profile],
+ "profiles": search_profiles or [search_profile],
},
},
}
@@ -641,3 +646,69 @@ def test_search_searxng_without_url_fallback() -> None:
resolved = resolve_search_runtime_config(catalog=catalog)
assert resolved.provider == "duckduckgo"
assert resolved.fallback_reason is not None
+
+
+def _search_profile(pid: str, provider: str, **overrides) -> dict:
+ profile = {
+ "id": pid,
+ "name": provider,
+ "provider": provider,
+ "base_url": "",
+ "api_key": "",
+ "proxy": "",
+ "models": [],
+ }
+ profile.update(overrides)
+ return profile
+
+
+def test_search_missing_credential_names_the_field() -> None:
+ assert search_missing_credential("brave", "", "") == "api_key"
+ assert search_missing_credential("searxng", "", "") == "base_url"
+ assert search_missing_credential("searxng", "", "https://searx.example.com") is None
+ assert search_missing_credential("duckduckgo", "", "") is None
+ assert search_missing_credential("exa", "", "") is None
+
+
+def test_search_credentials_come_from_the_matching_profile() -> None:
+ catalog = _build_catalog(
+ search_profile=_search_profile("p-brave", "brave", api_key="brave-key"),
+ search_profiles=[
+ _search_profile("p-brave", "brave", api_key="brave-key"),
+ _search_profile("p-tavily", "tavily", api_key="tavily-key"),
+ _search_profile("p-searx", "searxng", base_url="https://searx.example.com"),
+ ],
+ )
+ assert search_provider_credentials("brave", catalog=catalog) == ("brave-key", "")
+ assert search_provider_credentials("tavily", catalog=catalog) == ("tavily-key", "")
+ assert search_provider_credentials("searxng", catalog=catalog) == (
+ "",
+ "https://searx.example.com",
+ )
+ # A provider with no profile of its own gets nothing rather than borrowing
+ # the active profile's key.
+ assert search_provider_credentials("serper", catalog=catalog) == ("", "")
+
+
+def test_search_fallback_candidates_skip_unconfigured_providers() -> None:
+ catalog = _build_catalog(
+ search_profile=_search_profile("p-brave", "brave", api_key="brave-key"),
+ search_profiles=[
+ _search_profile("p-brave", "brave", api_key="brave-key"),
+ _search_profile("p-tavily", "tavily", api_key="tavily-key"),
+ _search_profile("p-serper", "serper"), # no key -> never a candidate
+ _search_profile("p-none", "none"), # explicit off -> never a candidate
+ ],
+ )
+ assert search_fallback_candidates("brave", catalog=catalog) == ["tavily", "duckduckgo"]
+ # The credential-free fallback is not appended when it is the requested
+ # provider itself — the remaining configured providers are the chain.
+ assert search_fallback_candidates("duckduckgo", catalog=catalog) == ["brave", "tavily"]
+
+
+def test_every_search_provider_has_a_registered_implementation() -> None:
+ from deeptutor.services.search.providers import list_providers
+
+ registered = set(list_providers())
+ expected = {name for name in SEARCH_PROVIDERS if name != "none"}
+ assert registered == expected
diff --git a/tests/services/search/test_search_providers.py b/tests/services/search/test_search_providers.py
new file mode 100644
index 000000000..f1155b233
--- /dev/null
+++ b/tests/services/search/test_search_providers.py
@@ -0,0 +1,356 @@
+"""Provider-level tests: the resolved search config must reach the HTTP call.
+
+`web_search` hands every provider the same `max_results` / `proxy` knobs from the
+active search profile. A provider that names its parameter differently silently
+drops them, which is how Serper used to ignore both (it takes `num`, and never
+passed `proxies`) and Jina used to return every result it got.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from deeptutor.services.search.providers.brave import BraveProvider
+from deeptutor.services.search.providers.jina import JinaProvider
+from deeptutor.services.search.providers.serper import SerperProvider
+from deeptutor.services.search.providers.tavily import TavilyProvider
+
+PROXY = "http://127.0.0.1:7890"
+
+
+class _FakeResponse:
+ status_code = 200
+ text = ""
+
+ def __init__(self, payload: dict[str, Any]) -> None:
+ self._payload = payload
+
+ def json(self) -> dict[str, Any]:
+ return self._payload
+
+
+def calls(monkeypatch):
+ """Capture requests made by any provider module."""
+ captured: list[dict[str, Any]] = []
+ payloads: dict[str, Any] = {
+ "organic": [],
+ "results": [],
+ "web": {"results": []},
+ "data": [],
+ }
+
+ def _record(method: str):
+ def _call(url: str, **kwargs: Any) -> _FakeResponse:
+ captured.append({"method": method, "url": url, **kwargs})
+ return _FakeResponse(payloads)
+
+ return _call
+
+ for module in ("serper", "tavily", "brave", "jina"):
+ target = f"deeptutor.services.search.providers.{module}.requests"
+
+ class _FakeRequests:
+ get = staticmethod(_record("GET"))
+ post = staticmethod(_record("POST"))
+
+ monkeypatch.setattr(target, _FakeRequests)
+ return captured
+
+
+def test_serper_maps_max_results_onto_num_and_honors_proxy(calls) -> None:
+ provider = SerperProvider(api_key="k", proxy=PROXY)
+ provider.search("q", max_results=3, proxy=PROXY)
+ assert calls[-1]["json"]["num"] == 3
+ assert calls[-1]["proxies"] == {"http": PROXY, "https": PROXY}
+
+
+def test_serper_keeps_its_own_num_parameter(calls) -> None:
+ provider = SerperProvider(api_key="k")
+ provider.search("q", num=7)
+ assert calls[-1]["json"]["num"] == 7
+ assert "proxies" not in calls[-1]
+
+
+def test_tavily_and_brave_already_carry_the_shared_knobs(calls) -> None:
+ TavilyProvider(api_key="k", proxy=PROXY).search("q", max_results=3)
+ assert calls[-1]["json"]["max_results"] == 3
+ assert calls[-1]["proxies"] == {"http": PROXY, "https": PROXY}
+
+ BraveProvider(api_key="k", proxy=PROXY).search("q", max_results=3)
+ assert calls[-1]["params"]["count"] == 3
+ assert calls[-1]["proxies"] == {"http": PROXY, "https": PROXY}
+
+
+def test_jina_truncates_results_to_max_results(monkeypatch) -> None:
+ rows = [
+ {"title": f"t{i}", "url": f"https://e/{i}", "description": "d", "content": "c"}
+ for i in range(6)
+ ]
+
+ class _FakeRequests:
+ @staticmethod
+ def get(url: str, **kwargs: Any) -> _FakeResponse:
+ return _FakeResponse({"data": rows})
+
+ monkeypatch.setattr("deeptutor.services.search.providers.jina.requests", _FakeRequests)
+
+ capped = JinaProvider(api_key="k").search("q", max_results=2)
+ assert len(capped.search_results) == 2
+ assert len(capped.citations) == 2
+ assert [c.id for c in capped.citations] == [1, 2]
+
+ uncapped = JinaProvider(api_key="k").search("q")
+ assert len(uncapped.search_results) == len(rows)
+
+
+def test_provider_metadata_comes_from_the_spec_table() -> None:
+ from deeptutor.services.config import SEARCH_PROVIDERS
+
+ for cls in (SerperProvider, TavilyProvider, BraveProvider, JinaProvider):
+ spec = SEARCH_PROVIDERS[cls.name]
+ assert cls.display_name == spec.label
+ assert cls.requires_api_key == spec.requires_api_key
+ assert cls.supports_answer == spec.supports_answer
+
+
+# --------------------------------------------------------------------------
+# Providers added on top of the original seven. Each names its result cap
+# something different, so the shared-knob contract is where they break first.
+# --------------------------------------------------------------------------
+
+# One body that every new provider can parse to an empty result set, so a
+# single fake response serves them all.
+_EMPTY_BODY: dict[str, Any] = {
+ "code": 200, # bocha treats a non-2xx `code` inside a 200 as an error
+ "success": True, # firecrawl
+ "data": {"webPages": {"value": []}, "web": []}, # bocha / firecrawl
+ "search_result": [], # zhipu
+ "references": [], # qianfan
+ "pageItems": [], # aliyun_iqs
+ "output": [], # doubao
+}
+
+
+def _limit_in_json(key: str):
+ return lambda call: call["json"][key]
+
+
+# (module, provider class, where the result cap lands in the request)
+_NEW_PROVIDERS = [
+ ("bocha", "BochaProvider", _limit_in_json("count")),
+ ("zhipu", "ZhipuProvider", _limit_in_json("count")),
+ ("firecrawl", "FirecrawlProvider", _limit_in_json("limit")),
+ ("qianfan", "QianfanProvider", lambda c: c["json"]["resource_type_filter"][0]["top_k"]),
+ ("doubao", "DoubaoProvider", lambda c: c["json"]["tools"][0]["limit"]),
+ # aliyun_iqs has no count parameter at all — it caps client-side, which
+ # `test_aliyun_iqs_caps_results_client_side` covers instead.
+ ("aliyun_iqs", "AliyunIQSProvider", None),
+]
+
+
+def _provider_class(module: str, name: str):
+ import importlib
+
+ return getattr(importlib.import_module(f"deeptutor.services.search.providers.{module}"), name)
+
+
+def new_calls(monkeypatch):
+ """Capture requests made by any of the newly added provider modules."""
+ captured: list[dict[str, Any]] = []
+
+ def _record(method: str):
+ def _call(url: str, **kwargs: Any) -> _FakeResponse:
+ captured.append({"method": method, "url": url, **kwargs})
+ return _FakeResponse(_EMPTY_BODY)
+
+ return _call
+
+ for module, _, _ in _NEW_PROVIDERS:
+
+ class _FakeRequests:
+ get = staticmethod(_record("GET"))
+ post = staticmethod(_record("POST"))
+
+ monkeypatch.setattr(f"deeptutor.services.search.providers.{module}.requests", _FakeRequests)
+ return captured
+
+
[email protected](("module", "cls_name", "read_limit"), _NEW_PROVIDERS)
+def test_new_providers_carry_max_results_and_proxy(module, cls_name, read_limit, new_calls) -> None:
+ provider = _provider_class(module, cls_name)(api_key="k", proxy=PROXY)
+ provider.search("q", max_results=3)
+
+ call = new_calls[-1]
+ assert call["proxies"] == {"http": PROXY, "https": PROXY}
+ if read_limit is not None:
+ assert read_limit(call) == 3
+
+
[email protected](("module", "cls_name", "_read_limit"), _NEW_PROVIDERS)
+def test_new_provider_metadata_comes_from_the_spec_table(module, cls_name, _read_limit) -> None:
+ from deeptutor.services.config import SEARCH_PROVIDERS
+
+ cls = _provider_class(module, cls_name)
+ spec = SEARCH_PROVIDERS[cls.name]
+ assert cls.display_name == spec.label
+ assert cls.requires_api_key == spec.requires_api_key
+ assert cls.supports_answer == spec.supports_answer
+ # None of these can quietly become DuckDuckGo: the China-hosted ones would
+ # fall back onto a network where it is unreachable.
+ assert spec.soft_fallback is False
+
+
[email protected](("module", "cls_name", "_read_limit"), _NEW_PROVIDERS)
+def test_new_providers_accept_a_base_url_override(module, cls_name, _read_limit, new_calls) -> None:
+ """A self-hosted gateway has to be reachable without patching the class."""
+ provider = _provider_class(module, cls_name)(api_key="k")
+ provider.search("q", base_url="https://gateway.example/search")
+ assert new_calls[-1]["url"] == "https://gateway.example/search"
+
+
+def test_doubao_reads_answer_and_citations_off_annotations(monkeypatch) -> None:
+ """Ark returns the answer inline; sources live in url_citation annotations."""
+ body = {
+ "model": "doubao-seed-1-6-251015",
+ "status": "completed",
+ "output": [
+ {"type": "web_search_call", "id": "ws_1", "status": "completed"},
+ {
+ "type": "message",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": "答案。",
+ "annotations": [
+ {
+ "type": "url_citation",
+ "title": "T1",
+ "url": "https://e/1",
+ "site_name": "站点",
+ "publish_time": "2026-08-01",
+ "summary": "s1",
+ },
+ # Same source cited twice — must collapse to one.
+ {"type": "url_citation", "title": "T1", "url": "https://e/1"},
+ {"type": "url_citation", "title": "T2", "url": "https://e/2"},
+ ],
+ }
+ ],
+ },
+ ],
+ "usage": {"input_tokens": 11, "output_tokens": 22, "total_tokens": 33},
+ }
+
+ class _FakeRequests:
+ @staticmethod
+ def post(url: str, **kwargs: Any) -> _FakeResponse:
+ return _FakeResponse(body)
+
+ monkeypatch.setattr("deeptutor.services.search.providers.doubao.requests", _FakeRequests)
+
+ from deeptutor.services.search.providers.doubao import DoubaoProvider
+
+ result = DoubaoProvider(api_key="k").search("q")
+ assert result.answer == "答案。"
+ assert [c.url for c in result.citations] == ["https://e/1", "https://e/2"]
+ assert [c.id for c in result.citations] == [1, 2]
+ assert result.citations[0].website == "站点"
+ assert result.citations[0].date == "2026-08-01"
+ assert result.usage["total_tokens"] == 33
+
+
+def test_doubao_rejects_an_unknown_source() -> None:
+ from deeptutor.services.search.providers.doubao import DoubaoProvider
+
+ with pytest.raises(ValueError, match="Doubao source"):
+ DoubaoProvider(api_key="k").search("q", sources=["weibo"])
+
+
+def test_qianfan_maps_its_native_citation_fields(monkeypatch) -> None:
+ """Citation's web_anchor/icon/website fields came from this API's shape."""
+ body = {
+ "request_id": "r1",
+ "references": [
+ {
+ "id": 1,
+ "title": "T",
+ "url": "https://e/1",
+ "snippet": "s",
+ "content": "c",
+ "type": "web",
+ "date": "2026-08-01",
+ "web_anchor": "anchor",
+ "icon": "https://e/i.png",
+ "website": "站点",
+ }
+ ],
+ }
+
+ class _FakeRequests:
+ @staticmethod
+ def post(url: str, **kwargs: Any) -> _FakeResponse:
+ return _FakeResponse(body)
+
+ monkeypatch.setattr("deeptutor.services.search.providers.qianfan.requests", _FakeRequests)
+
+ from deeptutor.services.search.providers.qianfan import QianfanProvider
+
+ citation = QianfanProvider(api_key="k").search("q").citations[0]
+ assert citation.web_anchor == "anchor"
+ assert citation.website == "站点"
+ assert citation.icon == "https://e/i.png"
+ assert citation.type == "web"
+
+
+def test_aliyun_iqs_caps_results_client_side(monkeypatch) -> None:
+ """IQS always returns a page of 10; the cap has to be applied on our side."""
+ body = {
+ "requestId": "r1",
+ "pageItems": [
+ {
+ "title": f"t{i}",
+ "link": f"https://e/{i}",
+ "snippet": "s",
+ "mainText": "m",
+ # Milliseconds since epoch, not a date string.
+ "publishTime": 1754006400000,
+ "score": 0.5,
+ }
+ for i in range(10)
+ ],
+ "searchInformation": {"total": 100},
+ }
+
+ class _FakeRequests:
+ @staticmethod
+ def get(url: str, **kwargs: Any) -> _FakeResponse:
+ return _FakeResponse(body)
+
+ monkeypatch.setattr("deeptutor.services.search.providers.aliyun_iqs.requests", _FakeRequests)
+
+ from deeptutor.services.search.providers.aliyun_iqs import AliyunIQSProvider
+
+ result = AliyunIQSProvider(api_key="k").search("q", max_results=3)
+ assert len(result.search_results) == 3
+ assert len(result.citations) == 3
+ # The epoch stamp must not reach the model as a raw integer.
+ assert result.citations[0].date.count("-") == 2
+
+
+def test_bocha_surfaces_an_error_carried_inside_a_200(monkeypatch) -> None:
+ class _FakeRequests:
+ @staticmethod
+ def post(url: str, **kwargs: Any) -> _FakeResponse:
+ return _FakeResponse({"code": 403, "msg": "quota exhausted"})
+
+ monkeypatch.setattr("deeptutor.services.search.providers.bocha.requests", _FakeRequests)
+
+ from deeptutor.services.search.providers.bocha import BochaProvider
+
+ with pytest.raises(Exception, match="quota exhausted"):
+ BochaProvider(api_key="k").search("q")
diff --git a/tests/services/search/test_web_search_runtime.py b/tests/services/search/test_web_search_runtime.py
index 6551ffe50..a034cbb80 100644
--- a/tests/services/search/test_web_search_runtime.py
+++ b/tests/services/search/test_web_search_runtime.py
@@ -24,14 +24,35 @@ class _FakeProvider:
)
-def test_web_search_rejects_deprecated_provider(monkeypatch) -> None:
+class _FailingProvider(_FakeProvider):
+ def search(self, query: str, **kwargs):
+ raise RuntimeError("202 Ratelimit")
+
+
+def _patch_runtime(monkeypatch, resolved: ResolvedSearchConfig, **kwargs) -> None:
+ """Pin the resolved config and keep the fallback chain off the real catalog."""
monkeypatch.setattr(
"deeptutor.services.search._get_web_search_config",
lambda: {"enabled": True},
)
monkeypatch.setattr(
"deeptutor.services.search.resolve_search_runtime_config",
- lambda: ResolvedSearchConfig(
+ lambda: resolved,
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.search.search_fallback_candidates",
+ lambda _provider: list(kwargs.get("candidates", [])),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.search.search_provider_credentials",
+ lambda provider: kwargs.get("credentials", {}).get(provider, ("", "")),
+ )
+
+
+def test_web_search_rejects_deprecated_provider(monkeypatch) -> None:
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
provider="exa",
requested_provider="exa",
unsupported_provider=True,
@@ -43,13 +64,9 @@ def test_web_search_rejects_deprecated_provider(monkeypatch) -> None:
def test_web_search_perplexity_missing_key_hard_fails(monkeypatch) -> None:
- monkeypatch.setattr(
- "deeptutor.services.search._get_web_search_config",
- lambda: {"enabled": True},
- )
- monkeypatch.setattr(
- "deeptutor.services.search.resolve_search_runtime_config",
- lambda: ResolvedSearchConfig(
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
provider="perplexity",
requested_provider="perplexity",
api_key="",
@@ -57,7 +74,6 @@ def test_web_search_perplexity_missing_key_hard_fails(monkeypatch) -> None:
missing_credentials=True,
),
)
- monkeypatch.setattr("deeptutor.services.search._resolve_provider_key", lambda _p, _k: "")
with pytest.raises(ValueError, match="perplexity requires api_key"):
web_search("hello")
@@ -70,13 +86,9 @@ def test_web_search_missing_key_falls_back_to_duckduckgo(monkeypatch) -> None:
captured["kwargs"] = kwargs
return _FakeProvider(name)
- monkeypatch.setattr(
- "deeptutor.services.search._get_web_search_config",
- lambda: {"enabled": True},
- )
- monkeypatch.setattr(
- "deeptutor.services.search.resolve_search_runtime_config",
- lambda: ResolvedSearchConfig(
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
provider="brave",
requested_provider="brave",
api_key="",
@@ -85,7 +97,6 @@ def test_web_search_missing_key_falls_back_to_duckduckgo(monkeypatch) -> None:
proxy="http://127.0.0.1:7890",
),
)
- monkeypatch.setattr("deeptutor.services.search._resolve_provider_key", lambda _p, _k: "")
monkeypatch.setattr("deeptutor.services.search.get_provider", _fake_get_provider)
result = web_search("hello")
assert captured["provider"] == "duckduckgo"
@@ -103,13 +114,9 @@ def test_web_search_searxng_uses_base_url(monkeypatch) -> None:
captured["kwargs"] = kwargs
return _FakeProvider(name)
- monkeypatch.setattr(
- "deeptutor.services.search._get_web_search_config",
- lambda: {"enabled": True},
- )
- monkeypatch.setattr(
- "deeptutor.services.search.resolve_search_runtime_config",
- lambda: ResolvedSearchConfig(
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
provider="searxng",
requested_provider="searxng",
base_url="https://searx.example.com",
@@ -122,3 +129,78 @@ def test_web_search_searxng_uses_base_url(monkeypatch) -> None:
assert captured["kwargs"]["base_url"] == "https://searx.example.com"
assert captured["kwargs"]["max_results"] == 4
assert result["provider"] == "searxng"
+
+
+def test_web_search_runtime_failure_falls_through_the_chain(monkeypatch) -> None:
+ seen: list[tuple[str, dict]] = []
+
+ def _fake_get_provider(name: str, **kwargs):
+ seen.append((name, kwargs))
+ return _FailingProvider(name) if name == "serper" else _FakeProvider(name)
+
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
+ provider="serper",
+ requested_provider="serper",
+ api_key="serper-key",
+ max_results=5,
+ ),
+ candidates=["tavily", "duckduckgo"],
+ credentials={"tavily": ("tavily-key", "")},
+ )
+ monkeypatch.setattr("deeptutor.services.search.get_provider", _fake_get_provider)
+ result = web_search("hello")
+
+ assert [name for name, _ in seen] == ["serper", "tavily"]
+ assert result["provider"] == "tavily"
+ fallback = result["search_fallback"]
+ assert fallback["requested"] == "serper"
+ assert fallback["used"] == "tavily"
+ assert "202 Ratelimit" in fallback["failures"][0]
+ # The fallback provider runs on its own credentials, never the failed
+ # provider's key.
+ assert seen[1][1]["api_key"] == "tavily-key"
+
+
+def test_web_search_raises_when_every_candidate_fails(monkeypatch) -> None:
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
+ provider="brave",
+ requested_provider="brave",
+ api_key="brave-key",
+ max_results=5,
+ ),
+ candidates=["duckduckgo"],
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.search.get_provider",
+ lambda name, **kwargs: _FailingProvider(name),
+ )
+ with pytest.raises(Exception, match="brave: 202 Ratelimit; duckduckgo: 202 Ratelimit"):
+ web_search("hello")
+
+
+def test_web_search_explicit_provider_uses_its_own_key(monkeypatch) -> None:
+ captured: dict[str, object] = {}
+
+ def _fake_get_provider(name: str, **kwargs):
+ captured["provider"] = name
+ captured["kwargs"] = kwargs
+ return _FakeProvider(name, supports_answer=True)
+
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
+ provider="brave",
+ requested_provider="brave",
+ api_key="brave-key",
+ max_results=5,
+ ),
+ credentials={"tavily": ("tavily-key", "")},
+ )
+ monkeypatch.setattr("deeptutor.services.search.get_provider", _fake_get_provider)
+ web_search("hello", provider="tavily")
+ assert captured["provider"] == "tavily"
+ assert captured["kwargs"]["api_key"] == "tavily-key"
diff --git a/tests/test_openrouter_provider.py b/tests/test_openrouter_provider.py
deleted file mode 100644
index 0db058a7f..000000000
--- a/tests/test_openrouter_provider.py
+++ /dev/null
@@ -1,74 +0,0 @@
-import unittest
-from unittest.mock import MagicMock, patch
-
-from deeptutor.services.search.providers.openrouter import OpenRouterProvider
-from deeptutor.services.search.types import WebSearchResponse
-
-
-class TestOpenRouterProvider(unittest.TestCase):
- def setUp(self):
- self.api_key = "test-key"
- # Mock openai module
- self.mock_openai = MagicMock()
- self.mock_client = MagicMock()
- self.mock_openai.OpenAI.return_value = self.mock_client
-
- # Patch import
- self.patcher = patch.dict("sys.modules", {"openai": self.mock_openai})
- self.patcher.start()
-
- def tearDown(self):
- self.patcher.stop()
-
- def test_search_success_root_citations(self):
- """Test search with citations in root response (standard OpenRouter Perplexity)"""
- provider = OpenRouterProvider(api_key=self.api_key)
-
- # Mock response
- mock_completion = MagicMock()
- mock_completion.choices = [MagicMock()]
- mock_completion.choices[0].message.content = "Test answer"
- mock_completion.choices[0].finish_reason = "stop"
- mock_completion.model = "perplexity/sonar"
- mock_completion.usage.prompt_tokens = 10
- mock_completion.usage.completion_tokens = 20
- mock_completion.usage.total_tokens = 30
-
- # model_dump return value
- mock_completion.model_dump.return_value = {
- "citations": ["https://example.com/1", {"url": "https://example.com/2"}]
- }
-
- self.mock_client.chat.completions.create.return_value = mock_completion
-
- result = provider.search("test query")
-
- self.assertIsInstance(result, WebSearchResponse)
- self.assertEqual(result.answer, "Test answer")
- self.assertEqual(len(result.citations), 2)
- self.assertEqual(result.citations[0].url, "https://example.com/1")
- self.assertEqual(result.citations[1].url, "https://example.com/2")
- self.assertEqual(result.provider, "openrouter")
-
- def test_search_success_choice_citations(self):
- """Test search with citations in choice (alternative format)"""
- provider = OpenRouterProvider(api_key=self.api_key)
-
- mock_completion = MagicMock()
- mock_completion.choices = [MagicMock()]
- mock_completion.choices[0].message.content = "Test answer"
-
- mock_completion.model_dump.return_value = {
- "choices": [{"citations": ["https://example.com/choice"]}]
- }
-
- self.mock_client.chat.completions.create.return_value = mock_completion
-
- result = provider.search("test query")
-
- self.assertEqual(len(result.citations), 1)
- self.assertEqual(result.citations[0].url, "https://example.com/choice")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/web/components/common/ProviderIcon.tsx b/web/components/common/ProviderIcon.tsx
index ebde112f1..0d538ccbf 100644
--- a/web/components/common/ProviderIcon.tsx
+++ b/web/components/common/ProviderIcon.tsx
@@ -43,8 +43,12 @@ const PROVIDER_ICONS: Record<string, { file: string; mono?: boolean }> = {
qianfan: { file: "baiducloud-color.svg" },
cohere: { file: "cohere-color.svg" },
jina: { file: "jina.svg", mono: true },
- // Search providers (web/components/settings/shared.tsx). brave/duckduckgo/
- // searxng come from simple-icons with the brand color baked in.
+ // Search providers (see SEARCH_PROVIDERS in
+ // deeptutor/services/config/provider_runtime.py). brave/duckduckgo/searxng
+ // come from simple-icons with the brand color baked in. Keys shared with an
+ // LLM binding above (zhipu, qianfan) already resolve and are not repeated.
+ // A search provider with no vendored logo falls back to the generic Bot mark
+ // rather than borrowing an unrelated brand's.
tavily: { file: "tavily-color.svg" },
perplexity: { file: "perplexity-color.svg" },
exa: { file: "exa-color.svg" },
@@ -52,6 +56,9 @@ const PROVIDER_ICONS: Record<string, { file: string; mono?: boolean }> = {
duckduckgo: { file: "duckduckgo.svg" },
searxng: { file: "searxng.svg" },
baidu: { file: "baidu-color.svg" },
+ // Doubao is Volcengine's own model line, so it carries the Ark mark.
+ doubao: { file: "volcengine-color.svg" },
+ aliyun_iqs: { file: "qwen-color.svg" },
};
export default function ProviderIcon({
diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsx
index 45d9f6c57..759bb912a 100644
--- a/web/components/settings/ServiceConfigEditor.tsx
+++ b/web/components/settings/ServiceConfigEditor.tsx
@@ -44,13 +44,11 @@ import { nextProfileName } from "./profile-naming";
import { searchProviderFields } from "./search-providers";
import {
activeProfileDetail,
- deprecatedSearchProviders,
formatContextWindowSource,
inputClass,
selectClass,
selectOptionClass,
stringifyExtraHeaders,
- supportedSearchProviders,
} from "./shared";
const SERVICE_LABEL: Record<ServiceName, string> = {
@@ -134,14 +132,28 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
: "";
const showSearchProviderWarning =
service === "search" && Boolean(searchProviderRaw);
- const isDeprecatedSearchProvider =
- deprecatedSearchProviders.has(searchProviderRaw);
- const isSupportedSearchProvider = supportedSearchProviders.includes(
- searchProviderRaw as (typeof supportedSearchProviders)[number],
+ // Every judgement below reads the backend's own provider list, so the web app
+ // never keeps a second (and drifting) copy of what is supported.
+ const searchProviderOption = (providers.search || []).find(
+ (option) => option.value === searchProviderRaw,
);
- const isPerplexityMissingKey =
+ const isDeprecatedSearchProvider =
+ searchProviderOption?.status === "deprecated";
+ const isSupportedSearchProvider =
+ Boolean(searchProviderOption) && !isDeprecatedSearchProvider;
+ const supportedSearchProviderNames = (providers.search || [])
+ .filter(
+ (option) => option.status !== "deprecated" && option.value !== "none",
+ )
+ .map((option) => option.value)
+ .join("/");
+ // Providers that fail hard rather than falling back need their key before the
+ // first query — say so while the user is still on this screen.
+ const searchProviderMissingKey =
service === "search" &&
- searchProviderRaw === "perplexity" &&
+ isSupportedSearchProvider &&
+ searchProviderOption?.requires_api_key === true &&
+ searchProviderOption?.soft_fallback === false &&
!String(activeProfile?.api_key || "").trim();
const activeLlmDetection =
service === "llm" &&
@@ -472,7 +484,8 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {
showSearchProviderWarning={showSearchProviderWarning}
isSupportedSearchProvider={isSupportedSearchProvider}
isDeprecatedSearchProvider={isDeprecatedSearchProvider}
- isPerplexityMissingKey={isPerplexityMissingKey}
+ searchProviderMissingKey={searchProviderMissingKey}
+ supportedSearchProviderNames={supportedSearchProviderNames}
onProviderChanged={(provider, previousProvider) => {
if (service !== "llm" || !activeProfile) return;
const crossesCodeBuddyBoundary =
@@ -1154,7 +1167,8 @@ function ProfileFields({
showSearchProviderWarning,
isSupportedSearchProvider,
isDeprecatedSearchProvider,
- isPerplexityMissingKey,
+ searchProviderMissingKey,
+ supportedSearchProviderNames,
onProviderChanged,
}: {
service: ServiceName;
@@ -1164,7 +1178,8 @@ function ProfileFields({
showSearchProviderWarning: boolean;
isSupportedSearchProvider: boolean;
isDeprecatedSearchProvider: boolean;
- isPerplexityMissingKey: boolean;
+ searchProviderMissingKey: boolean;
+ supportedSearchProviderNames: string;
onProviderChanged: (
provider: ProviderOption,
previousProvider: string,
@@ -1192,9 +1207,9 @@ function ProfileFields({
isCodexOAuth || isCodeBuddyAuth
? { apiKey: false, baseUrl: false, baseUrlRequired: false }
: service === "search"
- ? searchProviderFields(profile.provider)
+ ? searchProviderFields(profile.provider, providerOption)
: { apiKey: true, baseUrl: true, baseUrlRequired: false };
- const searxngMissingBaseUrl =
+ const missingRequiredBaseUrl =
fields.baseUrlRequired && !String(profile.base_url || "").trim();
return (
@@ -1261,15 +1276,17 @@ function ProfileFields({
<option className={selectOptionClass} value="">
{t("Select provider...")}
</option>
- {(providers[service] || []).map((p) => (
- <option
- className={selectOptionClass}
- key={p.value}
- value={p.value}
- >
- {p.label}
- </option>
- ))}
+ {(providers[service] || [])
+ .filter((p) => p.status !== "deprecated")
+ .map((p) => (
+ <option
+ className={selectOptionClass}
+ key={p.value}
+ value={p.value}
+ >
+ {p.label}
+ </option>
+ ))}
</select>
<ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--muted-foreground)]" />
</div>
@@ -1284,18 +1301,19 @@ function ProfileFields({
}`}
>
{isSupportedSearchProvider
- ? isPerplexityMissingKey
+ ? searchProviderMissingKey
? t(
- "Perplexity requires API key. It will fail hard without credentials.",
+ "{{provider}} requires an API key. It will fail hard without credentials.",
+ { provider: providerOption?.label ?? providerValue },
)
: t("Supported provider.")
: isDeprecatedSearchProvider
- ? t(
- "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.",
- )
- : t(
- "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.",
- )}
+ ? t("Deprecated provider. Switch to one of: {{providers}}.", {
+ providers: supportedSearchProviderNames,
+ })
+ : t("Unsupported provider. Use one of: {{providers}}.", {
+ providers: supportedSearchProviderNames,
+ })}
</p>
)}
</div>
@@ -1335,7 +1353,7 @@ function ProfileFields({
)}
</p>
)}
- {searxngMissingBaseUrl && (
+ {missingRequiredBaseUrl && (
<p className="mt-1.5 text-[11px] text-amber-600 dark:text-amber-400">
{t("Required — without it, search falls back to DuckDuckGo.")}
</p>
diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsx
index acbd146f0..d53ea79ba 100644
--- a/web/components/settings/SettingsContext.tsx
+++ b/web/components/settings/SettingsContext.tsx
@@ -171,6 +171,13 @@ export type ProviderOption = {
default_model?: string;
default_voice?: string;
auth_mode?: "api_key" | "oauth";
+ // Search providers only, from the backend SEARCH_PROVIDERS spec table:
+ // which connection fields the provider consumes, whether missing ones fall
+ // back to a free provider or fail hard, and whether it is still offered.
+ requires_api_key?: boolean;
+ requires_base_url?: boolean;
+ soft_fallback?: boolean;
+ status?: "supported" | "deprecated";
};
export type SystemStatus = {
diff --git a/web/components/settings/search-providers.ts b/web/components/settings/search-providers.ts
index d089480f2..982662a51 100644
--- a/web/components/settings/search-providers.ts
+++ b/web/components/settings/search-providers.ts
@@ -1,15 +1,17 @@
// Which connection fields a web-search provider actually uses.
//
-// This mirrors the backend resolver in
-// `deeptutor/services/config/provider_runtime.py`
-// (`resolve_search_runtime_config`): brave/tavily/jina/perplexity/serper
-// authenticate with an API key, searxng is configured by its instance Base
-// URL, and duckduckgo/none need no connection details at all. Every search
-// provider ships an empty `base_url` from the settings API
-// (`_provider_choices` in `deeptutor/api/routers/settings.py`), so the Base
-// URL only ever carries a value for searxng.
+// The answer comes from the backend spec table
+// (`SEARCH_PROVIDERS` in `deeptutor/services/config/provider_runtime.py`),
+// served per provider by `_provider_choices` in
+// `deeptutor/api/routers/settings.py`. There is deliberately no provider table
+// here — a second copy is how the web app ended up flagging Serper as
+// deprecated while the backend supported it.
//
-// Keep this table in sync with SUPPORTED_SEARCH_PROVIDERS on the backend.
+// Until the choices load (and for a custom or retired provider name that has no
+// entry), every field is shown: better an extra control than a hidden one the
+// provider actually needs.
+
+import type { ProviderOption } from "./SettingsContext";
export type SearchProviderFieldSpec = {
/** Provider authenticates with an API key. */
@@ -20,52 +22,29 @@ export type SearchProviderFieldSpec = {
baseUrlRequired: boolean;
};
-const KEY_ONLY: SearchProviderFieldSpec = {
- apiKey: true,
- baseUrl: false,
- baseUrlRequired: false,
-};
-
-const NO_CREDENTIALS: SearchProviderFieldSpec = {
- apiKey: false,
- baseUrl: false,
- baseUrlRequired: false,
-};
-
-const BASE_URL_ONLY: SearchProviderFieldSpec = {
- apiKey: false,
- baseUrl: true,
- baseUrlRequired: true,
-};
-
-// Providers we don't model (a custom/unknown value, the deprecated
-// exa/baidu/openrouter set, or an empty selection): show every field so we
-// never hide a control the provider might actually need.
-const UNKNOWN: SearchProviderFieldSpec = {
+const ALL_FIELDS: SearchProviderFieldSpec = {
apiKey: true,
baseUrl: true,
baseUrlRequired: false,
};
-const SEARCH_PROVIDER_FIELDS: Record<string, SearchProviderFieldSpec> = {
- none: NO_CREDENTIALS,
- duckduckgo: NO_CREDENTIALS,
- searxng: BASE_URL_ONLY,
- brave: KEY_ONLY,
- tavily: KEY_ONLY,
- jina: KEY_ONLY,
- perplexity: KEY_ONLY,
- serper: KEY_ONLY,
-};
-
/**
- * Resolve which connection fields to show for a search provider. Unknown,
- * custom, or empty provider names fall back to showing every field.
+ * Resolve which connection fields to show for a search provider, given the
+ * backend option describing it. Unknown, custom, retired, or not-yet-loaded
+ * providers fall back to showing every field.
*/
export function searchProviderFields(
provider: string | null | undefined,
+ option?: ProviderOption | null,
): SearchProviderFieldSpec {
const key = (provider ?? "").trim().toLowerCase();
- if (!key) return UNKNOWN;
- return SEARCH_PROVIDER_FIELDS[key] ?? UNKNOWN;
+ if (!key) return ALL_FIELDS;
+ if (!option || option.status === "deprecated") return ALL_FIELDS;
+ if (option.requires_api_key === undefined) return ALL_FIELDS;
+ const baseUrl = Boolean(option.requires_base_url);
+ return {
+ apiKey: Boolean(option.requires_api_key),
+ baseUrl,
+ baseUrlRequired: baseUrl,
+ };
}
diff --git a/web/components/settings/shared.tsx b/web/components/settings/shared.tsx
index b5a976910..5772fba7c 100644
--- a/web/components/settings/shared.tsx
+++ b/web/components/settings/shared.tsx
@@ -14,22 +14,6 @@ export const selectClass = `${nativeSelectClass} appearance-none`;
export const selectOptionClass =
"bg-[var(--background)] text-[var(--foreground)]";
-export const supportedSearchProviders = [
- "brave",
- "tavily",
- "jina",
- "searxng",
- "duckduckgo",
- "perplexity",
-] as const;
-
-export const deprecatedSearchProviders = new Set([
- "exa",
- "serper",
- "baidu",
- "openrouter",
-]);
-
export function stringifyExtraHeaders(
value: CatalogProfile["extra_headers"],
): string {
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index d2a115ae2..ef35616a4 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -741,11 +741,11 @@
"Delete profile": "Delete profile",
"Provider Hint / Binding": "Provider Hint / Binding",
"Select provider...": "Select provider...",
- "Perplexity requires API key. It will fail hard without credentials.": "Perplexity requires API key. It will fail hard without credentials.",
+ "{{provider}} requires an API key. It will fail hard without credentials.": "{{provider}} requires an API key. It will fail hard without credentials.",
"Supported provider.": "Supported provider.",
"Required — without it, search falls back to DuckDuckGo.": "Required — without it, search falls back to DuckDuckGo.",
- "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.": "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.",
- "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.": "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.",
+ "Deprecated provider. Switch to one of: {{providers}}.": "Deprecated provider. Switch to one of: {{providers}}.",
+ "Unsupported provider. Use one of: {{providers}}.": "Unsupported provider. Use one of: {{providers}}.",
"API Version": "API Version",
"Proxy": "Proxy",
"Extra Headers (JSON)": "Extra Headers (JSON)",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 596d1b06c..ee327f130 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -745,11 +745,11 @@
"Permanently remove the currently selected profile.": "永久删除当前选中的配置文件。",
"Provider Hint / Binding": "提供商提示 / 绑定",
"Select provider...": "选择提供商...",
- "Perplexity requires API key. It will fail hard without credentials.": "Perplexity 需要 API 密钥,缺少凭证将无法使用。",
+ "{{provider}} requires an API key. It will fail hard without credentials.": "{{provider}} 需要 API 密钥,缺少凭证将无法使用。",
"Supported provider.": "受支持的提供商。",
"Required — without it, search falls back to DuckDuckGo.": "必填——缺少它,搜索将回退到 DuckDuckGo。",
- "Deprecated provider. Switch to brave/tavily/jina/searxng/duckduckgo/perplexity.": "已弃用的提供商。请切换到 brave/tavily/jina/searxng/duckduckgo/perplexity。",
- "Unsupported provider. Use brave/tavily/jina/searxng/duckduckgo/perplexity.": "不受支持的提供商。请使用 brave/tavily/jina/searxng/duckduckgo/perplexity。",
+ "Deprecated provider. Switch to one of: {{providers}}.": "已弃用的提供商。请切换到:{{providers}}。",
+ "Unsupported provider. Use one of: {{providers}}.": "不受支持的提供商。请使用:{{providers}}。",
"API Version": "API 版本",
"Proxy": "代理",
"Extra (optional)": "Extra(可选)",
diff --git a/web/tests/search-providers.test.ts b/web/tests/search-providers.test.ts
index cdb766d91..a09fb8e61 100644
--- a/web/tests/search-providers.test.ts
+++ b/web/tests/search-providers.test.ts
@@ -2,11 +2,52 @@ import test from "node:test";
import assert from "node:assert/strict";
import { searchProviderFields } from "../components/settings/search-providers";
+import type { ProviderOption } from "../components/settings/SettingsContext";
+
+// Options as `/api/v1/settings/provider-choices` serves them, derived from the
+// backend SEARCH_PROVIDERS spec table. The web app owns no provider table of its
+// own, so these fixtures are the contract under test.
+const option = (
+ value: string,
+ label: string,
+ extra: Partial<ProviderOption> = {},
+): ProviderOption => ({
+ value,
+ label,
+ base_url: "",
+ requires_api_key: false,
+ requires_base_url: false,
+ soft_fallback: true,
+ status: "supported",
+ ...extra,
+});
+
+const OPTIONS: Record<string, ProviderOption> = {
+ none: option("none", "None"),
+ brave: option("brave", "Brave", { requires_api_key: true }),
+ tavily: option("tavily", "Tavily", { requires_api_key: true }),
+ jina: option("jina", "Jina", { requires_api_key: true }),
+ searxng: option("searxng", "SearXNG", { requires_base_url: true }),
+ duckduckgo: option("duckduckgo", "DuckDuckGo"),
+ perplexity: option("perplexity", "Perplexity", {
+ requires_api_key: true,
+ soft_fallback: false,
+ }),
+ serper: option("serper", "Serper", {
+ requires_api_key: true,
+ soft_fallback: false,
+ }),
+ exa: option("exa", "exa", { status: "deprecated" }),
+ baidu: option("baidu", "baidu", { status: "deprecated" }),
+ openrouter: option("openrouter", "openrouter", { status: "deprecated" }),
+};
+
+const ALL_FIELDS = { apiKey: true, baseUrl: true, baseUrlRequired: false };
test("key-based providers show only the API key field", () => {
for (const provider of ["brave", "tavily", "jina", "perplexity", "serper"]) {
assert.deepEqual(
- searchProviderFields(provider),
+ searchProviderFields(provider, OPTIONS[provider]),
{ apiKey: true, baseUrl: false, baseUrlRequired: false },
`expected ${provider} to require only an API key`,
);
@@ -14,7 +55,7 @@ test("key-based providers show only the API key field", () => {
});
test("searxng shows only a required Base URL", () => {
- assert.deepEqual(searchProviderFields("searxng"), {
+ assert.deepEqual(searchProviderFields("searxng", OPTIONS.searxng), {
apiKey: false,
baseUrl: true,
baseUrlRequired: true,
@@ -24,70 +65,45 @@ test("searxng shows only a required Base URL", () => {
test("zero-config providers show no connection fields", () => {
for (const provider of ["duckduckgo", "none"]) {
assert.deepEqual(
- searchProviderFields(provider),
+ searchProviderFields(provider, OPTIONS[provider]),
{ apiKey: false, baseUrl: false, baseUrlRequired: false },
`expected ${provider} to need no credentials`,
);
}
});
-test("unknown, deprecated, and empty providers fall back to showing every field", () => {
- // Deprecated (exa/baidu/openrouter), a custom value, and no selection must
- // never hide a control we can't reason about.
- for (const provider of [
- "exa",
- "baidu",
- "openrouter",
- "custom-thing",
- "",
- null,
- undefined,
- ]) {
+test("deprecated providers fall back to showing every field", () => {
+ for (const provider of ["exa", "baidu", "openrouter"]) {
assert.deepEqual(
- searchProviderFields(provider),
- { apiKey: true, baseUrl: true, baseUrlRequired: false },
- `expected ${String(provider)} to show all fields`,
+ searchProviderFields(provider, OPTIONS[provider]),
+ ALL_FIELDS,
+ `expected ${provider} to show all fields`,
);
}
});
-test("provider name is matched case-insensitively and trimmed", () => {
- assert.deepEqual(searchProviderFields(" Brave "), {
- apiKey: true,
- baseUrl: false,
- baseUrlRequired: false,
- });
- assert.deepEqual(searchProviderFields("SearXNG"), {
- apiKey: false,
- baseUrl: true,
- baseUrlRequired: true,
- });
+test("unknown, unloaded, and empty providers fall back to showing every field", () => {
+ // Before the choices arrive there is no option to read, and a custom value has
+ // no option at all — never hide a control we can't reason about.
+ for (const provider of ["custom-thing", "brave", "", null, undefined]) {
+ assert.deepEqual(
+ searchProviderFields(provider, undefined),
+ ALL_FIELDS,
+ `expected ${String(provider)} with no option to show all fields`,
+ );
+ }
+ // An option from an older backend that predates the credential flags.
+ assert.deepEqual(
+ searchProviderFields("brave", { value: "brave", label: "Brave" }),
+ ALL_FIELDS,
+ );
});
-// The 8 providers the backend offers in the Search dropdown
-// (deeptutor/api/routers/settings.py:_provider_choices) plus a few
-// off-list values. Keep in sync if the backend adds a provider.
-const ALL_PROVIDERS = [
- "none",
- "brave",
- "tavily",
- "jina",
- "searxng",
- "duckduckgo",
- "perplexity",
- "serper",
- "exa",
- "baidu",
- "openrouter",
- "custom",
- "",
-];
-
test("a required Base URL is never hidden (baseUrlRequired implies baseUrl)", () => {
// A field that is mandatory but not rendered would be an unfixable
// configuration — guard the whole matrix against that state.
- for (const provider of ALL_PROVIDERS) {
- const fields = searchProviderFields(provider);
+ for (const [provider, opt] of Object.entries(OPTIONS)) {
+ const fields = searchProviderFields(provider, opt);
if (fields.baseUrlRequired) {
assert.ok(
fields.baseUrl,
@@ -98,8 +114,10 @@ test("a required Base URL is never hidden (baseUrlRequired implies baseUrl)", ()
});
test("searxng is the only provider that requires a Base URL", () => {
- const requiring = ALL_PROVIDERS.filter(
- (p) => searchProviderFields(p).baseUrlRequired,
- );
+ const requiring = Object.entries(OPTIONS)
+ .filter(
+ ([provider, opt]) => searchProviderFields(provider, opt).baseUrlRequired,
+ )
+ .map(([provider]) => provider);
assert.deepEqual(requiring, ["searxng"]);
});