diff --git a/astrbot/core/astr_agent_runtime/main_agent/web_search.py b/astrbot/core/astr_agent_runtime/main_agent/web_search.py index 5b9f8524fff..6a8bfff7246 100644 --- a/astrbot/core/astr_agent_runtime/main_agent/web_search.py +++ b/astrbot/core/astr_agent_runtime/main_agent/web_search.py @@ -17,6 +17,8 @@ SerpApiNewsSearchTool, SerpApiScholarSearchTool, SerpApiWebSearchTool, + SpecStreamExtractWebPageTool, + SpecStreamWebSearchTool, TavilyExtractWebPageTool, TavilyWebSearchTool, ) @@ -33,6 +35,7 @@ "web_search_exa", "web_search_anysearch", "web_search_deepseek", + "web_search_specstream", "web_search_serpapi", "news_search_serpapi", "image_search_serpapi", @@ -96,6 +99,11 @@ def apply_web_search( elif provider == "deepseek": req.func_tool.add_tool(tool_mgr.get_builtin_tool(DeepSeekWebSearchTool)) req.func_tool.add_tool(tool_mgr.get_builtin_tool(DeepSeekFetchWebPageTool)) + elif provider == "specstream": + req.func_tool.add_tool(tool_mgr.get_builtin_tool(SpecStreamWebSearchTool)) + req.func_tool.add_tool( + tool_mgr.get_builtin_tool(SpecStreamExtractWebPageTool) + ) elif provider == "serpapi": req.func_tool.add_tool(tool_mgr.get_builtin_tool(SerpApiWebSearchTool)) req.func_tool.add_tool(tool_mgr.get_builtin_tool(SerpApiNewsSearchTool)) diff --git a/astrbot/core/astr_agent_runtime/tools/web_search_tools.py b/astrbot/core/astr_agent_runtime/tools/web_search_tools.py index d625515067a..354648e89e7 100644 --- a/astrbot/core/astr_agent_runtime/tools/web_search_tools.py +++ b/astrbot/core/astr_agent_runtime/tools/web_search_tools.py @@ -32,6 +32,8 @@ "scholar_search_serpapi", "web_search_deepseek", "deepseek_fetch_web_page", + "web_search_specstream", + "specstream_extract_web_page", ] _TAVILY_WEB_SEARCH_TOOL_CONFIG = { "provider_settings.web_search": True, @@ -65,6 +67,10 @@ "provider_settings.web_search": True, "provider_settings.websearch_provider": "deepseek", } +_SPECSTREAM_WEB_SEARCH_TOOL_CONFIG = { + "provider_settings.web_search": True, + "provider_settings.websearch_provider": "specstream", +} _SERPAPI_WEB_SEARCH_TOOL_CONFIG = { "provider_settings.web_search": True, "provider_settings.websearch_provider": "serpapi", @@ -139,6 +145,8 @@ async def get( _FIRECRAWL_RETRYABLE_HTTP_STATUSES: frozenset[int] = frozenset({401, 402, 403, 429}) _EXA_RETRYABLE_HTTP_STATUSES: frozenset[int] = frozenset({401, 402, 429}) _DEEPSEEK_RETRYABLE_HTTP_STATUSES: frozenset[int] = frozenset({401, 402, 429}) +# 401 - missing or invalid key, 402 - empty balance. +_SPECSTREAM_RETRYABLE_HTTP_STATUSES: frozenset[int] = frozenset({401, 402}) _TAVILY_KEY_ROTATOR = _KeyRotator("websearch_tavily_key", "Tavily") _BOCHA_KEY_ROTATOR = _KeyRotator("websearch_bocha_key", "BoCha") @@ -147,6 +155,7 @@ async def get( _EXA_KEY_ROTATOR = _KeyRotator("websearch_exa_key", "Exa") _ANYSEARCH_KEY_ROTATOR = _KeyRotator("websearch_anysearch_key", "AnySearch") _DEEPSEEK_KEY_ROTATOR = _KeyRotator("websearch_deepseek_key", "DeepSeek") +_SPECSTREAM_KEY_ROTATOR = _KeyRotator("websearch_specstream_key", "SpecStream") _SERPAPI_KEY_ROTATOR = _KeyRotator("websearch_serpapi_key", "SerpApi") @@ -2325,6 +2334,198 @@ async def call(self, context, **kwargs) -> ToolExecResult: return f"URL: {url}\nTitle: {data.get('title', '')}\nContent: {data['content']}" +@builtin_tool(config=_SPECSTREAM_WEB_SEARCH_TOOL_CONFIG) +@pydantic_dataclass +class SpecStreamWebSearchTool(FunctionTool[AstrAgentContext]): + name: str = "web_search_specstream" + description: str = ( + "Search the live web using SpecStream and return sources with snippets. " + "Use specstream_extract_web_page for full page content when needed." + ) + parameters: dict = Field( + default_factory=lambda: { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "description": "Required. The question or search query.", + }, + "count": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 10, + "description": "Optional. Maximum number of results, 1-50. Default is 10.", + }, + }, + "required": ["query"], + } + ) + + async def call(self, context, **kwargs) -> ToolExecResult: + """Search the SpecStream Search API and normalize the sources. + + Args: + context: Current agent execution context. + **kwargs: Search query and optional count. + + Returns: + Search results with citation indices, or an input/configuration error. + + Raises: + RuntimeError: If all keys fail or a non-retryable HTTP error is returned. + """ + _, provider_settings, _ = _get_runtime(context) + keys = provider_settings.get("websearch_specstream_key", []) + if not keys: + return "Error: SpecStream API key is not configured in AstrBot." + + query = kwargs.get("query") + if not isinstance(query, str) or not query.strip(): + return "Error: query must be a non-blank string." + count = kwargs.get("count", 10) + if type(count) is not int or not 1 <= count <= 50: + return "Error: count must be an integer between 1 and 50." + + last_error = None + tried_keys: set[str] = set() + for _ in range(len(set(keys))): + key = await _SPECSTREAM_KEY_ROTATOR.get(provider_settings, tried_keys) + headers = {"Authorization": f"Bearer {key}"} + async with aiohttp.ClientSession(trust_env=True) as session: + async with session.get( + "https://api.specstream.ai/v1/web-search", + params={"q": query}, + headers=headers, + ) as response: + if response.status != 200: + reason = await response.text() + last_error = RuntimeError( + f"SpecStream web search failed: {reason}, status: {response.status}" + ) + if response.status in _SPECSTREAM_RETRYABLE_HTTP_STATUSES: + continue + raise last_error + data = await response.json() + break + else: + if last_error is not None: + raise last_error + raise RuntimeError("SpecStream web search failed with all configured keys.") + + # The API has no result-count parameter, so trim locally. + sources = (data.get("data") or {}).get("sources") or [] + results = [ + SearchResult( + title=item.get("title") or "", + url=item["url"], + snippet=item.get("snippet") or "", + ) + for item in sources + if item.get("url") + ][:count] + if not results: + return "Error: SpecStream web search does not return any results." + return _search_result_payload(results) + + +@builtin_tool(config=_SPECSTREAM_WEB_SEARCH_TOOL_CONFIG) +@pydantic_dataclass +class SpecStreamExtractWebPageTool(FunctionTool[AstrAgentContext]): + name: str = "specstream_extract_web_page" + description: str = ( + "Extract a single web page using SpecStream and return its title and " + "Markdown content. Use this to read a known URL, including a page found " + "through web search." + ) + parameters: dict = Field( + default_factory=lambda: { + "type": "object", + "properties": { + "url": { + "type": "string", + "minLength": 1, + "description": "Required. HTTP or HTTPS URL of the page to extract.", + }, + }, + "required": ["url"], + } + ) + + async def call(self, context, **kwargs) -> ToolExecResult: + """Extract Markdown content from the SpecStream Extract API. + + Args: + context: Current agent execution context. + **kwargs: The HTTP or HTTPS page URL to extract. + + Returns: + The page URL, title and Markdown content, or an input/configuration error. + + Raises: + RuntimeError: If all keys fail or a non-retryable HTTP error is returned. + """ + _, provider_settings, _ = _get_runtime(context) + keys = provider_settings.get("websearch_specstream_key", []) + if not keys: + return "Error: SpecStream API key is not configured in AstrBot." + + url = kwargs.get("url") + try: + parsed = urlsplit(url) if isinstance(url, str) else None + # Port syntax and range are validated only when this property is read. + _ = parsed.port if parsed is not None else None + valid_url = ( + parsed is not None + and parsed.scheme in {"http", "https"} + and bool(parsed.hostname) + and not any(char.isspace() for char in url) + ) + except ValueError: + valid_url = False + if not valid_url: + return "Error: url must be an HTTP or HTTPS URL with a host." + + last_error = None + tried_keys: set[str] = set() + for _ in range(len(set(keys))): + key = await _SPECSTREAM_KEY_ROTATOR.get(provider_settings, tried_keys) + headers = { + "Authorization": f"Bearer {key}", + "Content-Type": "application/json", + } + async with aiohttp.ClientSession(trust_env=True) as session: + async with session.post( + "https://api.specstream.ai/v1/extract", + json={"urls": [url], "format": "markdown"}, + headers=headers, + ) as response: + if response.status != 200: + reason = await response.text() + last_error = RuntimeError( + f"SpecStream extract failed: {reason}, status: {response.status}" + ) + if response.status in _SPECSTREAM_RETRYABLE_HTTP_STATUSES: + continue + raise last_error + data = await response.json() + break + else: + if last_error is not None: + raise last_error + raise RuntimeError("SpecStream extract failed with all configured keys.") + + results = (data.get("data") or {}).get("results") or [] + page = results[0] if results else {} + if page.get("status") != "ok" or not page.get("text"): + return ( + "Error: SpecStream extract does not return any content " + f"(status: {page.get('status', 'unknown')})." + ) + return f"URL: {url}\nTitle: {page.get('title') or ''}\nContent: {page['text']}" + + __all__ = [ "AnySearchWebSearchTool", "BaiduWebSearchTool", @@ -2339,6 +2540,8 @@ async def call(self, context, **kwargs) -> ToolExecResult: "SerpApiNewsSearchTool", "SerpApiScholarSearchTool", "SerpApiWebSearchTool", + "SpecStreamExtractWebPageTool", + "SpecStreamWebSearchTool", "TavilyExtractWebPageTool", "TavilyWebSearchTool", "WEB_SEARCH_TOOL_NAMES", diff --git a/astrbot/core/config/default.py b/astrbot/core/config/default.py index ae5945eddfd..bc0126f0490 100644 --- a/astrbot/core/config/default.py +++ b/astrbot/core/config/default.py @@ -152,6 +152,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict: "websearch_exa_key": [], "websearch_anysearch_key": [], "websearch_deepseek_key": [], + "websearch_specstream_key": [], "websearch_serpapi_key": [], "web_search_link": False, "display_reasoning_text": False, @@ -3759,6 +3760,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict: "firecrawl", "exa", "anysearch", + "specstream", ], "labels": [ "SerpApi", @@ -3770,6 +3772,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict: "Firecrawl", "Exa", "AnySearch", + "SpecStream", ], "subtitles": [ "Google 网页、新闻、图片、学术和财经搜索", @@ -3781,6 +3784,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict: "", "", "", + "SpecStream 实时网页搜索与页面提取", ], "condition": { "provider_settings.web_search": True, @@ -3872,6 +3876,17 @@ def get_local_permission_defaults(system: str | None = None) -> dict: "provider_settings.web_search": True, }, }, + "provider_settings.websearch_specstream_key": { + "description": "SpecStream API Key", + "type": "list", + "items": {"type": "string"}, + "hint": "可添加多个 Key 进行轮询。获取 Key:[https://specstream.ai](https://specstream.ai)", + "secret": True, + "condition": { + "provider_settings.websearch_provider": "specstream", + "provider_settings.web_search": True, + }, + }, "provider_settings.websearch_serpapi_key": { "description": "SerpApi API Key", "type": "list", diff --git a/astrbot/dashboard/services/chat_service.py b/astrbot/dashboard/services/chat_service.py index c9158a5b2f3..d1191e2d35f 100644 --- a/astrbot/dashboard/services/chat_service.py +++ b/astrbot/dashboard/services/chat_service.py @@ -282,6 +282,7 @@ def extract_web_search_refs(accumulated_text: str, accumulated_parts: list) -> d "web_search_bocha", "web_search_brave", "web_search_deepseek", + "web_search_specstream", "web_search_serpapi", "news_search_serpapi", "image_search_serpapi", diff --git a/astrbot/dashboard/services/live_chat_service.py b/astrbot/dashboard/services/live_chat_service.py index 6727cbef8c6..211ae5e76b8 100644 --- a/astrbot/dashboard/services/live_chat_service.py +++ b/astrbot/dashboard/services/live_chat_service.py @@ -288,6 +288,7 @@ def extract_web_search_refs(accumulated_text: str, accumulated_parts: list) -> d "web_search_bocha", "web_search_brave", "web_search_deepseek", + "web_search_specstream", "web_search_serpapi", "news_search_serpapi", "image_search_serpapi", diff --git a/dashboard/src/i18n/locales/en-US/features/config-metadata.json b/dashboard/src/i18n/locales/en-US/features/config-metadata.json index d328c2f20cd..3d7342d20cf 100644 --- a/dashboard/src/i18n/locales/en-US/features/config-metadata.json +++ b/dashboard/src/i18n/locales/en-US/features/config-metadata.json @@ -210,7 +210,8 @@ "Brave", "Firecrawl", "Exa", - "AnySearch" + "AnySearch", + "SpecStream" ], "subtitles": [ "Google web, news, image, scholar, and finance search", @@ -221,7 +222,8 @@ "", "", "", - "" + "", + "Live web search and page extraction" ] }, "websearch_tavily_key": { @@ -262,6 +264,10 @@ "websearch_deepseek_key": { "description": "DeepSeek API Key", "hint": "Enter your DeepSeek API key. Can use the same key as the chat model (must be entered separately). Supports multiple keys for rotation. Get a key: [https://platform.deepseek.com/api_keys](https://platform.deepseek.com/api_keys)" + }, + "websearch_specstream_key": { + "description": "SpecStream API Key", + "hint": "Multiple keys can be added for rotation. Get a key: [https://specstream.ai](https://specstream.ai)" } } }, diff --git a/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json b/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json index e71567b67f4..b95de5fa7ad 100644 --- a/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json +++ b/dashboard/src/i18n/locales/ja-JP/features/config-metadata.json @@ -298,7 +298,8 @@ "Brave", "Firecrawl", "Exa", - "AnySearch" + "AnySearch", + "SpecStream" ], "subtitles": [ "Google のウェブ・ニュース・画像・学術・金融検索", @@ -309,7 +310,8 @@ "", "", "", - "" + "", + "リアルタイムのウェブ検索とページ抽出" ] }, "websearch_tavily_key": { @@ -350,6 +352,10 @@ "websearch_deepseek_key": { "description": "DeepSeek API Key", "hint": "DeepSeek API Key を入力します。チャットモデルと同じ Key も使用可能(個別に入力が必要)。複数 Key のローテーションに対応しています。 Key の取得: [https://platform.deepseek.com/api_keys](https://platform.deepseek.com/api_keys)" + }, + "websearch_specstream_key": { + "description": "SpecStream API Key", + "hint": "複数の Key を追加してローテーションできます。Key の取得: [https://specstream.ai](https://specstream.ai)" } } }, diff --git a/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json b/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json index d13ae4315ae..913a6540d4f 100644 --- a/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json +++ b/dashboard/src/i18n/locales/ru-RU/features/config-metadata.json @@ -298,7 +298,8 @@ "Brave", "Firecrawl", "Exa", - "AnySearch" + "AnySearch", + "SpecStream" ], "subtitles": [ "Веб-поиск, новости, изображения, научные публикации и финансы Google", @@ -309,7 +310,8 @@ "", "", "", - "" + "", + "Веб-поиск в реальном времени и извлечение страниц" ] }, "websearch_tavily_key": { @@ -350,6 +352,10 @@ "websearch_deepseek_key": { "description": "API-ключ DeepSeek", "hint": "Введите API-ключ DeepSeek. Можно использовать тот же ключ, что и для чат-модели (не подставляется автоматически). Поддерживается ротация нескольких ключей. Получить ключ: [https://platform.deepseek.com/api_keys](https://platform.deepseek.com/api_keys)" + }, + "websearch_specstream_key": { + "description": "API-ключ SpecStream", + "hint": "Можно добавить несколько ключей для ротации. Получить ключ: [https://specstream.ai](https://specstream.ai)" } } }, diff --git a/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json b/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json index 2c70baec619..4e9ea32fea8 100644 --- a/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json +++ b/dashboard/src/i18n/locales/zh-CN/features/config-metadata.json @@ -226,7 +226,8 @@ "Brave", "Firecrawl", "Exa", - "AnySearch" + "AnySearch", + "SpecStream" ], "subtitles": [ "Google 网页、新闻、图片、学术和财经搜索", @@ -237,7 +238,8 @@ "", "", "", - "" + "", + "实时网页搜索与页面提取" ] }, "websearch_tavily_key": { @@ -278,6 +280,10 @@ "websearch_deepseek_key": { "description": "DeepSeek API Key", "hint": "填入 DeepSeek API Key。可使用与对话模型相同的 Key(需独立填写)。可添加多个 Key 轮询。 获取 Key: [https://platform.deepseek.com/api_keys](https://platform.deepseek.com/api_keys)" + }, + "websearch_specstream_key": { + "description": "SpecStream API Key", + "hint": "可添加多个 Key 进行轮询。获取 Key: [https://specstream.ai](https://specstream.ai)" } } }, diff --git a/docs/en/dev/astrbot-config.md b/docs/en/dev/astrbot-config.md index 8395eb06ffb..b5f8a09882f 100644 --- a/docs/en/dev/astrbot-config.md +++ b/docs/en/dev/astrbot-config.md @@ -65,6 +65,7 @@ The default AstrBot configuration is as follows: "websearch_bocha_key": [], "websearch_brave_key": [], "websearch_deepseek_key": [], + "websearch_specstream_key": [], "websearch_serpapi_key": [], "web_search_link": False, "display_reasoning_text": False, @@ -294,7 +295,7 @@ Whether to enable AstrBot's built-in web search capability. Default is `false`. #### `provider_settings.websearch_provider` -Web search provider type. Default is `tavily`. Currently supports `serpapi`, `deepseek`, `tavily`, `bocha`, `baidu_ai_search`, `brave`, `firecrawl`, `exa`, and `anysearch`. +Web search provider type. Default is `tavily`. Currently supports `serpapi`, `deepseek`, `tavily`, `bocha`, `baidu_ai_search`, `brave`, `firecrawl`, `exa`, `anysearch`, and `specstream`. - `serpapi`: Uses SerpApi Google Search, Google News, Google Images Light, Google Finance, and Google Scholar. - `deepseek`: Uses the DeepSeek Search API. @@ -305,6 +306,7 @@ Web search provider type. Default is `tavily`. Currently supports `serpapi`, `de - `firecrawl`: Uses the Firecrawl Search API. - `exa`: Uses the Exa Search API. - `anysearch`: Uses the AnySearch API. +- `specstream`: Uses the SpecStream Search and Extract APIs. #### `provider_settings.websearch_tavily_key` @@ -326,6 +328,10 @@ API Key list for the Firecrawl search engine. Required when using `firecrawl` as API Key list for the DeepSeek search engine. Required when using `deepseek` as the web search provider. Can use the same API key as the chat model, but must be configured separately. Multiple keys under the same account share rate limits. +#### `provider_settings.websearch_specstream_key` + +API Key list for SpecStream. Required when using `specstream` as the web search provider. Multiple keys rotate, with failover on missing-key and empty-balance errors (HTTP 401 and 402). + #### `provider_settings.websearch_serpapi_key` API Key list shared by SerpApi Google Search, Google News, Google Images Light, Google Finance, and Google Scholar. Required when using `serpapi` as the web search provider. Obtain a key at [SerpApi](https://serpapi.com/manage-api-key). Multiple keys rotate, with failover on authentication and quota errors. diff --git a/docs/en/use/websearch.md b/docs/en/use/websearch.md index 262f464cd9c..71d5033057a 100644 --- a/docs/en/use/websearch.md +++ b/docs/en/use/websearch.md @@ -27,7 +27,7 @@ These settings belong to the selected profile. Changing `default` does not enabl ## Choose a search provider -AstrBot supports nine providers. Configure one to start; you do not need an account with every service. +AstrBot supports ten providers. Configure one to start; you do not need an account with every service. | Provider | Get a key | Capabilities available in AstrBot | | --- | --- | --- | @@ -39,6 +39,7 @@ AstrBot supports nine providers. Configure one to start; you do not need an acco | Brave | [Brave Search API](https://brave.com/search/api/) | Web search | | Firecrawl | [Firecrawl](https://firecrawl.dev/) | Web search and page content extraction from a URL | | Exa | [Exa dashboard](https://dashboard.exa.ai/) | Keyword or semantic search, page contents, and filters such as domain and date | +| SpecStream | [SpecStream](https://specstream.ai) / [Search API docs](https://specstream.ai/docs/search-api) | Web search with source URLs and page content extraction from a URL. Search is $5 per 1,000 searches; extraction is $0.80 per 1,000 pages | | AnySearch | [AnySearch console](https://anysearch.com/console/api-keys) | General search and specialized retrieval for research, code documentation, finance, legal information, and other domains | AnySearch uses anonymous mode with a daily free quota when its key list is empty. Other providers require their own keys. Check each service's website for current quotas, pricing, regional availability, and authorization requirements. @@ -49,7 +50,7 @@ The detailed SerpApi instructions and examples have moved to [Web Search → Ser ### Searching versus reading a link -Searching a topic returns results from a search service. Summarizing a specific link requires extracting that page's contents. Tavily, Firecrawl, Exa, and DeepSeek currently provide dedicated page extraction tools; choose one of them if reading links is a common task. +Searching a topic returns results from a search service. Summarizing a specific link requires extracting that page's contents. Tavily, Firecrawl, Exa, DeepSeek, and SpecStream currently provide dedicated page extraction tools; choose one of them if reading links is a common task. Extraction cannot read every website. Pages behind a login or paywall, sites with anti-bot restrictions, and some pages rendered through scripts may fail. diff --git a/docs/zh/dev/astrbot-config.md b/docs/zh/dev/astrbot-config.md index 588284193e7..7939e57fdd4 100644 --- a/docs/zh/dev/astrbot-config.md +++ b/docs/zh/dev/astrbot-config.md @@ -65,6 +65,7 @@ AstrBot 默认配置如下: "websearch_bocha_key": [], "websearch_brave_key": [], "websearch_deepseek_key": [], + "websearch_specstream_key": [], "websearch_serpapi_key": [], "web_search_link": False, "display_reasoning_text": False, @@ -294,7 +295,7 @@ ID 白名单。填写后,将只处理所填写的 ID 发来的消息事件。 #### `provider_settings.websearch_provider` -网页搜索提供商类型。默认为 `tavily`。目前支持 `serpapi`、`deepseek`、`tavily`、`bocha`、`baidu_ai_search`、`brave`、`firecrawl`、`exa`、`anysearch`。 +网页搜索提供商类型。默认为 `tavily`。目前支持 `serpapi`、`deepseek`、`tavily`、`bocha`、`baidu_ai_search`、`brave`、`firecrawl`、`exa`、`anysearch`、`specstream`。 - `serpapi`:使用 SerpApi Google Search、Google News、Google Images Light、Google Finance 和 Google Scholar。 - `deepseek`:使用 DeepSeek Search API。 @@ -305,6 +306,7 @@ ID 白名单。填写后,将只处理所填写的 ID 发来的消息事件。 - `firecrawl`:使用 Firecrawl Search API。 - `exa`:使用 Exa Search API。 - `anysearch`:使用 AnySearch API。 +- `specstream`:使用 SpecStream 搜索与网页提取 API。 #### `provider_settings.websearch_tavily_key` @@ -326,6 +328,10 @@ Firecrawl 搜索引擎的 API Key 列表。使用 `firecrawl` 作为网页搜索 DeepSeek 搜索引擎的 API Key 列表。使用 `deepseek` 作为网页搜索提供商时需要填写。可使用与对话模型相同的 API Key,配置相互独立。同账号下的多个 Key 共享 QPS 限制。 +#### `provider_settings.websearch_specstream_key` + +SpecStream 的 API Key 列表。使用 `specstream` 作为网页搜索提供商时需要填写。多个 Key 轮询,遇到缺少 Key 或余额为空(HTTP 401 和 402)时自动切换。 + #### `provider_settings.websearch_serpapi_key` SerpApi Google Search、Google News、Google Images Light、Google Finance 和 Google Scholar 共用的 API Key 列表。使用 `serpapi` 作为网页搜索提供商时需要填写。前往 [SerpApi](https://serpapi.com/manage-api-key) 获取 Key。多个 Key 轮询使用,鉴权或额度错误时会尝试下一个 Key。 diff --git a/docs/zh/use/websearch.md b/docs/zh/use/websearch.md index 4489df8ce29..2f6e5e33a73 100644 --- a/docs/zh/use/websearch.md +++ b/docs/zh/use/websearch.md @@ -27,7 +27,7 @@ ## 选择搜索提供商 -当前支持以下九种接入方式。先选一个完成配置即可,无需同时申请所有服务。 +当前支持以下十种接入方式。先选一个完成配置即可,无需同时申请所有服务。 | 提供商 | Key 申请入口 | AstrBot 提供的能力 | | --- | --- | --- | @@ -39,6 +39,7 @@ | Brave | [Brave Search API](https://brave.com/search/api/) | 网页搜索 | | Firecrawl | [Firecrawl](https://firecrawl.dev/) | 网页搜索、按 URL 提取网页正文 | | Exa | [Exa 控制台](https://dashboard.exa.ai/) | 关键词或语义搜索、按 URL 获取正文,支持域名、日期等筛选 | +| SpecStream | [SpecStream](https://specstream.ai) / [搜索 API 文档](https://specstream.ai/docs/search-api) | 网页搜索(附来源 URL)、按 URL 提取网页正文。搜索每 1,000 次 5 美元,网页提取每 1,000 页 0.80 美元 | | AnySearch | [AnySearch 控制台](https://anysearch.com/console/api-keys) | 通用搜索,以及学术、代码文档、金融、法律等垂直领域检索 | AnySearch 的 Key 留空时会使用匿名模式,服务提供每日免费额度。其他提供商需要填写相应的 Key。服务的额度、收费、可用地区和授权方式以各自官网为准。 @@ -49,7 +50,7 @@ SerpApi 的详细说明与专属示例已移至 [网页搜索 → SerpApi](./web ### 搜索与读取链接的区别 -“搜索某个话题”会从搜索服务获取结果;“总结这个链接”需要提取指定网页的正文。当前 Tavily、Firecrawl、Exa 和 DeepSeek 都提供独立的网页正文提取工具。若经常需要阅读具体链接,优先选择其中一种。 +“搜索某个话题”会从搜索服务获取结果;“总结这个链接”需要提取指定网页的正文。当前 Tavily、Firecrawl、Exa、DeepSeek 和 SpecStream 都提供独立的网页正文提取工具。若经常需要阅读具体链接,优先选择其中一种。 网页提取不保证能读取所有网站。登录后才能访问的页面、反爬限制、付费内容,以及某些依赖脚本加载的页面,都可能导致提取失败。 diff --git a/tests/unit/test_astr_main_agent.py b/tests/unit/test_astr_main_agent.py index 6bd8ca09199..63d1237da97 100644 --- a/tests/unit/test_astr_main_agent.py +++ b/tests/unit/test_astr_main_agent.py @@ -719,6 +719,13 @@ async def test_apply_web_search_tools_uses_builtin_tool_manager( "web_search_deepseek", "deepseek_fetch_web_page", ), + ( + "specstream", + web_search_build.SpecStreamWebSearchTool, + web_search_build.SpecStreamExtractWebPageTool, + "web_search_specstream", + "specstream_extract_web_page", + ), ], ) async def test_apply_web_search_tools_adds_search_and_extract_tools( @@ -767,6 +774,7 @@ async def test_apply_web_search_tools_adds_search_and_extract_tools( [ "web_search_tavily", "web_search_deepseek", + "web_search_specstream", "web_search_serpapi", "news_search_serpapi", "image_search_serpapi", diff --git a/tests/unit/test_func_tool_manager.py b/tests/unit/test_func_tool_manager.py index 7aff4ca9bf0..fd9a9f2efef 100644 --- a/tests/unit/test_func_tool_manager.py +++ b/tests/unit/test_func_tool_manager.py @@ -19,6 +19,8 @@ DeepSeekWebSearchTool, FirecrawlExtractWebPageTool, FirecrawlWebSearchTool, + SpecStreamExtractWebPageTool, + SpecStreamWebSearchTool, ) from astrbot.core.provider import func_tool_manager as ftm from astrbot.core.provider.func_tool_manager import FunctionToolManager @@ -922,6 +924,12 @@ async def fake_get_booter(context, session_id): "web_search_deepseek", "deepseek_fetch_web_page", ), + ( + SpecStreamWebSearchTool, + SpecStreamExtractWebPageTool, + "web_search_specstream", + "specstream_extract_web_page", + ), ], ) def test_search_tools_are_registered_as_builtin_tools( diff --git a/tests/unit/test_web_search_refs.py b/tests/unit/test_web_search_refs.py index 3132f244ff1..21dd2e54e3f 100644 --- a/tests/unit/test_web_search_refs.py +++ b/tests/unit/test_web_search_refs.py @@ -18,6 +18,7 @@ "tool_name", [ "web_search_deepseek", + "web_search_specstream", "web_search_serpapi", "news_search_serpapi", "image_search_serpapi", @@ -61,7 +62,7 @@ def test_search_refs_include_only_cited_sources( ) -@pytest.mark.parametrize("provider", ["deepseek", "serpapi"]) +@pytest.mark.parametrize("provider", ["deepseek", "specstream", "serpapi"]) def test_search_configuration_is_available_in_webui(provider): settings = DEFAULT_CONFIG["provider_settings"] items = CONFIG_METADATA_3["ai_group"]["metadata"]["websearch"]["items"] diff --git a/tests/unit/test_web_search_tools.py b/tests/unit/test_web_search_tools.py index a28bd58b4d9..3085d38d5a7 100644 --- a/tests/unit/test_web_search_tools.py +++ b/tests/unit/test_web_search_tools.py @@ -2044,3 +2044,316 @@ async def test_key_rotator_keeps_request_attempts_independent(): assert await rotator.get(settings) == "first" assert await rotator.get(settings) == "first" assert await rotator.get(settings) == "second" + + +class _SpecStreamSession: + """Fake ClientSession that records get() and post() calls for SpecStream tests.""" + + def __init__(self, responses: list): + self.responses = responses + self.cursor = 0 + self.trust_env = None + self.calls: list[dict] = [] + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc, tb): + return None + + def _next(self, call): + self.calls.append(call) + resp = self.responses[self.cursor] + self.cursor = (self.cursor + 1) % len(self.responses) + return resp + + def get(self, url, params, headers): + return self._next( + {"method": "GET", "url": url, "params": params, "headers": headers} + ) + + def post(self, url, json, headers): + return self._next( + {"method": "POST", "url": url, "json": json, "headers": headers} + ) + + +@pytest.fixture +def specstream_session(monkeypatch): + """Install an isolated mocked HTTP session and key rotator for SpecStream tests.""" + session = _SpecStreamSession([_FakeFirecrawlResponse()]) + + def fake_client_session(*, trust_env): + session.trust_env = trust_env + return session + + monkeypatch.setattr(tools.aiohttp, "ClientSession", fake_client_session) + monkeypatch.setattr( + tools, + "_SPECSTREAM_KEY_ROTATOR", + tools._KeyRotator("websearch_specstream_key", "SpecStream"), + ) + monkeypatch.setitem(tools.sp.temporary_cache, "_ws_favicon", {}) + return session + + +@pytest.mark.asyncio +async def test_specstream_search_request_mapping_and_local_trim(specstream_session): + specstream_session.responses = [ + _FakeFirecrawlResponse( + json_data={ + "data": { + "kind": "answer", + "answer": None, + "rows": [], + "sources": [ + { + "url": "https://example.com/a", + "title": "First", + "site": "example.com", + "snippet": "First snippet", + "published": "2026-10-01", + "cited": True, + }, + {"url": "", "title": "No url", "snippet": "dropped"}, + {"url": "https://example.com/b", "title": None}, + {"url": "https://example.com/c", "title": "Third"}, + ], + } + } + ) + ] + context = _context_with_provider_settings({"websearch_specstream_key": ["key"]}) + + result = await tools.SpecStreamWebSearchTool().call( + context, query="who wrote AstrBot", count=2 + ) + + assert specstream_session.calls == [ + { + "method": "GET", + "url": "https://api.specstream.ai/v1/web-search", + "params": {"q": "who wrote AstrBot"}, + "headers": {"Authorization": "Bearer key"}, + } + ] + assert specstream_session.trust_env is True + results = json.loads(result)["results"] + reference = results[0]["index"].split(".")[0] + assert results == [ + { + "title": "First", + "url": "https://example.com/a", + "snippet": "First snippet", + "index": f"{reference}.1", + }, + { + "title": "", + "url": "https://example.com/b", + "snippet": "", + "index": f"{reference}.2", + }, + ] + + +@pytest.mark.asyncio +async def test_specstream_search_without_sources_reports_no_results( + specstream_session, +): + specstream_session.responses = [ + _FakeFirecrawlResponse(json_data={"data": {"kind": "answer", "sources": []}}) + ] + context = _context_with_provider_settings({"websearch_specstream_key": ["key"]}) + + result = await tools.SpecStreamWebSearchTool().call(context, query="q") + + assert result == "Error: SpecStream web search does not return any results." + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"query": None}, "Error: query must be a non-blank string."), + ({"query": " "}, "Error: query must be a non-blank string."), + ( + {"query": "q", "count": 0}, + "Error: count must be an integer between 1 and 50.", + ), + ( + {"query": "q", "count": 51}, + "Error: count must be an integer between 1 and 50.", + ), + ( + {"query": "q", "count": True}, + "Error: count must be an integer between 1 and 50.", + ), + ], +) +async def test_specstream_search_rejects_invalid_parameters( + specstream_session, kwargs, message +): + context = _context_with_provider_settings({"websearch_specstream_key": ["key"]}) + + result = await tools.SpecStreamWebSearchTool().call(context, **kwargs) + + assert result == message + assert specstream_session.calls == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "tool_class", [tools.SpecStreamWebSearchTool, tools.SpecStreamExtractWebPageTool] +) +async def test_specstream_tools_require_api_key(specstream_session, tool_class): + context = _context_with_provider_settings({}) + + result = await tool_class().call(context, query="q", url="https://example.com") + + assert result == "Error: SpecStream API key is not configured in AstrBot." + assert specstream_session.calls == [] + + +@pytest.mark.asyncio +async def test_specstream_search_rotates_key_on_empty_balance(specstream_session): + specstream_session.responses = [ + _FakeFirecrawlResponse(status=402, text_data="empty balance"), + _FakeFirecrawlResponse( + json_data={"data": {"sources": [{"url": "https://example.com"}]}} + ), + ] + context = _context_with_provider_settings( + {"websearch_specstream_key": ["first-key", "second-key"]} + ) + + result = await tools.SpecStreamWebSearchTool().call(context, query="q") + + assert json.loads(result)["results"][0]["url"] == "https://example.com" + assert [call["headers"]["Authorization"] for call in specstream_session.calls] == [ + "Bearer first-key", + "Bearer second-key", + ] + + +@pytest.mark.asyncio +async def test_specstream_search_raises_on_non_retryable_status(specstream_session): + specstream_session.responses = [ + _FakeFirecrawlResponse(status=503, text_data="unavailable") + ] + context = _context_with_provider_settings( + {"websearch_specstream_key": ["first-key", "second-key"]} + ) + + with pytest.raises(RuntimeError, match="unavailable, status: 503"): + await tools.SpecStreamWebSearchTool().call(context, query="q") + + assert len(specstream_session.calls) == 1 + + +@pytest.mark.asyncio +async def test_specstream_search_raises_when_all_keys_fail(specstream_session): + specstream_session.responses = [_FakeFirecrawlResponse(status=401, text_data="bad")] + context = _context_with_provider_settings( + {"websearch_specstream_key": ["first-key", "second-key"]} + ) + + with pytest.raises(RuntimeError, match="bad, status: 401"): + await tools.SpecStreamWebSearchTool().call(context, query="q") + + assert len(specstream_session.calls) == 2 + + +@pytest.mark.asyncio +async def test_specstream_extract_returns_title_and_markdown(specstream_session): + specstream_session.responses = [ + _FakeFirecrawlResponse( + json_data={ + "data": { + "results": [ + { + "url": "https://example.com/page", + "status": "ok", + "title": "Example", + "text": "# Example\n\nMarkdown body", + } + ] + } + } + ) + ] + context = _context_with_provider_settings({"websearch_specstream_key": ["key"]}) + + result = await tools.SpecStreamExtractWebPageTool().call( + context, url="https://example.com/page" + ) + + assert specstream_session.calls == [ + { + "method": "POST", + "url": "https://api.specstream.ai/v1/extract", + "json": {"urls": ["https://example.com/page"], "format": "markdown"}, + "headers": { + "Authorization": "Bearer key", + "Content-Type": "application/json", + }, + } + ] + assert result == ( + "URL: https://example.com/page\nTitle: Example\nContent: # Example\n\n" + "Markdown body" + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("page_status", ["blocked", "empty"]) +async def test_specstream_extract_reports_page_failure(specstream_session, page_status): + specstream_session.responses = [ + _FakeFirecrawlResponse( + json_data={ + "data": { + "results": [ + { + "url": "https://example.com", + "status": page_status, + "text": "", + } + ] + } + } + ) + ] + context = _context_with_provider_settings({"websearch_specstream_key": ["key"]}) + + result = await tools.SpecStreamExtractWebPageTool().call( + context, url="https://example.com" + ) + + assert result == ( + f"Error: SpecStream extract does not return any content (status: {page_status})." + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "url", + [ + None, + 1, + "", + "ftp://example.com", + "https:///page", + "https://[broken", + "https://example.com:abc/page", + "https://example.com:70000/page", + "https://example.com:-1/page", + "https://example.com/with space", + "https://example.com/\npage", + ], +) +async def test_specstream_extract_rejects_invalid_url(specstream_session, url): + context = _context_with_provider_settings({"websearch_specstream_key": ["key"]}) + + result = await tools.SpecStreamExtractWebPageTool().call(context, url=url) + + assert result == "Error: url must be an HTTP or HTTPS URL with a host." + assert specstream_session.calls == []