Compare commits

...

5 commits

Author SHA1 Message Date
Bao1573
9f0176641a
Merge cef2540dc4 into cda17f4d6a 2026-11-19 09:57:42 +08:00
wengzh
cda17f4d6a
Merge pull request #3548 from zhenglieAllen/zhenglieAllen/fix/check-model-key-none
Some checks failed
Tests / Java (manager-api) (push) Failing after 16s
Tests / Vue (manager-web) (push) Successful in 2m46s
Tests / Python (xiaozhi-server) (push) Successful in 3m24s
fix(util): check_model_key 遇到空 api_key 不再抛 TypeError
2026-11-19 09:52:20 +08:00
wengzh
61a8c04477
feat(web_search): 新增 SpecStream 搜索源 (#3560)
Some checks failed
Tests / Python (xiaozhi-server) (push) Successful in 10m44s
Tests / Java (manager-api) (push) Failing after 30s
Tests / Vue (manager-web) (push) Successful in 11m40s
* feat(web_search): 新增SpecStream搜索源

* docs(web_search): SpecStream API Key申请链接指向注册页

* docs: 更新SpecStream搜索的免费额度信息

---------

Co-authored-by: Tarek Etman <tarek@specstream.ai>
2026-11-16 14:53:37 +08:00
Allen
579538478b fix(util): check_model_key 遇到空 api_key 不再抛 TypeError
现象:provider 构造期报
    TypeError: argument of type 'NoneType' is not iterable
而且栈顶落在 core/utils/util.py 的 check_model_key,看不出是哪个模块的
key 没配。智控台下发的配置里未必带 api_key 字段(本地 LLM 场景也常把
它留空),HA 插件配置没填 api_key 时同样中招:hass_state 和
hass_play_music 都调 initialize_hass_handler,整个插件初始化被打断。

原因:check_model_key 直接写 ``"你" in modelKey``,modelKey 为 None 时
这行就炸了;modelKey 为空串时则静默返回 None,等于没检查。

改法:先把 None / 空串当成「未设置」处理,返回提示文案而不是抛异常。
    if not modelKey:
        return f"配置错误: {modelType} 的 API key 未设置"
出厂占位符的分支保持原样,提示文案里仍带当前值,方便用户对照改。

测试:
- 新增 tests/core/utils/test_check_model_key.py:缺 key / 占位符 / 真 key
  三种情况的契约
- tests/plugins_func/test_hass_init.py 补一条端到端:插件配置里没有
  api_key 时 initialize_hass_handler 不再崩
- 全量 pytest tests/ -q 无新增失败

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-11-07 22:33:44 +08:00
Bao
cef2540dc4 feat(config): 单模块部署也能按设备配置:data/devices.yaml
连接拿到 device-id 后读 data/devices.yaml(device_overrides_file),把该设备的 prompt / llm / tts(有 S2S 模块时还有 brain)合并进这条连接的配置。每次连接重读、改表重连即生效;文件不存在、格式错、未登记、停用、名字不存在都只记日志不改配置。新增 core/utils/device_overrides.py、docs/device-overrides.md、测试;connection.py 加一行调用。
2026-10-31 22:20:13 +08:00
13 changed files with 509 additions and 8 deletions

43
docs/device-overrides.md Normal file
View file

@ -0,0 +1,43 @@
# 按设备覆盖配置(单模块部署)
## 概述
智控台(manager-api)能给每台设备配不同的模型和提示词;只跑 xiaozhi-server 一个模块时,配置是全局的,所有设备一样。
`data/devices.yaml` 补上这一块:连接初始化时按 `device-id` 读这台设备的覆盖项,合并进这条连接的配置。
## 工作原理
`core/utils/device_overrides.py` 在 `ConnectionHandler._initialize_components` 最开头被调用(每条连接的 config 都是深拷贝,互不影响)。
每次连接都重读文件(几 KB),改完表让设备重连即生效,不用重启服务器。文件不存在、格式错、设备没登记、`enabled: false`、
名字在对应配置块里不存在,都只记日志、不改配置、不抛异常。
## 配置
`data/.config.yaml`:
```yaml
device_overrides_file: data/devices.yaml # 默认值,可不写
```
`data/devices.yaml`(schema v1):
```yaml
version: 1
devices:
"aa:bb:cc:dd:ee:ff": # device-id(设备 MAC,小写;大小写不敏感)
name: 书房
enabled: true
brain: cascade # cascade = 原版 VAD→ASR→LLM→TTS;填 S2S 配置块里的名字 = 这台设备用语音进语音出模型
prompt: 你是书房的语音助手。 # 非空则替换全局 prompt
llm: null # 非空且在 LLM 配置块里存在 → 这台设备用它
tts: null # 同上
```
同一份文件也可以给前置的准入网关当白名单(`client_id` 字段给网关用,服务器不读)。
## 测试
```bash
cd main/xiaozhi-server
pytest tests/core/utils/test_device_overrides.py -q
```

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搜索:注册赠送10美元,每条结果带来源链接和摘要,有发布日期时一并返回;每1000次搜索5美元(每次最多10条结果)。
## API Key申请指南
@ -40,6 +41,13 @@
- 复制生成的API Key,这是配置所需的关键信息
- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview)
### 方式五:使用SpecStream搜索
- 访问 [SpecStream](https://specstream.ai/signup?src=xiaozhi-esp32-server),注册并登录账号
- 在工作区的 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

@ -81,6 +81,10 @@ enable_websocket_ping: false
# > 0: 使用固定延迟(毫秒)发送,例如: 60
tts_audio_send_delay: 0
# 按设备覆盖配置(单模块部署没有智控台时的差异化配置):按 device-id 从这个文件读该设备的大脑 / 提示词 / LLM / TTS,
# 每次连接都重读,改完表设备重连即生效;文件不存在就全部用全局配置。格式见 docs/device-overrides.md
device_overrides_file: data/devices.yaml
exit_commands:
- "退出"
- "关闭"
@ -172,19 +176,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/signup?src=xiaozhi-esp32-server
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

@ -22,6 +22,7 @@ from core.utils.util import (
)
from typing import Dict, Any
from collections import deque
from core.utils.device_overrides import apply_device_overrides
from core.utils.modules_initialize import (
initialize_modules,
initialize_tts,
@ -219,6 +220,9 @@ class ConnectionHandler:
)
self.device_id = self.headers.get("device-id", None)
# 按设备覆盖(data/devices.yaml):选大脑 / 提示词 / LLM / TTS,见 docs/device-overrides.md。
# 放在拿到 device-id 的第一时间,后面的消息处理(唤醒词、组件初始化)都能看到覆盖后的配置
apply_device_overrides(self)
# 认证通过,继续处理
self.websocket = ws

View file

@ -0,0 +1,106 @@
"""按设备覆盖配置:单模块部署(没有智控台)时的"差异化配置"。
智控台(manager-api)能给每台设备配不同的模型和提示词;只跑 xiaozhi-server 一个模块时配置是全局的。这个模块补上这一块:
连接初始化时按请求头里的 device-id 读本地 YAML,把这台设备的覆盖项合并进这条连接的 config(connection.py 每条连接都是
深拷贝,互不影响)。每次连接都重读文件(几 KB),改完表让设备重连即生效,不用重启。
文件路径:config["device_overrides_file"],默认 data/devices.yaml;文件不存在 = 不覆盖。schema v1:
```yaml
version: 1
devices:
"aa:bb:cc:dd:ee:ff": # device-id(设备 MAC,小写)
name: 书房
enabled: true # false 时这里不处理(准入由 server.auth 或前置网关负责)
brain: cascade # cascade = 原版 VAD→ASR→LLM→TTS;填 S2S 配置块里的名字(OpenAIRealtime)或它的 type(openai_realtime)= 用该语音模型
prompt: null # 非空则替换 config["prompt"]
llm: null # 非空且在 LLM 配置块里存在 → selected_module.LLM
tts: null # 同上,TTS
```
任何错误都只记日志、不抛出:配置文件坏了不能让设备连不上。
"""
from __future__ import annotations
import os
import yaml
TAG = __name__
DEFAULT_FILE = "data/devices.yaml"
def load_device_overrides(path: str, device_id: str | None) -> dict | None:
"""返回这台设备的覆盖项字典;文件不存在、格式错、没登记、被停用都返回 None。"""
if not device_id or not path or not os.path.exists(path):
return None
try:
with open(path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
except (OSError, yaml.YAMLError):
return None
devices = data.get("devices") if isinstance(data, dict) else None
if not isinstance(devices, dict):
return None
for key, info in devices.items():
if str(key).lower() == str(device_id).lower():
if not isinstance(info, dict) or info.get("enabled", True) is False:
return None
return info
return None
def _resolve_s2s_name(s2s_block: dict, brain: str) -> str | None:
"""brain 既可以写 S2S 配置块里的名字(OpenAIRealtime),也可以写它的 type(openai_realtime)。"""
if brain in s2s_block:
return brain
for name, cfg in s2s_block.items():
if isinstance(cfg, dict) and str(cfg.get("type", name)) == brain:
return name
return None
def apply_device_overrides(conn) -> dict:
"""把这台设备的覆盖项合并进 conn.config;返回实际应用了哪些(给日志 / 测试用)。"""
applied: dict = {}
try:
config = conn.config
path = config.get("device_overrides_file", DEFAULT_FILE)
info = load_device_overrides(path, getattr(conn, "device_id", None))
if not info:
return applied
selected = config.setdefault("selected_module", {})
brain = info.get("brain")
if brain is not None:
brain = str(brain).strip()
if brain in ("", "cascade"):
selected["S2S"] = ""
applied["S2S"] = ""
else:
name = _resolve_s2s_name(config.get("S2S") or {}, brain)
if name:
selected["S2S"] = name
applied["S2S"] = name
else:
conn.logger.bind(tag=TAG).warning(f"设备覆盖的 brain={brain} 既不是 S2S 配置块的名字也不是其中某项的 type,忽略")
prompt = info.get("prompt")
if isinstance(prompt, str) and prompt.strip():
config["prompt"] = prompt
applied["prompt"] = True
for key, section in (("llm", "LLM"), ("tts", "TTS")):
name = info.get(key)
if isinstance(name, str) and name.strip():
if name in (config.get(section) or {}):
selected[section] = name
applied[section] = name
else:
conn.logger.bind(tag=TAG).warning(f"设备覆盖的 {key}={name} 不在 {section} 配置块里,忽略")
if applied:
conn.logger.bind(tag=TAG).info(f"已应用设备覆盖: {applied}")
except Exception as e: # noqa: BLE001
conn.logger.bind(tag=TAG).warning(f"应用设备覆盖失败,按全局配置继续: {type(e).__name__}: {e}")
return applied

View file

@ -179,6 +179,14 @@ def remove_punctuation_and_length(text):
def check_model_key(modelType, modelKey):
"""检查 API key 是不是还停留在出厂占位符上。
modelKey 允许是 None / 空串:智控台下发的配置里未必带 api_key 字段
(本地 LLM 场景也常把它留空),而 ``"你" in None`` 会直接抛
TypeError,把「配置没填」这种业务错误变成了 provider 构造期的崩溃。
"""
if not modelKey:
return f"配置错误: {modelType} 的 API key 未设置"
if "你" in modelKey:
return f"配置错误: {modelType} 的 API key 未设置,当前值为: {modelKey}"
return None

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,38 @@
"""check_model_key 的行为约束。
背景:智控台下发的配置里未必带 api_key 字段,本地 LLM 场景也常把它留空。
原来的实现直接写 ``"你" in modelKey``,modelKey 为 None 时抛
``TypeError: argument of type 'NoneType' is not iterable``,
把「配置没填」这种业务错误变成了 provider 构造期的崩溃 ——
调用方想看到的那句「API key 未设置」根本来不及打印。
"""
import pytest
from core.utils.util import check_model_key
@pytest.mark.parametrize("model_key", [None, ""])
def test_missing_key_reports_error_instead_of_crashing(model_key):
"""key 没配(None / 空串)时返回提示文案,不能抛 TypeError。"""
msg = check_model_key("LLM", model_key)
assert msg is not None, "缺少 api_key 时应当返回提示文案"
assert "API key 未设置" in msg
def test_placeholder_key_reports_error_with_current_value():
"""出厂占位符仍按原样提示,并带上当前值,方便用户对照改。"""
msg = check_model_key("LLM", "你的api_key")
assert msg is not None
assert "API key 未设置" in msg
assert "你的api_key" in msg
def test_real_key_passes():
"""真 key 不该被拦。"""
assert check_model_key("LLM", "sk-abcdef123456") is None
def test_model_type_is_mentioned_in_the_message():
"""提示文案里要带上是哪个模块出的问题。"""
msg = check_model_key("VLLM", None)
assert "VLLM" in msg

View file

@ -0,0 +1,74 @@
"""按设备覆盖(data/devices.yaml):选大脑、提示词、LLM / TTS;没登记 / 停用 / 文件坏 / 名字不存在都不改配置、不抛异常。"""
from __future__ import annotations
import copy
from config.logger import setup_logging
from core.utils.device_overrides import apply_device_overrides, load_device_overrides
LOGGER = setup_logging()
REG = """
version: 1
devices:
"AA:BB:CC:DD:EE:01": {name: s3, client_id: "x", brain: OpenAIRealtime, prompt: "你是书房助手"}
"aa:bb:cc:dd:ee:02": {name: p, brain: cascade, llm: OtherLLM, tts: NoSuchTTS}
"aa:bb:cc:dd:ee:03": {name: paused, enabled: false, brain: OpenAIRealtime}
"aa:bb:cc:dd:ee:04": {name: bad-brain, brain: Nope}
"aa:bb:cc:dd:ee:05": {name: by-type, brain: openai_realtime}
"""
class Conn:
def __init__(self, device_id, path):
self.device_id = device_id
self.logger = LOGGER
self.config = {
"device_overrides_file": path,
"prompt": "全局提示词",
"selected_module": {"LLM": "MainLLM", "TTS": "EdgeTTS", "S2S": ""},
"S2S": {"OpenAIRealtime": {"type": "openai_realtime"}},
"LLM": {"MainLLM": {}, "OtherLLM": {}},
"TTS": {"EdgeTTS": {}},
}
def test_brain_prompt_and_case_insensitive_mac(tmp_path):
p = tmp_path / "devices.yaml"
p.write_text(REG, encoding="utf-8")
c = Conn("aa:bb:cc:dd:ee:01", str(p))
assert apply_device_overrides(c) == {"S2S": "OpenAIRealtime", "prompt": True}
assert c.config["selected_module"]["S2S"] == "OpenAIRealtime" and c.config["prompt"] == "你是书房助手"
def test_brain_accepts_provider_type_name(tmp_path):
p = tmp_path / "devices.yaml"
p.write_text(REG, encoding="utf-8")
c = Conn("aa:bb:cc:dd:ee:05", str(p))
assert apply_device_overrides(c) == {"S2S": "OpenAIRealtime"} # 写 type 也能解析到配置块的名字
def test_cascade_and_llm_override_with_unknown_tts_ignored(tmp_path):
p = tmp_path / "devices.yaml"
p.write_text(REG, encoding="utf-8")
c = Conn("aa:bb:cc:dd:ee:02", str(p))
c.config["selected_module"]["S2S"] = "OpenAIRealtime" # 全局选了 S2S,这台设备要级联
assert apply_device_overrides(c) == {"S2S": "", "LLM": "OtherLLM"}
assert c.config["selected_module"] == {"LLM": "OtherLLM", "TTS": "EdgeTTS", "S2S": ""}
assert c.config["prompt"] == "全局提示词"
def test_no_change_cases(tmp_path):
p = tmp_path / "devices.yaml"
p.write_text(REG, encoding="utf-8")
for dev in ("aa:bb:cc:dd:ee:03", "aa:bb:cc:dd:ee:04", "ff:ff:ff:ff:ff:ff", None):
c = Conn(dev, str(p))
before = copy.deepcopy(c.config)
assert apply_device_overrides(c) == {}
assert c.config == before
c = Conn("aa:bb:cc:dd:ee:01", str(tmp_path / "missing.yaml"))
assert apply_device_overrides(c) == {}
p.write_text("{broken", encoding="utf-8")
assert load_device_overrides(str(p), "aa:bb:cc:dd:ee:01") is None
p.write_text("devices: [1, 2]\n", encoding="utf-8")
assert load_device_overrides(str(p), "aa:bb:cc:dd:ee:01") is None

View file

@ -6,7 +6,7 @@ can only concatenate str (not "list") to str,设备清单进不了提示词,
import pytest
import plugins_func.functions.hass_state # noqa: F401 注册 hass_state 模块,填充 module_func_map
from plugins_func.functions.hass_init import append_devices_to_prompt
from plugins_func.functions.hass_init import append_devices_to_prompt, initialize_hass_handler
HEADER = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
BASE_PROMPT = "你是小智。"
@ -82,3 +82,20 @@ def test_without_hass_functions_prompt_unchanged():
append_devices_to_prompt(conn)
assert conn.prompt == BASE_PROMPT
assert conn.dialogue.system_messages == []
def test_initialize_hass_handler_without_api_key_does_not_crash():
"""插件配置里没有 api_key 时,初始化不能以 TypeError 崩掉。
check_model_key 以前直接写 ``"你" in modelKey``,modelKey 为 None 时
抛 TypeError,HA 插件初始化(hass_state / hass_play_music 都调它)
会被整个打断。
"""
conn = FakeConn(_plugin())
conn.config["plugins"]["home_assistant"].pop("api_key")
conn.load_function_plugin = True
ha_config = initialize_hass_handler(conn)
assert ha_config["base_url"] == "http://homeassistant.local:8123"
assert ha_config["api_key"] is None

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}