This commit is contained in:
Yusuf Gürdoğan 2026-11-19 13:49:55 +08:00 committed by GitHub
commit 2cc83759e5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 227 additions and 7 deletions

View file

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

View file

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

View file

@ -788,3 +788,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611101200.sql
- changeSet:
id: 202611161200
author: yusufgurdogan
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202611161200.sql

View file

@ -176,20 +176,21 @@ plugins:
# ragflow知识库id
dataset_ids: ["123456789"]
# 联网搜索插件配置
# 支持秘塔(metaso)、Tavily、Serply、Outcrawl和SpecStream五个搜索源
# 支持秘塔(metaso)、Tavily、Serply、Outcrawl、SpecStream和Sofya六个搜索源
# 秘塔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/signup?src=xiaozhi-esp32-server
# Sofya API Key申请:https://sofya.co/dashboard
web_search:
# 搜索源:metaso / tavily / serply / outcrawl / specstream
# 搜索源:metaso / tavily / serply / outcrawl / specstream / sofya
provider: "metaso"
# 工具描述,用于告知LLM何时调用此工具,可根据需要自定义
description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。"
# 返回结果数量(默认5)
max_results: 5
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key / SpecStream API Key
# 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key / SpecStream API Key / Sofya API Key(sofya_live_前缀)
api_key: "mk-xxx"
# 声纹识别配置
voiceprint:

View file

@ -249,6 +249,59 @@ async def _search_specstream(api_key: str, query: str, max_results: int) -> str:
return "\n".join(lines)
async def _search_sofya(api_key: str, query: str, max_results: int) -> str:
"""调用Sofya搜索API"""
url = "https://sofya.co/v1/search"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"User-Agent": "xiaozhi-esp32-server",
}
# snippets只返回摘要、不抓取网页正文,响应最快;单次最多返回20条
payload = {
"query": query,
"max_results": max(1, min(max_results, 20)),
"search_depth": "snippets",
}
logger.bind(tag=TAG).debug(f"Sofya搜索请求 | URL: {url} | payload: {payload}")
async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client:
response = await client.post(url, json=payload, headers=headers)
data = response.json()
logger.bind(tag=TAG).debug(f"Sofya搜索响应 | status: {response.status_code}")
if response.status_code != 200:
# 错误信封为 {"error": "...", "detail": "..."},失败的请求不扣费
code = data.get("error", "") if isinstance(data, dict) else ""
detail = data.get("detail", "") if isinstance(data, dict) else ""
logger.bind(tag=TAG).error(
f"Sofya搜索失败 | status: {response.status_code} | code: {code} | detail: {detail}"
)
if response.status_code == 401:
return "联网搜索请求失败,请检查API Key是否正确。"
if response.status_code == 402:
# insufficient_credits(余额不足)或 key_cap_reached(该Key达到用量上限)
return "联网搜索额度已用完,请检查Sofya账户余额。"
# 其余状态(429限流、503、504等)多为暂时性故障,统一引导重试
return "联网搜索请求失败,请稍后重试。"
results = data.get("results", [])
if not results:
return "未找到相关搜索结果。"
lines = ["【联网搜索结果】"]
for i, item in enumerate(results[:max_results], 1):
title = item.get("title") or "无标题"
snippet = item.get("description") or item.get("content") or ""
date = item.get("published_date") 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}")
@ -279,6 +332,8 @@ async def web_search(conn: "ConnectionHandler", query: str = None):
result_text = await _search_outcrawl(api_key, query, max_results)
elif provider == "specstream":
result_text = await _search_specstream(api_key, query, max_results)
elif provider == "sofya":
result_text = await _search_sofya(api_key, query, max_results)
else:
return ActionResponse(
Action.REQLLM,

View file

@ -0,0 +1,141 @@
"""Tests for the Sofya 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 post(self, url, json=None, headers=None):
FakeAsyncClient.requests.append({"url": url, "json": json, "headers": headers})
return FakeAsyncClient.response
@pytest.fixture
def fake_http(monkeypatch):
"""Replace httpx.AsyncClient with the recording fake."""
FakeAsyncClient.requests = []
FakeAsyncClient.response = FakeResponse(payload={"results": []})
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_sofya_sends_bearer_key_and_snippets_depth(fake_http):
await web_search_module._search_sofya("sofya_live_key", "上海天气", 5)
[request] = fake_http.requests
assert request["url"] == "https://sofya.co/v1/search"
assert request["json"] == {"query": "上海天气", "max_results": 5, "search_depth": "snippets"}
assert request["headers"]["Authorization"] == "Bearer sofya_live_key"
assert request["headers"]["User-Agent"] == "xiaozhi-esp32-server"
@pytest.mark.parametrize(("max_results", "sent"), [(0, 1), (50, 20)])
async def test_sofya_clamps_max_results(fake_http, max_results, sent):
await web_search_module._search_sofya("sofya_live_key", "q", max_results)
assert fake_http.requests[0]["json"]["max_results"] == sent
async def test_sofya_formats_titles_dates_and_snippets_without_urls(fake_http):
fake_http.response = FakeResponse(
payload={
"query": "q",
"answer": None,
"results": [
{
"url": "https://a.example/1",
"title": "标题一",
"content": "摘要一",
"description": "摘要一",
"fetched": False,
"published_date": "2026-11-10",
},
{"url": "https://a.example/2", "title": "", "content": "", "description": None, "published_date": None},
{"url": "https://a.example/3", "title": "标题三", "content": "摘要三"},
],
"search_depth": "snippets",
"credits_used": 1,
}
)
result = await web_search_module._search_sofya("sofya_live_key", "q", 2)
assert result == "【联网搜索结果】\n1. 标题:标题一\n 日期:2026-11-10\n 摘要:摘要一\n2. 标题:无标题"
assert "https://" not in result
async def test_sofya_falls_back_to_content_when_description_is_missing(fake_http):
fake_http.response = FakeResponse(
payload={"results": [{"url": "https://a.example", "title": "T", "content": "C", "description": None}]}
)
assert await web_search_module._search_sofya("sofya_live_key", "q", 3) == "【联网搜索结果】\n1. 标题:T\n 摘要:C"
async def test_sofya_empty_results(fake_http):
fake_http.response = FakeResponse(payload={"results": []})
assert await web_search_module._search_sofya("sofya_live_key", "q", 3) == "未找到相关搜索结果。"
@pytest.mark.parametrize(
("status", "code", "message"),
[
(401, "unauthorized", "联网搜索请求失败,请检查API Key是否正确。"),
(402, "insufficient_credits", "联网搜索额度已用完,请检查Sofya账户余额。"),
(402, "key_cap_reached", "联网搜索额度已用完,请检查Sofya账户余额。"),
(429, "rate_limited", "联网搜索请求失败,请稍后重试。"),
(503, "search_unavailable", "联网搜索请求失败,请稍后重试。"),
],
)
async def test_sofya_error_status(fake_http, status, code, message):
fake_http.response = FakeResponse(status_code=status, payload={"error": code, "detail": "denied"})
assert await web_search_module._search_sofya("sofya_live_key", "q", 3) == message
async def test_web_search_dispatches_to_sofya(fake_http):
fake_http.response = FakeResponse(
payload={"results": [{"url": "https://a.example", "title": "T", "description": "S", "content": "S"}]}
)
conn = FakeConn({"provider": "Sofya", "api_key": "sofya_live_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]["json"] == {"query": "q", "max_results": 3, "search_depth": "snippets"}