Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions astrbot/core/astr_agent_runtime/main_agent/web_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
SerpApiNewsSearchTool,
SerpApiScholarSearchTool,
SerpApiWebSearchTool,
SpecStreamExtractWebPageTool,
SpecStreamWebSearchTool,
TavilyExtractWebPageTool,
TavilyWebSearchTool,
)
Expand All @@ -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",
Expand Down Expand Up @@ -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))
Expand Down
203 changes: 203 additions & 0 deletions astrbot/core/astr_agent_runtime/tools/web_search_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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")
Expand All @@ -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")


Expand Down Expand Up @@ -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)
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
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",
Expand All @@ -2339,6 +2540,8 @@ async def call(self, context, **kwargs) -> ToolExecResult:
"SerpApiNewsSearchTool",
"SerpApiScholarSearchTool",
"SerpApiWebSearchTool",
"SpecStreamExtractWebPageTool",
"SpecStreamWebSearchTool",
"TavilyExtractWebPageTool",
"TavilyWebSearchTool",
"WEB_SEARCH_TOOL_NAMES",
Expand Down
15 changes: 15 additions & 0 deletions astrbot/core/config/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -3759,6 +3760,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"firecrawl",
"exa",
"anysearch",
"specstream",
],
"labels": [
"SerpApi",
Expand All @@ -3770,6 +3772,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"Firecrawl",
"Exa",
"AnySearch",
"SpecStream",
],
"subtitles": [
"Google 网页、新闻、图片、学术和财经搜索",
Expand All @@ -3781,6 +3784,7 @@ def get_local_permission_defaults(system: str | None = None) -> dict:
"",
"",
"",
"SpecStream 实时网页搜索与页面提取",
],
"condition": {
"provider_settings.web_search": True,
Expand Down Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions astrbot/dashboard/services/chat_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions astrbot/dashboard/services/live_chat_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 8 additions & 2 deletions dashboard/src/i18n/locales/en-US/features/config-metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,8 @@
"Brave",
"Firecrawl",
"Exa",
"AnySearch"
"AnySearch",
"SpecStream"
],
"subtitles": [
"Google web, news, image, scholar, and finance search",
Expand All @@ -221,7 +222,8 @@
"",
"",
"",
""
"",
"Live web search and page extraction"
]
},
"websearch_tavily_key": {
Expand Down Expand Up @@ -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)"
}
}
},
Expand Down
Loading