feat(web_search): 新增SpecStream搜索源

This commit is contained in:
Tarek Etman 2026-11-10 18:57:21 +00:00
parent 4b1a54a41c
commit 5151cfefb2
6 changed files with 214 additions and 7 deletions

View file

@ -2,15 +2,16 @@
## 功能简介
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持四个搜索源:秘塔(Metaso)、Tavily、Serply和Outcrawl,用户可根据需要选择其中一个。
联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持五个搜索源:秘塔(Metaso)、Tavily、Serply、Outcrawl和SpecStream,用户可根据需要选择其中一个。
## API Key申请指南
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`和`Outcrawl搜索`。
目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`、`Outcrawl搜索`和`SpecStream搜索`。
- Tavily搜索:每个月1000次免费额度。
- 秘塔搜索:拥有较为优质的国内数据源。
- Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。
- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。
- SpecStream搜索:每条结果带来源链接和摘要,有发布日期时一并返回;每1000次搜索5美元(每次最多10条结果)。
## API Key申请指南
@ -40,6 +41,13 @@
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview)
### 方式五:使用SpecStream搜索
- 访问 [SpecStream](https://specstream.ai),注册并登录账号
- 在工作区的 Agents & API 页面创建API Key
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [SpecStream文档](https://specstream.ai/search-api)
## 配置方式
### 方式1. 使用智控台部署(推荐)
@ -48,14 +56,14 @@
- 进入"配置角色"页面,选择要配置的智能体
- 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件
- 勾选"联网搜索"
- 填入搜索源(`metaso`、`tavily`、`serply`或`outcrawl`),并将对应的`API Key`填入配置项
- 填入搜索源(`metaso`、`tavily`、`serply`、`outcrawl`或`specstream`),并将对应的`API Key`填入配置项
- 保存配置,再保存智能体配置
### 方式2. 单模块xiaozhi-server部署
在 `data/.config.yaml` 中配置:
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply` 或 `outcrawl`
- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply`、`outcrawl` 或 `specstream`
- 将申请到的API Key填入 `api_key`
```yaml

View file

@ -0,0 +1,9 @@
-- 联网搜索插件新增SpecStream搜索源
UPDATE `ai_model_provider`
SET `fields` = JSON_SET(
`fields`,
'$[0].label',
'搜索源:metaso / tavily / serply / outcrawl / specstream'
)
WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH';

View file

@ -767,3 +767,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611021200.sql
- changeSet:
id: 202611101200
author: Specstreamai
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611101200.sql

View file

@ -172,19 +172,20 @@ plugins:
# ragflow知识库id
dataset_ids: ["123456789"]
# 联网搜索插件配置
# 支持秘塔(metaso)、Tavily、Serply和Outcrawl四个搜索源
# 支持秘塔(metaso)、Tavily、Serply、Outcrawl和SpecStream五个搜索源
# 秘塔API Key申请:https://metaso.cn/search-api/api-keys
# Tavily API Key申请:https://app.tavily.com/home
# Serply API Key申请:https://serply.io
# Outcrawl API Key申请:https://outcrawl.ai
# SpecStream API Key申请:https://specstream.ai
web_search:
# 搜索源:metaso / tavily / serply / outcrawl
# 搜索源:metaso / tavily / serply / outcrawl / specstream
provider: "metaso"
# 工具描述,用于告知LLM何时调用此工具,可根据需要自定义
description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
# 返回结果数量(默认5)
max_results: 5
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key / SpecStream API Key
api_key: "mk-xxx"
# 声纹识别配置
voiceprint:

View file

@ -197,6 +197,58 @@ async def _search_outcrawl(api_key: str, query: str, max_results: int) -> str:
return "\n".join(lines)
async def _search_specstream(api_key: str, query: str, max_results: int) -> str:
"""调用SpecStream搜索API"""
url = "https://api.specstream.ai/v1/web-search"
headers = {
"Authorization": f"Bearer {api_key}",
"User-Agent": "xiaozhi-esp32-server",
}
# 单次10条以内按基础价计费,所以num按1到10截取
params = {"q": query, "num": max(1, min(max_results, 10))}
logger.bind(tag=TAG).debug(f"SpecStream搜索请求 | URL: {url} | params: {params}")
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
response = await client.get(url, params=params, headers=headers)
data = response.json()
logger.bind(tag=TAG).debug(f"SpecStream搜索响应 | status: {response.status_code}")
if response.status_code != 200:
# 错误信封为 {"error": {"code": "...", "message": "...", "details": {}}}
error = data.get("error", {}) if isinstance(data, dict) else {}
code = error.get("code", "") if isinstance(error, dict) else ""
detail = error.get("message", "") if isinstance(error, dict) else ""
logger.bind(tag=TAG).error(
f"SpecStream搜索失败 | status: {response.status_code} | code: {code} | detail: {detail}"
)
if code in ("missing_api_key", "invalid_token"):
return "联网搜索请求失败,请检查API Key是否正确。"
if code in ("insufficient_balance", "payment_required"):
return "联网搜索额度已用完,请检查SpecStream账户余额。"
# 其余code(rate_limited、capacity、bad_request等)统一引导重试
return "联网搜索请求失败,请稍后重试。"
page = data.get("data") or {}
sources = page.get("sources", [])
if not sources:
return "未找到相关搜索结果。"
lines = ["【联网搜索结果】"]
answer = (page.get("answer") or {}).get("value", "")
if answer:
lines.append(f"总结:{answer}")
for i, item in enumerate(sources[:max_results], 1):
title = item.get("title") or "无标题"
snippet = item.get("snippet", "")
date = item.get("published") or ""
lines.append(f"{i}. 标题:{title}")
if date:
lines.append(f" 日期:{date}")
if snippet:
lines.append(f" 摘要:{snippet}")
return "\n".join(lines)
@register_function("web_search", WEB_SEARCH_FUNCTION_DESC, ToolType.SYSTEM_CTL)
async def web_search(conn: "ConnectionHandler", query: str = None):
logger.bind(tag=TAG).info(f"web_search 被调用 | query={query}")
@ -225,6 +277,8 @@ async def web_search(conn: "ConnectionHandler", query: str = None):
result_text = await _search_serply(api_key, query, max_results)
elif provider == "outcrawl":
result_text = await _search_outcrawl(api_key, query, max_results)
elif provider == "specstream":
result_text = await _search_specstream(api_key, query, max_results)
else:
return ActionResponse(
Action.REQLLM,

View file

@ -0,0 +1,128 @@
"""Tests for the SpecStream source of the web_search plugin.
The HTTP layer is replaced with a fake client and every request is recorded.
Nothing here touches the network.
"""
import httpx
import pytest
from plugins_func.functions import web_search as web_search_module
from plugins_func.register import Action
class FakeResponse:
def __init__(self, status_code=200, payload=None):
self.status_code = status_code
self.payload = payload
def json(self):
return self.payload
class FakeAsyncClient:
"""Stands in for httpx.AsyncClient and records what was requested."""
requests = []
response = None
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc_info):
return False
async def get(self, url, params=None, headers=None):
FakeAsyncClient.requests.append({"url": url, "params": params, "headers": headers})
return FakeAsyncClient.response
@pytest.fixture
def fake_http(monkeypatch):
"""Replace httpx.AsyncClient with the recording fake."""
FakeAsyncClient.requests = []
FakeAsyncClient.response = FakeResponse(payload={"data": {"sources": []}})
monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient)
return FakeAsyncClient
class FakeConn:
def __init__(self, web_search_config):
self.config = {"plugins": {"web_search": web_search_config}}
async def test_specstream_sends_bearer_key_and_num(fake_http):
await web_search_module._search_specstream("ss-key", "上海天气", 5)
[request] = fake_http.requests
assert request["url"] == "https://api.specstream.ai/v1/web-search"
assert request["params"] == {"q": "上海天气", "num": 5}
assert request["headers"]["Authorization"] == "Bearer ss-key"
assert request["headers"]["User-Agent"] == "xiaozhi-esp32-server"
@pytest.mark.parametrize(("max_results", "num"), [(0, 1), (50, 10)])
async def test_specstream_clamps_num(fake_http, max_results, num):
await web_search_module._search_specstream("ss-key", "q", max_results)
assert fake_http.requests[0]["params"]["num"] == num
async def test_specstream_formats_answer_titles_dates_and_snippets_without_urls(fake_http):
fake_http.response = FakeResponse(
payload={
"data": {
"answer": {"value": "多云", "page": "https://a.example/1"},
"sources": [
{"url": "https://a.example/1", "title": "标题一", "snippet": "摘要一", "published": "2026-11-10"},
{"url": "https://a.example/2", "title": "", "snippet": "", "published": None},
{"url": "https://a.example/3", "title": "标题三", "snippet": "摘要三"},
],
"price_usd": 0.005,
}
}
)
result = await web_search_module._search_specstream("ss-key", "q", 2)
assert result == "【联网搜索结果】\n总结:多云\n1. 标题:标题一\n 日期:2026-11-10\n 摘要:摘要一\n2. 标题:无标题"
assert "https://" not in result
async def test_specstream_empty_sources(fake_http):
fake_http.response = FakeResponse(payload={"data": {"answer": None, "sources": []}})
assert await web_search_module._search_specstream("ss-key", "q", 3) == "未找到相关搜索结果。"
@pytest.mark.parametrize(
("status", "code", "message"),
[
(401, "invalid_token", "联网搜索请求失败,请检查API Key是否正确。"),
(401, "missing_api_key", "联网搜索请求失败,请检查API Key是否正确。"),
(402, "insufficient_balance", "联网搜索额度已用完,请检查SpecStream账户余额。"),
(429, "rate_limited", "联网搜索请求失败,请稍后重试。"),
(503, "capacity", "联网搜索请求失败,请稍后重试。"),
],
)
async def test_specstream_error_code(fake_http, status, code, message):
fake_http.response = FakeResponse(
status_code=status, payload={"error": {"code": code, "message": "denied", "details": {}}}
)
assert await web_search_module._search_specstream("ss-key", "q", 3) == message
async def test_web_search_dispatches_to_specstream(fake_http):
fake_http.response = FakeResponse(
payload={"data": {"answer": None, "sources": [{"url": "https://a.example", "title": "T", "snippet": "S"}]}}
)
conn = FakeConn({"provider": "SpecStream", "api_key": "ss-key", "max_results": 3})
response = await web_search_module.web_search(conn, "q")
assert response.action == Action.REQLLM
assert response.result == "【联网搜索结果】\n1. 标题:T\n 摘要:S"
assert fake_http.requests[0]["params"] == {"q": "q", "num": 3}