Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(tools): refine DeepSeek search credentials and query validation
chengyongrudca49c258a9d
diff --git a/docs/configuration.md b/docs/configuration.mdindex 650734ae5..cc5c22334 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -2074,7 +2074,7 @@ AnySearch works out of the box with no key, via its anonymous quota (lower rate"web": {"search": {"provider": "deepseek",- "apiKey": "${DEEPSEEK_API_KEY}"+ "apiKey": "${DEEPSEEK_SEARCH_KEY}"}}}@@ -2083,16 +2083,9 @@ AnySearch works out of the box with no key, via its anonymous quota (lower rate</details>-This provider calls the standalone [DeepSeek Search API](https://api-docs.deepseek.com/zh-cn/guides/search/) (`POST https://api.deepseek.com/v1/tools/search`). It is a separate web-search backend and is **not** the same as the provider-hosted web search that DeepSeek models can run inside a chat request; selecting `deepseek` here does not change the DeepSeek LLM provider or inject any tool into model requests.+Create a key at [platform.deepseek.com](https://platform.deepseek.com). Set `tools.web.search.apiKey` directly or with a `${VAR_NAME}` reference. Missing credentials cause a configuration error, with no provider fallback.-- Create a key at [platform.deepseek.com](https://platform.deepseek.com). The key can also come from the `DEEPSEEK_API_KEY` environment variable. Without a key, nanobot falls back to DuckDuckGo, like the other keyed search providers.-- Billing is per successful request: ¥5 per 1,000 requests. Requests that fail, time out, or return no results are not billed. `count` only changes the number of results and not the price.-- The account limit is 5 QPS. nanobot retries HTTP 408, 429, and 5xx responses once after one second before reporting the failure; other 4xx responses are not retried.-- A query is limited to 128 Unicode characters. nanobot trims surrounding whitespace and truncates longer queries locally, so no request that would fail with HTTP 400 is sent.-- Search syntax is passed through unchanged: `site:`, `-site:`, `-`, `-"..."`, `"..."`, `lang:`, `after:`, and `before:`. For example: `DeepSeek models site:github.com lang:zh after:2025`.-- Results use the API's `summary`, falling back to `snippet` when a summary is missing. Each result's text is capped at 500 characters, because real responses can be several times longer than the documented 600–800, and ten uncapped summaries would cost around 10k tokens per call. The publication date is included when the API returns one.--nanobot requests results without page bodies (`need_content: false`), so full page text is not added to the model's context. Use `web_fetch` when you need the page content.+Queries are limited to 128 Unicode characters after trimming whitespace; longer queries are rejected. Pricing is ¥5 per 1,000 successful requests, with an account-wide limit of 5 QPS across API keys. See the [DeepSeek Search API documentation](https://api-docs.deepseek.com/zh-cn/guides/search/) for search syntax and billing details.#### `tools.web.search`diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.pyindex b11e5a976..1d81565a0 100644--- a/nanobot/agent/tools/web.py+++ b/nanobot/agent/tools/web.py@@ -24,7 +24,11 @@ from nanobot.agent.tools.schema import (StringSchema,tool_parameters_schema,)-from nanobot.agent.tools.web_config import WebFetchConfig, WebSearchConfig, WebToolsConfig+from nanobot.agent.tools.web_config import (+ WebFetchConfig,+ WebSearchConfig,+ WebToolsConfig,+)from nanobot.utils.helpers import build_image_content_blocks# Shared constants@@ -43,8 +47,7 @@ _DEEPSEEK_MAX_RESULTS = 50# Ten uncapped summaries would otherwise cost roughly 10k tokens per call._DEEPSEEK_MAX_SUMMARY_CHARS = 500_DEEPSEEK_ERROR_DETAIL_MAX_CHARS = 300-# One retry after a transient status, matching the Brave provider. A one-second-# wait also puts the next attempt below the account-wide limit of 5 QPS.+# One retry after a transient status; this does not coordinate account-wide QPS._DEEPSEEK_RETRY_DELAY_S = 1.0_VOLCENGINE_SEARCH_API_URL = "https://open.feedcoopapi.com/search_api/web_search"_VOLCENGINE_TRAFFIC_TAG = "nanobot"@@ -306,20 +309,6 @@ def _format_results(query: str, items: list[dict[str, Any]], n: int) -> str:return "\n".join(lines)-def _normalize_deepseek_query(query: str) -> str | None:- """Trim and clamp a query to the Search API's 1-128 character window.-- Truncation counts Unicode code points, not bytes, so CJK and emoji queries- are cut at the documented boundary instead of splitting a multi-byte- sequence. Returns ``None`` when the query is only whitespace, which the API- rejects with HTTP 400.- """- normalized = query.strip()- if not normalized:- return None- return normalized[:_DEEPSEEK_MAX_QUERY_CHARS]--def _deepseek_is_retryable(status_code: int) -> bool:"""Transient statuses: 408, 429 and 5xx. Every other 4xx needs a new request."""return status_code in {408, 429} or status_code >= 500@@ -493,9 +482,6 @@ class WebSearchTool(Tool):return "keenable"if provider == "anysearch":return "anysearch"- if provider == "deepseek":- api_key = self.config.api_key or os.environ.get("DEEPSEEK_API_KEY", "")- return "deepseek" if api_key else "duckduckgo"if provider == "serper":api_key = self.config.api_key or os.environ.get("SERPER_API_KEY", "")return "serper" if api_key else "duckduckgo"@@ -947,14 +933,21 @@ class WebSearchTool(Tool):unrelated to DeepSeek models' provider-hosted search: it never injectsa ``web_search`` tool into a chat completion request."""- api_key = self.config.api_key or os.environ.get("DEEPSEEK_API_KEY", "")+ api_key = self.config.api_keyif not api_key:- logger.warning("DEEPSEEK_API_KEY not set, falling back to DuckDuckGo")- return await self._search_duckduckgo(query, n)+ return ToolResult.error(+ "Error: DeepSeek search requires an API key. "+ "Set tools.web.search.apiKey."+ )- normalized_query = _normalize_deepseek_query(query)- if normalized_query is None:+ normalized_query = query.strip()+ if not normalized_query:return ToolResult.error("Error: DeepSeek search requires a non-blank query.")+ if len(normalized_query) > _DEEPSEEK_MAX_QUERY_CHARS:+ return ToolResult.error(+ f"Error: DeepSeek search accepts at most {_DEEPSEEK_MAX_QUERY_CHARS} Unicode characters. "+ "Shorten or split the query while preserving its search operators."+ )payload = {"query": normalized_query,"count": min(max(n, 1), _DEEPSEEK_MAX_RESULTS),@@ -989,7 +982,7 @@ class WebSearchTool(Tool):if r.status_code == 401:return ToolResult.error("Error: DeepSeek search rejected the API key (HTTP 401). "- "Set a valid key in tools.web.search.apiKey or DEEPSEEK_API_KEY."+ "Set a valid key in tools.web.search.apiKey.")if r.status_code == 402:return ToolResult.error(@@ -999,7 +992,7 @@ class WebSearchTool(Tool):if r.status_code == 429:return ToolResult.error("Error: DeepSeek search rate limited after retry. The account "- "limit is 5 QPS; retry later or reduce consecutive web_search calls."+ "limit is 5 QPS; retry later or reduce the frequency of concurrent web_search calls.")if _deepseek_is_retryable(r.status_code):return ToolResult.error(diff --git a/tests/tools/test_web_search_tool.py b/tests/tools/test_web_search_tool.pyindex 1784f1527..3ad6b2758 100644--- a/tests/tools/test_web_search_tool.py+++ b/tests/tools/test_web_search_tool.py@@ -5,7 +5,8 @@ import pytestfrom nanobot.agent.tools.registry import is_tool_error_resultfrom nanobot.agent.tools.web import WebSearchTool-from nanobot.config.schema import WebSearchConfig+from nanobot.config.loader import resolve_config_env_vars+from nanobot.config.schema import Config, WebSearchConfigdef _tool(@@ -52,7 +53,7 @@ def test_brave_with_api_key_remains_concurrency_safe():pytest.param("KEENABLE_API_KEY", False, True, "keenable", id="keenable"),pytest.param("SERPER_API_KEY", True, False, "serper", id="serper-fallback"),pytest.param("ANYSEARCH_API_KEY", False, True, "anysearch", id="anysearch"),- pytest.param("DEEPSEEK_API_KEY", True, False, "deepseek", id="deepseek-fallback"),+ pytest.param("DEEPSEEK_API_KEY", False, True, "deepseek", id="deepseek-missing-key"),],)def test_search_concurrency_without_api_key(@@ -475,7 +476,7 @@ async def test_deepseek_search_empty_results(monkeypatch):@pytest.mark.asyncio-async def test_deepseek_search_uses_env_api_key(monkeypatch):+async def test_deepseek_search_uses_explicit_env_reference(monkeypatch):async def mock_post(self, url, **kw):assert kw["headers"]["Authorization"] == "Bearer env-deepseek-key"return _response(json={@@ -483,33 +484,57 @@ async def test_deepseek_search_uses_env_api_key(monkeypatch):})monkeypatch.setattr(httpx.AsyncClient, "post", mock_post)- monkeypatch.setenv("DEEPSEEK_API_KEY", "env-deepseek-key")- tool = _tool(provider="deepseek", api_key="")+ monkeypatch.setenv("DEEPSEEK_SEARCH_KEY", "env-deepseek-key")+ config = Config()+ config.tools.web.search.provider = "deepseek"+ config.tools.web.search.api_key = "${DEEPSEEK_SEARCH_KEY}"+ tool = WebSearchTool(config=resolve_config_env_vars(config).tools.web.search)result = await tool.execute(query="env")assert "Env" in result@pytest.mark.asyncio-async def test_deepseek_missing_key_falls_back_to_duckduckgo(monkeypatch):- class MockDDGS:- def __init__(self, **kw):- pass[email protected]("environment_key", [None, "ambient-deepseek-key"])+async def test_deepseek_missing_key_returns_error_without_searching(monkeypatch, environment_key):+ async def unexpected_search(*args, **kwargs):+ pytest.fail("Missing DeepSeek credentials must not send the query to another provider")- def text(self, query, max_results=5):- return [{"title": "Fallback", "href": "https://ddg.example", "body": "DuckDuckGo fallback"}]+ monkeypatch.setattr(WebSearchTool, "_search_duckduckgo", unexpected_search)+ monkeypatch.setattr(httpx.AsyncClient, "post", unexpected_search)+ if environment_key is None:+ monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)+ else:+ monkeypatch.setenv("DEEPSEEK_API_KEY", environment_key)- monkeypatch.setattr("ddgs.DDGS", MockDDGS)- monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)+ result = await _tool(provider="deepseek").execute(query="test")- tool = _tool(provider="deepseek", api_key="")- result = await tool.execute(query="test")+ assert is_tool_error_result(result)+ assert "tools.web.search.apiKey" in result- assert "DuckDuckGo fallback" in result+[email protected]("query", [+ "搜" * 129,+ "🙂" * 129,+ "DeepSeek Flash API vision reasoning tool calling context window input output "+ "limits documentation and release notes October 2026 -site:example.com",+])+async def test_deepseek_search_rejects_long_queries_without_network(monkeypatch, query):+ async def unexpected_post(*args, **kwargs):+ pytest.fail("An overlong query must be rejected, not truncated and searched")++ monkeypatch.setattr(httpx.AsyncClient, "post", unexpected_post)+ result = await _tool(provider="deepseek", api_key="deepseek-key").execute(query=query)++ assert is_tool_error_result(result)+ assert "128 Unicode characters" in result+ assert "Shorten" in result@pytest.mark.asyncio-async def test_deepseek_search_truncates_query_to_128_unicode_characters(monkeypatch):[email protected]("query", ["搜" * 128, "🙂" * 128])+async def test_deepseek_search_preserves_queries_at_unicode_limit(monkeypatch, query):captured: dict[str, object] = {}async def mock_post(self, url, **kw):@@ -517,22 +542,9 @@ async def test_deepseek_search_truncates_query_to_128_unicode_characters(monkeypreturn _response(json={"results": []})monkeypatch.setattr(httpx.AsyncClient, "post", mock_post)- tool = _tool(provider="deepseek", api_key="deepseek-key")+ await _tool(provider="deepseek", api_key="deepseek-key").execute(query=f" {query} ")- # CJK characters are 3 UTF-8 bytes each, so byte-based truncation would- # land well below 128 characters (or split a code point).- await tool.execute(query="搜" * 200, count=1)- query_value = captured["query"]- assert isinstance(query_value, str)- assert len(query_value) == 128- assert query_value == "搜" * 128-- # Emoji are astral-plane code points; Python counts each as one character.- await tool.execute(query="🙂" * 150, count=1)- emoji_query = captured["query"]- assert isinstance(emoji_query, str)- assert len(emoji_query) == 128- assert emoji_query == "🙂" * 128+ assert captured["query"] == query@pytest.mark.asynciodiff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.pyindex f9fe5cbb6..b44fd2123 100644--- a/tests/webui/test_settings_api.py+++ b/tests/webui/test_settings_api.py@@ -1439,10 +1439,16 @@ def test_update_web_search_settings_accepts_deepseek_with_api_key(assert option["credential"] == "api_key"[email protected]("environment_key", [None, "ambient-deepseek-key"])def test_update_web_search_settings_requires_deepseek_api_key(tmp_path,monkeypatch: pytest.MonkeyPatch,+ environment_key,) -> None:+ if environment_key is None:+ monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)+ else:+ monkeypatch.setenv("DEEPSEEK_API_KEY", environment_key)config_path = tmp_path / "config.json"config = Config()save_config(config, config_path)@@ -1454,6 +1460,30 @@ def test_update_web_search_settings_requires_deepseek_api_key(assert load_config(config_path).tools.web.search.provider == "duckduckgo"+def test_deepseek_explicit_env_reference_survives_settings_updates(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("DEEPSEEK_SEARCH_KEY", "private-deepseek-environment-key")+ config_path = tmp_path / "config.json"+ config = Config()+ config.tools.web.search.provider = "deepseek"+ config.tools.web.search.api_key = "${DEEPSEEK_SEARCH_KEY}"+ save_config(config, config_path)+ monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)++ for timeout in (30, 45):+ payload = update_web_search_settings({+ "provider": ["deepseek"], "timeout": [str(timeout)],+ })+ saved = load_config(config_path).tools.web.search+ assert saved.provider == "deepseek"+ assert saved.api_key == "${DEEPSEEK_SEARCH_KEY}"+ assert saved.timeout == timeout+ assert payload["web_search"]["api_key_hint"]+ assert "private-deepseek-environment-key" not in str(payload)++def test_settings_payload_includes_effective_transcription_config(tmp_path,monkeypatch: pytest.MonkeyPatch,diff --git a/webui/src/components/settings/capabilities/useCapabilitySettingsActions.ts b/webui/src/components/settings/capabilities/useCapabilitySettingsActions.tsindex 1d214eec5..422cc5e86 100644--- a/webui/src/components/settings/capabilities/useCapabilitySettingsActions.ts+++ b/webui/src/components/settings/capabilities/useCapabilitySettingsActions.ts@@ -3,7 +3,7 @@ import type { TFunction } from "i18next";import {webSearchProviderAcceptsApiKey,- webSearchProviderRequiresApiKey,+ webSearchDraftState,} from "@/components/settings/capabilities/WebSettings";import type { CapabilitySettingsState } from "@/components/settings/capabilities/useCapabilitySettingsState";import type {@@ -151,17 +151,7 @@ export function useCapabilitySettingsActions({if (!provider) return;const apiKey = webSearchForm.apiKey?.trim() ?? "";const baseUrl = webSearchForm.baseUrl?.trim() ?? "";- const hasExistingSecret =- webSearchProviderAcceptsApiKey(provider) &&- webSearchForm.provider === settings.web_search.provider &&- !!settings.web_search.api_key_hint;-- if (webSearchProviderRequiresApiKey(provider) && !apiKey && !hasExistingSecret) {- return;- }- if (provider.credential === "base_url" && !baseUrl) {- return;- }+ if (webSearchDraftState(settings, webSearchForm).missingCredential) return;setError("web");setWebSearchSaving(true);diff --git a/webui/src/tests/settings-capabilities.test.tsx b/webui/src/tests/settings-capabilities.test.tsxindex 9d59c1022..7e545d2b8 100644--- a/webui/src/tests/settings-capabilities.test.tsx+++ b/webui/src/tests/settings-capabilities.test.tsx@@ -374,6 +374,42 @@ describe("Settings capabilities", () => {);});+ it("requires an explicit DeepSeek search key before saving and preserves it on later edits", async () => {+ let payload: SettingsPayload = settingsPayload();+ payload.web_search.providers.push({+ name: "deepseek", label: "DeepSeek", credential: "api_key",+ });+ requestMutationMock.mockImplementation(async (_method, update) => {+ payload = { ...payload, web_search: {+ ...payload.web_search, provider: update.provider, timeout: update.timeout,+ api_key_hint: "sk-d...key",+ } };+ return payload;+ });+ renderSettingsView({ initialSection: "browser", initialSettings: payload });++ fireEvent.keyDown(screen.getByRole("combobox", { name: "DuckDuckGo" }), { key: "ArrowDown" });+ fireEvent.click(await screen.findByRole("option", { name: "DeepSeek" }));+ expect(await screen.findByText("Add the required credential before saving.")).toBeVisible();+ expect(requestMutationMock).not.toHaveBeenCalled();+ fireEvent.change(screen.getByPlaceholderText("Enter API key"), { target: { value: "sk-deepseek-search-key" } });+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(+ "settings.web_search.update",+ { provider: "deepseek", api_key: "sk-deepseek-search-key", max_results: 5, timeout: 30, use_jina_reader: true },+ 20_000,+ ));+ expect(await screen.findByText("sk-d...key")).toBeVisible();++ fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));+ const timeout = screen.getAllByRole("spinbutton").find((input) => (input as HTMLInputElement).value === "30")!;+ fireEvent.change(timeout, { target: { value: "45" } });+ await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(+ "settings.web_search.update",+ { provider: "deepseek", max_results: 5, timeout: 45, use_jina_reader: true },+ 20_000,+ ));+ });+it("uses native host safety copy on the native surface", async () => {const payload = {...settingsPayload(),