Merge PR #2533: feat(search): add DeepSeek standalone SERP provider

This commit is contained in:
Bingxi Zhao (Frank)
2026-11-14 23:00:23 +08:00
6 changed files with 312 additions and 0 deletions

View File

@@ -121,6 +121,9 @@ SEARCH_PROVIDERS: dict[str, SearchProviderSpec] = {
"aliyun_iqs": SearchProviderSpec(
label="Aliyun IQS", requires_api_key=True, soft_fallback=False
),
# DeepSeek's standalone SERP engine (``POST /v1/tools/search``) — usable
# with any chat LLM, unlike the model-side web_search tool mapping.
"deepseek": SearchProviderSpec(label="DeepSeek", requires_api_key=True, soft_fallback=False),
}
# The credential-free provider every soft fallback lands on.

View File

@@ -173,6 +173,7 @@ def _register_builtin_providers() -> None:
aliyun_iqs,
bocha,
brave,
deepseek,
doubao,
duckduckgo,
firecrawl,
@@ -192,6 +193,7 @@ def _register_builtin_providers() -> None:
aliyun_iqs,
bocha,
brave,
deepseek,
doubao,
duckduckgo,
firecrawl,

View File

@@ -0,0 +1,136 @@
"""DeepSeek search provider.
API: https://api-docs.deepseek.com/guides/search/
Endpoint: POST https://api.deepseek.com/v1/tools/search
Standalone SERP access to DeepSeek's in-house search engine, usable with any
configured chat LLM — unlike the model-side ``web_search`` tool mapping, which
only applies when the LLM itself is a DeepSeek model. Rows are plain SERP
results with no model-written answer, so consolidation still supplies the
answer.
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from urllib.parse import urlsplit
import requests
from ..base import BaseSearchProvider
from ..types import Citation, SearchResult, WebSearchResponse
from . import register_provider
@register_provider("deepseek")
class DeepSeekProvider(BaseSearchProvider):
"""DeepSeek Search API (``POST /v1/tools/search``) results."""
description = "DeepSeek in-house search engine results"
BASE_URL = "https://api.deepseek.com/v1/tools/search"
API_KEY_ENV_VARS = ("DEEPSEEK_API_KEY", "SEARCH_API_KEY")
def search(
self,
query: str,
max_results: int = 5,
need_content: bool = False,
timeout: int = 30,
**kwargs: Any,
) -> WebSearchResponse:
"""Search DeepSeek.
Args:
query: Search query (1-128 chars; supports ``site:``, ``lang:``,
``after:``/``before:`` and quoted-phrase operators verbatim).
max_results: Result cap. DeepSeek's own ``count`` accepts 1-50.
need_content: Ask for each page's body as Markdown in
``SearchResult.content``. Off by default so a wide query cannot
push megabytes of page text into consolidation.
timeout: Request timeout in seconds.
**kwargs: Additional options, including ``base_url``, used
verbatim as the endpoint for a self-hosted gateway.
Returns:
WebSearchResponse: Standardized search response.
"""
if not self.api_key:
raise ValueError("DeepSeek requires an API key in Settings > Search.")
endpoint = str(kwargs.get("base_url") or self.BASE_URL)
count = max(1, min(int(max_results), 50))
payload = {
"query": query,
"count": count,
"need_content": bool(need_content),
}
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"DeepSeek API error: {resp.status_code} - {resp.text}")
rows = [row for row in resp.json().get("results") or [] if isinstance(row, dict)]
rows = rows[:count]
citations: list[Citation] = []
search_results: list[SearchResult] = []
for idx, row in enumerate(rows, 1):
result = _parse_row(row)
search_results.append(result)
citations.append(
Citation(
id=idx,
reference=f"[{idx}]",
url=result.url,
title=result.title,
snippet=result.snippet,
date=result.date,
source=result.source,
content=result.content,
icon=str(row.get("site_icon") or ""),
website=str(row.get("site_name") or ""),
)
)
return WebSearchResponse(
query=query,
answer="",
provider="deepseek",
timestamp=datetime.now().isoformat(),
model="deepseek-search",
citations=citations,
search_results=search_results,
metadata={"finish_reason": "stop"},
)
def _parse_row(row: dict[str, Any]) -> SearchResult:
"""Map one DeepSeek row onto ``SearchResult``.
``summary`` (600-800 chars) is written to be read by a model, so it wins
over the UI-facing ``snippet``; ``content`` carries the page body when
``need_content`` was set. ``authority`` (0-4) and ``rerank_score`` (0-3)
have no slot on ``SearchResult`` and travel in ``attributes``.
"""
url = str(row.get("url", ""))
site_name = str(row.get("site_name") or "")
host = urlsplit(url).hostname if url.startswith(("http://", "https://")) else ""
attributes: dict[str, Any] = {}
if row.get("authority") is not None:
attributes["authority"] = row["authority"]
if row.get("rerank_score") is not None:
attributes["rerank_score"] = row["rerank_score"]
return SearchResult(
title=str(row.get("title", "") or ""),
url=url,
snippet=str(row.get("summary") or row.get("snippet") or ""),
date=str(row.get("date") or ""),
source=site_name or host or "DeepSeek",
content=str(row.get("content") or ""),
attributes=attributes,
)

View File

@@ -227,6 +227,13 @@ SEARCH_PROVIDERS: tuple[SearchProviderSpec, ...] = (
env_keys=("ALIYUN_IQS_API_KEY", "IQS_API_KEY", "SEARCH_API_KEY"),
hint="China-hosted · reranked results",
),
SearchProviderSpec(
name="deepseek",
label="DeepSeek (深度求索)",
requires_api_key=True,
env_keys=("DEEPSEEK_API_KEY", "SEARCH_API_KEY"),
hint="own engine · optional page bodies · billed per request",
),
SearchProviderSpec(
name="duckduckgo",
label="DuckDuckGo",

View File

@@ -131,6 +131,7 @@ _EMPTY_BODY: dict[str, Any] = {
"references": [], # qianfan
"pageItems": [], # aliyun_iqs
"output": [], # doubao
"results": [], # deepseek
}
@@ -148,6 +149,7 @@ _NEW_PROVIDERS = [
# 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),
("deepseek", "DeepSeekProvider", _limit_in_json("count")),
]
@@ -624,6 +626,167 @@ def test_youcom_surfaces_http_errors(monkeypatch) -> None:
YouComProvider(api_key="k").search("q")
# --------------------------------------------------------------------------
# DeepSeek: the standalone SERP engine (`POST /v1/tools/search`), separate
# from DeepSeek's model-side web_search tool. Billed per request, so a missing
# key raises instead of falling through to DuckDuckGo.
# --------------------------------------------------------------------------
_DEEPSEEK_BODY: dict[str, Any] = {
"results": [
{
"rerank_score": 2.4,
"title": "DeepSeek V4 model released",
"url": "https://example.com/deepseek-v4",
"snippet": "DeepSeek V4 is now available, with tool calling support.",
"summary": "DeepSeek has released the V4 model. The release adds improved tool calling.",
"content": "",
"site_name": "Example News",
"site_icon": "https://example.com/favicon.ico",
"date": "2026-06-01T00:00:00+00:00",
"authority": 3,
},
# Bare row: no summary, no site_name — the model-facing blurb falls
# back to `snippet` and the source to the URL host.
{
"title": "Bare row",
"url": "https://example.org/bare",
"snippet": "Snippet only",
},
]
}
@pytest.fixture
def deepseek_calls(monkeypatch):
captured: list[dict[str, Any]] = []
def _post(url: str, **kwargs: Any) -> _FakeResponse:
captured.append({"method": "POST", "url": url, **kwargs})
return _FakeResponse(_DEEPSEEK_BODY)
class _FakeRequests:
post = staticmethod(_post)
monkeypatch.setattr("deeptutor.services.search.providers.deepseek.requests", _FakeRequests)
return captured
def test_deepseek_rejects_missing_key_before_network(deepseek_calls, monkeypatch) -> None:
from deeptutor.services.search.providers.deepseek import DeepSeekProvider
monkeypatch.setattr(DeepSeekProvider, "_get_api_key", lambda self: "")
with pytest.raises(ValueError, match="requires an API key"):
DeepSeekProvider(proxy=PROXY).search("attention")
assert deepseek_calls == []
def test_deepseek_posts_bearer_query_count_and_need_content(deepseek_calls) -> None:
from deeptutor.services.search.providers.deepseek import DeepSeekProvider
DeepSeekProvider(api_key="k").search("attention", max_results=3)
DeepSeekProvider(api_key="k").search("attention", max_results=3, need_content=True)
default_call, content_call = deepseek_calls[-2:]
assert default_call["url"] == "https://api.deepseek.com/v1/tools/search"
assert default_call["headers"]["Authorization"] == "Bearer k"
assert default_call["json"] == {"query": "attention", "count": 3, "need_content": False}
assert content_call["json"]["need_content"] is True
def test_deepseek_prefers_summary_and_carries_ranking_attributes(deepseek_calls) -> None:
from deeptutor.services.search.providers.deepseek import DeepSeekProvider
response = DeepSeekProvider(api_key="k").search("attention", max_results=2)
assert response.provider == "deepseek"
assert response.answer == ""
assert response.model == "deepseek-search"
first, second = response.search_results
assert first.title == "DeepSeek V4 model released"
assert (
first.snippet
== "DeepSeek has released the V4 model. The release adds improved tool calling."
)
assert first.source == "Example News"
assert first.date == "2026-06-01T00:00:00+00:00"
assert first.attributes == {"authority": 3, "rerank_score": 2.4}
assert second.snippet == "Snippet only"
assert second.source == "example.org"
assert second.attributes == {}
citation = response.citations[0]
assert citation.reference == "[1]"
assert citation.icon == "https://example.com/favicon.ico"
assert citation.website == "Example News"
def test_deepseek_keeps_page_markdown_when_present(monkeypatch) -> None:
body = {
"results": [
{
"title": "Page",
"url": "https://e/1",
"snippet": "s",
"summary": "long summary",
"content": "# Page\n\nbody markdown",
}
]
}
class _FakeRequests:
@staticmethod
def post(url: str, **kwargs: Any) -> _FakeResponse:
return _FakeResponse(body)
monkeypatch.setattr("deeptutor.services.search.providers.deepseek.requests", _FakeRequests)
from deeptutor.services.search.providers.deepseek import DeepSeekProvider
response = DeepSeekProvider(api_key="k").search("q", need_content=True)
(row,) = response.search_results
assert row.snippet == "long summary"
assert row.content == "# Page\n\nbody markdown"
assert response.citations[0].content == "# Page\n\nbody markdown"
def test_deepseek_metadata_comes_from_the_spec_table() -> None:
from deeptutor.services.config import SEARCH_PROVIDERS
from deeptutor.services.search.providers import list_providers
from deeptutor.services.search.providers.deepseek import DeepSeekProvider
spec = SEARCH_PROVIDERS["deepseek"]
assert "deepseek" in list_providers()
assert DeepSeekProvider.display_name == spec.label
assert DeepSeekProvider.requires_api_key is True
assert DeepSeekProvider.supports_answer is False
# Paid per-request engine: never quietly turn a billed key into DuckDuckGo.
assert spec.soft_fallback is False
@pytest.mark.parametrize("status", [401, 402, 429])
def test_deepseek_surfaces_http_errors(monkeypatch, status) -> None:
class _ErrorResponse:
text = "error body"
def __init__(self) -> None:
self.status_code = status
def json(self) -> dict[str, Any]:
return {}
class _FakeRequests:
@staticmethod
def post(url: str, **kwargs: Any) -> _ErrorResponse:
return _ErrorResponse()
monkeypatch.setattr("deeptutor.services.search.providers.deepseek.requests", _FakeRequests)
from deeptutor.services.search.providers.deepseek import DeepSeekProvider
with pytest.raises(Exception, match=f"{status} - error body"):
DeepSeekProvider(api_key="k").search("q")
def test_perplexity_client_sends_integration_header() -> None:
from perplexity._models import FinalRequestOptions

View File

@@ -567,6 +567,7 @@ const PROVIDER_LABELS: Record<string, string> = {
iqs: "IQS",
bocha: "Bocha",
zhipu: "Zhipu",
deepseek: "DeepSeek",
};
function providerLabel(slug: string): string {