From 9b8a9b585d6d8f9c429b9a67c2a07480afdecb1e Mon Sep 17 00:00:00 2001 From: Bao1573 <77220108+PG2047@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:29:34 +0800 Subject: [PATCH 01/16] =?UTF-8?q?fix(tools):=20=E6=9C=8D=E5=8A=A1=E7=AB=AF?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E7=9A=84=E5=90=8C=E6=AD=A5=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E6=94=BE=E7=BA=BF=E7=A8=8B=E6=B1=A0=EF=BC=8C=E4=B8=8D=E9=98=BB?= =?UTF-8?q?=E5=A1=9E=E4=BA=8B=E4=BB=B6=E5=BE=AA=E7=8E=AF=20(#3528)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ServerPluginExecutor.execute 在事件循环上被 await,而 hass_state、天气等插件用 requests 同步阻塞,工具执行期间整个循环停转、正在发的音频节拍也停。同步函数改用 run_in_executor 放到线程池;async def 插件照常 await;传参规则不变。附测试。 --- .../tools/server_plugins/plugin_executor.py | 27 ++++---- .../tests/core/providers/tools/__init__.py | 0 .../tools/test_plugin_executor_offload.py | 62 +++++++++++++++++++ 3 files changed, 77 insertions(+), 12 deletions(-) create mode 100644 main/xiaozhi-server/tests/core/providers/tools/__init__.py create mode 100644 main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index afe89c18d..5917b3380 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -1,6 +1,7 @@ """服务端插件工具执行器""" import asyncio +import functools from typing import Dict, Any, TYPE_CHECKING if TYPE_CHECKING: @@ -30,21 +31,23 @@ class ServerPluginExecutor(ToolExecutor): # 根据工具类型决定如何调用 if hasattr(func_item, "type"): func_type = func_item.type - if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (需要conn参数) - result = func_item.func(conn, **arguments) - elif func_type.code == 2: # WAIT - result = func_item.func(**arguments) - elif func_type.code == 3: # CHANGE_SYS_PROMPT - result = func_item.func(conn, **arguments) - else: - result = func_item.func(**arguments) + if func_type.code in [3, 4, 5]: # CHANGE_SYS_PROMPT, SYSTEM_CTL, IOT_CTL (需要conn参数) + call = functools.partial(func_item.func, conn, **arguments) + else: # WAIT 等不传conn + call = functools.partial(func_item.func, **arguments) else: # 默认不传conn参数 - result = func_item.func(**arguments) + call = functools.partial(func_item.func, **arguments) - # 兼容 async def 工具函数 - if asyncio.iscoroutine(result): - result = await result + if asyncio.iscoroutinefunction(func_item.func): + result = await call() + else: + # 同步插件函数(requests 等阻塞调用)放到线程池:这个方法是在事件循环上被 await 的, + # 直接调用会把整个循环卡住,正在给设备发的音频节拍也会停。 + result = await asyncio.get_running_loop().run_in_executor(None, call) + # 兼容同步函数返回协程的写法 + if asyncio.iscoroutine(result): + result = await result return result diff --git a/main/xiaozhi-server/tests/core/providers/tools/__init__.py b/main/xiaozhi-server/tests/core/providers/tools/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py b/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py new file mode 100644 index 000000000..cf89b3a92 --- /dev/null +++ b/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py @@ -0,0 +1,62 @@ +"""服务端插件执行器:同步插件函数在线程池里跑,不卡事件循环;async 插件照常 await;异常变成 ERROR 响应。""" +from __future__ import annotations + +import asyncio +import time +from types import SimpleNamespace + +from core.providers.tools.server_plugins.plugin_executor import ServerPluginExecutor +from plugins_func.register import Action, ActionResponse, ToolType, all_function_registry + +_real_sleep = asyncio.tasks.sleep # conftest 在 mock 模式把 asyncio.sleep 换成空函数 + + +def _register(name, func, tool_type): + item = SimpleNamespace(name=name, func=func, type=tool_type, description={}) + all_function_registry[name] = item + return item + + +def test_sync_plugin_runs_off_loop_and_async_plugin_is_awaited(monkeypatch): + monkeypatch.setattr(asyncio, "sleep", _real_sleep) + conn = SimpleNamespace(config={}) + + def slow_sync(conn_arg, entity_id): + time.sleep(0.3) # 模拟 requests 调 HA + return ActionResponse(Action.RESPONSE, None, f"{entity_id} 已打开") + + async def fast_async(question): + await asyncio.sleep(0) + return ActionResponse(Action.REQLLM, f"答:{question}", None) + + def boom(conn_arg): + raise RuntimeError("连不上") + + _register("t_slow_sync", slow_sync, ToolType.SYSTEM_CTL) + _register("t_fast_async", fast_async, ToolType.WAIT) + _register("t_boom", boom, ToolType.SYSTEM_CTL) + try: + async def go(): + ex = ServerPluginExecutor(conn) + ticks = [] + + async def ticker(): + while True: + ticks.append(time.monotonic()) + await asyncio.sleep(0.02) + + t = asyncio.create_task(ticker()) + r = await ex.execute(conn, "t_slow_sync", {"entity_id": "light.living"}) + t.cancel() + assert r.action == Action.RESPONSE and r.response == "light.living 已打开" + assert len(ticks) >= 8 # 300 ms 里事件循环一直在转(没被 time.sleep 卡住) + r2 = await ex.execute(conn, "t_fast_async", {"question": "几点"}) + assert r2.action == Action.REQLLM and r2.result == "答:几点" + r3 = await ex.execute(conn, "t_boom", {}) + assert r3.action == Action.ERROR and "连不上" in r3.response + r4 = await ex.execute(conn, "t_missing", {}) + assert r4.action == Action.NOTFOUND + asyncio.run(go()) + finally: + for n in ("t_slow_sync", "t_fast_async", "t_boom"): + all_function_registry.pop(n, None) From f9138e65b7c1d3281d4574dd580b5e30bed14a85 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Tue, 3 Nov 2026 10:43:53 +0800 Subject: [PATCH 02/16] =?UTF-8?q?update:=20=E4=BD=BF=E7=94=A8=E4=B8=93?= =?UTF-8?q?=E7=94=A8=E7=BA=BF=E7=A8=8B=E6=B1=A0=E9=81=BF=E5=85=8D=E9=98=BB?= =?UTF-8?q?=E5=A1=9E=E9=BB=98=E8=AE=A4=E6=B1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tools/server_plugins/plugin_executor.py | 23 ++--- main/xiaozhi-server/core/utils/util.py | 2 +- .../plugins_func/functions/get_weather.py | 3 +- main/xiaozhi-server/plugins_func/register.py | 6 +- .../tools/test_plugin_executor_offload.py | 86 +++++++++++++++++-- 5 files changed, 99 insertions(+), 21 deletions(-) diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py index 5917b3380..1451d849a 100644 --- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py +++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py @@ -2,6 +2,7 @@ import asyncio import functools +from concurrent.futures import ThreadPoolExecutor from typing import Dict, Any, TYPE_CHECKING if TYPE_CHECKING: @@ -9,6 +10,10 @@ if TYPE_CHECKING: from ..base import ToolType, ToolDefinition, ToolExecutor from plugins_func.register import all_function_registry, module_func_map, Action, ActionResponse +# 插件专用线程池:不用 asyncio 默认池(DNS 解析、ASR、initialize_modules 等都在用), +# 避免慢插件打满默认池后拖垮所有协程的 DNS 解析和连接建立。 +_PLUGIN_POOL = ThreadPoolExecutor(max_workers=8, thread_name_prefix="plugin") + class ServerPluginExecutor(ToolExecutor): """服务端插件工具执行器""" @@ -29,22 +34,18 @@ class ServerPluginExecutor(ToolExecutor): try: # 根据工具类型决定如何调用 - if hasattr(func_item, "type"): - func_type = func_item.type - if func_type.code in [3, 4, 5]: # CHANGE_SYS_PROMPT, SYSTEM_CTL, IOT_CTL (需要conn参数) - call = functools.partial(func_item.func, conn, **arguments) - else: # WAIT 等不传conn - call = functools.partial(func_item.func, **arguments) - else: - # 默认不传conn参数 + func_type = getattr(func_item, "type", None) + if func_type is not None and func_type.code in [3, 4, 5]: + # CHANGE_SYS_PROMPT, SYSTEM_CTL, IOT_CTL (需要conn参数) + call = functools.partial(func_item.func, conn, **arguments) + else: # WAIT 等不传conn(含 type 未指定的插件) call = functools.partial(func_item.func, **arguments) if asyncio.iscoroutinefunction(func_item.func): result = await call() else: - # 同步插件函数(requests 等阻塞调用)放到线程池:这个方法是在事件循环上被 await 的, - # 直接调用会把整个循环卡住,正在给设备发的音频节拍也会停。 - result = await asyncio.get_running_loop().run_in_executor(None, call) + # 同步函数在 loop 线程上直接执行会卡住整个事件循环,放专用线程池。 + result = await asyncio.get_running_loop().run_in_executor(_PLUGIN_POOL, call) # 兼容同步函数返回协程的写法 if asyncio.iscoroutine(result): result = await result diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index af113a36f..4db4f3842 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -135,7 +135,7 @@ def get_ip_info(ip_addr, logger): if is_private_ip(ip_addr): ip_addr = "" url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}" - resp = requests.get(url).json() + resp = requests.get(url, timeout=5).json() ip_info = {"city": resp.get("city")} # 存入缓存 diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py index ef3ddedad..6cee939a5 100644 --- a/main/xiaozhi-server/plugins_func/functions/get_weather.py +++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py @@ -268,7 +268,8 @@ async def get_weather(conn: "ConnectionHandler", location: str = None, lang: str location = cached_ip_info.get("city") else: # 缓存未命中,调用API获取 - ip_info = get_ip_info(client_ip, logger) + # get_ip_info 是同步 requests 调用,放线程池,避免卡住主事件循环 + ip_info = await asyncio.to_thread(get_ip_info, client_ip, logger) if ip_info: cache_manager.set(CacheType.IP_INFO, client_ip, ip_info) location = ip_info.get("city") diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py index 8b3194ed2..3c48c2cbf 100644 --- a/main/xiaozhi-server/plugins_func/register.py +++ b/main/xiaozhi-server/plugins_func/register.py @@ -83,7 +83,11 @@ module_func_map = {} def register_function(name, desc, type=None): - """注册函数到函数注册字典的装饰器""" + """注册函数到函数注册字典的装饰器 + + 同步函数在工作线程中执行,函数体内不可调用 asyncio 事件循环 API; + 需要异步(httpx、await)请定义为 async def。 + """ def decorator(func): all_function_registry[name] = FunctionItem(name, desc, func, type) diff --git a/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py b/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py index cf89b3a92..2ae45c389 100644 --- a/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py +++ b/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py @@ -8,8 +8,6 @@ from types import SimpleNamespace from core.providers.tools.server_plugins.plugin_executor import ServerPluginExecutor from plugins_func.register import Action, ActionResponse, ToolType, all_function_registry -_real_sleep = asyncio.tasks.sleep # conftest 在 mock 模式把 asyncio.sleep 换成空函数 - def _register(name, func, tool_type): item = SimpleNamespace(name=name, func=func, type=tool_type, description={}) @@ -17,12 +15,16 @@ def _register(name, func, tool_type): return item -def test_sync_plugin_runs_off_loop_and_async_plugin_is_awaited(monkeypatch): - monkeypatch.setattr(asyncio, "sleep", _real_sleep) +def test_sync_plugin_runs_off_loop_and_async_plugin_is_awaited(): conn = SimpleNamespace(config={}) + async def paced_sleep(delay): + # 不能用 asyncio.sleep 计时:conftest 在 mock 模式会把它换成不让出循环的桩, + # 这里放到线程池里睡,保证 ticker 每拍都真正让出事件循环。 + await asyncio.get_running_loop().run_in_executor(None, time.sleep, delay) + def slow_sync(conn_arg, entity_id): - time.sleep(0.3) # 模拟 requests 调 HA + time.sleep(0.3) # 模拟阻塞 IO return ActionResponse(Action.RESPONSE, None, f"{entity_id} 已打开") async def fast_async(question): @@ -43,13 +45,13 @@ def test_sync_plugin_runs_off_loop_and_async_plugin_is_awaited(monkeypatch): async def ticker(): while True: ticks.append(time.monotonic()) - await asyncio.sleep(0.02) + await paced_sleep(0.02) t = asyncio.create_task(ticker()) r = await ex.execute(conn, "t_slow_sync", {"entity_id": "light.living"}) t.cancel() assert r.action == Action.RESPONSE and r.response == "light.living 已打开" - assert len(ticks) >= 8 # 300 ms 里事件循环一直在转(没被 time.sleep 卡住) + assert len(ticks) >= 5 # 300 ms 里事件循环一直在转(没被 time.sleep 卡住) r2 = await ex.execute(conn, "t_fast_async", {"question": "几点"}) assert r2.action == Action.REQLLM and r2.result == "答:几点" r3 = await ex.execute(conn, "t_boom", {}) @@ -60,3 +62,73 @@ def test_sync_plugin_runs_off_loop_and_async_plugin_is_awaited(monkeypatch): finally: for n in ("t_slow_sync", "t_fast_async", "t_boom"): all_function_registry.pop(n, None) + + +def test_conn_passing_rules_and_compat_branches(): + """code 3/4/5 传 conn;WAIT/type=None 不传;同步函数返回协程会被兜底 await。""" + conn = SimpleNamespace(config={}) + seen = {} + + def prompt_fn(conn_arg): + seen["prompt"] = conn_arg + return ActionResponse(Action.RESPONSE, None, "切角色") + + def wait_fn(): + seen["wait"] = True + return ActionResponse(Action.RESPONSE, None, "等") + + def no_type_fn(): + seen["no_type"] = True + return ActionResponse(Action.RESPONSE, None, "无类型") + + def sync_returns_coro(conn_arg): + seen["coro"] = conn_arg + + async def inner(): + return ActionResponse(Action.RESPONSE, None, "协程兜底") + + return inner() + + _register("t_prompt", prompt_fn, ToolType.CHANGE_SYS_PROMPT) + _register("t_wait", wait_fn, ToolType.WAIT) + _register("t_no_type", no_type_fn, None) + _register("t_sync_coro", sync_returns_coro, ToolType.SYSTEM_CTL) + try: + async def go(): + ex = ServerPluginExecutor(conn) + r1 = await ex.execute(conn, "t_prompt", {}) + assert seen["prompt"] is conn and r1.response == "切角色" + r2 = await ex.execute(conn, "t_wait", {}) + assert "wait" in seen and r2.response == "等" + r3 = await ex.execute(conn, "t_no_type", {}) + assert "no_type" in seen and r3.response == "无类型" + r4 = await ex.execute(conn, "t_sync_coro", {}) + assert seen["coro"] is conn and r4.response == "协程兜底" + asyncio.run(go()) + finally: + for n in ("t_prompt", "t_wait", "t_no_type", "t_sync_coro"): + all_function_registry.pop(n, None) + + +def test_sync_plugin_uses_dedicated_pool(): + """同步插件必须跑在专用池上,不能用 asyncio 默认池(DNS 解析等共用默认池)。""" + import threading + + conn = SimpleNamespace(config={}) + seen = {} + + def sync_fn(): + seen["thread"] = threading.current_thread().name + return ActionResponse(Action.RESPONSE, None, "ok") + + _register("t_pool", sync_fn, ToolType.WAIT) + try: + async def go(): + ex = ServerPluginExecutor(conn) + r = await ex.execute(conn, "t_pool", {}) + assert r.response == "ok" + + asyncio.run(go()) + assert seen["thread"].startswith("plugin"), seen["thread"] # 专用池线程名前缀 + finally: + all_function_registry.pop("t_pool", None) From 5b0de039c993df5fd39cfb0ab8f63d5ee8d9bc8b Mon Sep 17 00:00:00 2001 From: hrz <1710360675@qq.com> Date: Tue, 3 Nov 2026 17:44:29 +0800 Subject: [PATCH 03/16] =?UTF-8?q?=E8=AE=A9=20CI=20=E7=9C=9F=E6=AD=A3?= =?UTF-8?q?=E8=B7=91=E8=B5=B7=E4=B8=89=E7=B1=BB=E6=B5=8B=E8=AF=95=E5=B9=B6?= =?UTF-8?q?=E4=BF=AE=E6=8E=89=E6=8C=A1=E8=B7=AF=E7=9A=84=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=BC=BA=E9=99=B7=20(#3475)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 让 CI 真正跑起三类测试并修掉挡路的测试缺陷 之前 CI 只跑了一小部分,Java 那边的测试被 pom 里的开关整个跳过了。 这条把它打开,并补上 MySQL、Redis 两个容器,Java、契约、Python 三类 测试都在 CI 里真跑起来。 另外修了两个挡路的地方:一条 Java 用例单跑会因为实体信息没注册而报错, 现在自己注册;Python 的假网络层把整个 httpx 类换掉了,第三方库拼请求 时报错,改成只换发请求那一步。 * 给 runner 补上 libopus,修掉音频用例报错 opuslib_next 是 ctypes 绑定,真正编解码靠系统里的 libopus。runner 上默认 没有,import 失败后测试里换上的是自己写的桩,桩里的编码器只有构造方法, 一调就报错。正式镜像里是装了这个库的,CI 少了这一步。 顺手把桩的报错改成一句人话,别再让人对着缺方法的报错猜根因。 * 本地没起库也能构建,CI 里集成测试不许跳过 三个要连 MySQL 和 Redis 的集成测试加了守卫:依赖连不上就整类跳过,日志写明缺什么,构建照样是绿的;CI 上依赖不通就直接失败。另外加了一个门禁检查脚本和 CI 步骤,盯住这三个类有没有真跑,守卫哪天手滑把它们全跳过了,CI 必须变红。README 里补了本地怎么起依赖、怎么只编译不跑测试。 --- .github/workflows/test.yml | 57 ++++++- main/manager-api/README.md | 25 +++ main/manager-api/pom.xml | 2 +- .../scripts/check-integration-tests.sh | 44 ++++++ .../impl/CorrectWordFileServiceImplTest.java | 19 +++ .../xiaozhi/modules/device/DeviceTest.java | 7 + .../impl/ModelConfigPersistenceTest.java | 7 + .../modules/sys/loginControllerTest.java | 7 + .../IntegrationTestEnvironment.java | 149 ++++++++++++++++++ main/xiaozhi-server/tests/conftest.py | 59 ++++--- main/xiaozhi-server/tests/test_llm.py | 7 + 11 files changed, 349 insertions(+), 34 deletions(-) create mode 100755 main/manager-api/scripts/check-integration-tests.sh create mode 100644 main/manager-api/src/test/java/xiaozhi/testsupport/IntegrationTestEnvironment.java diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 135cfbd65..a0d515a2f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -20,24 +20,58 @@ jobs: python-version: '3.10' cache: 'pip' cache-dependency-path: 'main/xiaozhi-server/requirements.txt' + - name: Install system dependencies + run: | + # opuslib_next 是 ctypes 绑定,pip 装上的是纯 Python 包,真正的编解码 + # 靠系统里的 libopus.so。runner 上默认没有,import 会失败,音频相关的 + # 用例直接报错。正式镜像 Dockerfile-server-base 里也是装 libopus0 的 + sudo apt-get update + sudo apt-get install -y --no-install-recommends libopus0 - name: Install dependencies working-directory: main/xiaozhi-server run: | pip install -r requirements.txt pip install pytest pytest-asyncio freezegun - - name: Run smoke test + - name: Prepare test config working-directory: main/xiaozhi-server run: | - if [ -f tests/test_smoke.py ]; then - pytest tests/test_smoke.py -x -q - else - echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing" - exit 0 - fi + # config/settings.py 在 import 期就要这个文件,缺了整套用例连收集都过不去。 + # data/ 在 .gitignore 里,只能由这一步现造 + mkdir -p data + printf '{}\n' > data/.config.yaml + - name: Run tests + working-directory: main/xiaozhi-server + run: | + # Edge TTS 那条要连微软公网,runner 的出口 IP 会被风控挡掉,先排除。 + # 根治办法是给它打 live 标记,让 mock 模式下自动不收(另开一条改) + pytest tests/ -v -k "not test_tts_text_to_speak_writes_file" java: name: Java (manager-api) runs-on: ubuntu-latest + # 三个 @SpringBootTest 要真连 MySQL 和 Redis,空库即可,Liquibase 会自己建表 + services: + mysql: + image: mysql:8.0 + env: + MYSQL_ROOT_PASSWORD: 123456 + MYSQL_DATABASE: xiaozhi_esp32_server + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -p123456" + --health-interval=10s + --health-timeout=5s + --health-retries=20 + redis: + image: redis:8.0 + ports: + - 6379:6379 + options: >- + --health-cmd="redis-cli ping" + --health-interval=10s + --health-timeout=5s + --health-retries=20 steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 @@ -47,7 +81,12 @@ jobs: cache: 'maven' - name: Run tests working-directory: main/manager-api - run: mvn -B -q test -DfailIfNoTests=false + run: mvn -B test -DskipTests=false -DfailIfNoTests=false + - name: Check the integration tests really ran + working-directory: main/manager-api + # 守卫在依赖不齐时会把整类集成测试跳过,这里盯一下它们有没有真跑, + # 免得门禁被悄悄掏空 + run: bash scripts/check-integration-tests.sh web: name: Vue (manager-web) @@ -63,4 +102,6 @@ jobs: working-directory: main/manager-web run: | npm ci --no-audit --no-fund + npm run test:contract npm run test:unit + npm run build diff --git a/main/manager-api/README.md b/main/manager-api/README.md index 484c28dc0..19683a66b 100644 --- a/main/manager-api/README.md +++ b/main/manager-api/README.md @@ -16,3 +16,28 @@ Vue 3.x # 接口文档 启动后打开:http://localhost:8002/xiaozhi/doc.html +# 跑测试 +测试分两种:纯单元测试,和要真连 MySQL、Redis 的集成测试(`DeviceTest`、`loginControllerTest`、`ModelConfigPersistenceTest`)。 + +集成测试需要先起好 MySQL 8 和 Redis 8。没起的时候这类测试整类跳过,不会让构建变红,日志里会写明缺的是哪个依赖。CI 上不一样:依赖连不上就直接让构建失败,不许跳过,免得门禁被悄悄掏空。 + +本地用 Docker 起这两个依赖: + +```bash +docker run -d --name xiaozhi-mysql -p 3306:3306 \ + -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABASE=xiaozhi_esp32_server mysql:8.0 +docker run -d --name xiaozhi-redis -p 6379:6379 redis:8.0 +``` + +跑全部测试: + +```bash +mvn -B test -DskipTests=false +``` + +只想编译、不跑测试: + +```bash +mvn -B package -DskipTests=true +``` + diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml index 455ee6e11..e94004843 100644 --- a/main/manager-api/pom.xml +++ b/main/manager-api/pom.xml @@ -32,7 +32,7 @@ 4.20.0 4.1.0 3.4.0 - true + false diff --git a/main/manager-api/scripts/check-integration-tests.sh b/main/manager-api/scripts/check-integration-tests.sh new file mode 100755 index 000000000..526b80820 --- /dev/null +++ b/main/manager-api/scripts/check-integration-tests.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# 检查那几个要连 MySQL 和 Redis 的集成测试是不是真的跑了。 +# 守卫要是哪天手滑把它们全跳过了,CI 必须红,不能安安静静少跑一半门禁。 +set -uo pipefail + +REPORT_DIR="${1:-target/surefire-reports}" + +WATCHED=( + "xiaozhi.modules.device.DeviceTest" + "xiaozhi.modules.model.service.impl.ModelConfigPersistenceTest" + "xiaozhi.modules.sys.loginControllerTest" +) + +if [ ! -d "$REPORT_DIR" ]; then + echo "找不到测试报告目录:$REPORT_DIR" + exit 1 +fi + +missing=() +for class in "${WATCHED[@]}"; do + count=0 + for report in "$REPORT_DIR"/TEST-*.xml; do + [ -e "$report" ] || continue + name=$(sed -n 's/.*]*name="\([^"]*\)".*/\1/p' "$report" | head -1) + if [ "$name" = "$class" ]; then + count=$(sed -n 's/.*]*tests="\([0-9]*\)".*/\1/p' "$report" | head -1) + count=${count:-0} + break + fi + done + if [ "$count" -eq 0 ]; then + missing+=("$class") + else + echo "OK $class 跑了 $count 条" + fi +done + +if [ ${#missing[@]} -ne 0 ]; then + echo "这几个集成测试一条都没跑:${missing[*]}" + echo "守卫把门禁掏空了,构建必须失败" + exit 1 +fi + +echo "集成测试都跑过了" diff --git a/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java index 25fbebea7..b41953db6 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/correctword/service/impl/CorrectWordFileServiceImplTest.java @@ -14,9 +14,14 @@ import java.util.Collections; import java.util.Date; import java.util.List; +import org.apache.ibatis.builder.MapperBuilderAssistant; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; +import com.baomidou.mybatisplus.core.MybatisConfiguration; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; + import xiaozhi.modules.agent.dao.AgentCorrectWordMappingDao; import xiaozhi.modules.agent.entity.AgentCorrectWordMappingEntity; import xiaozhi.modules.correctword.dao.CorrectWordFileDao; @@ -37,6 +42,20 @@ class CorrectWordFileServiceImplTest { private final CorrectWordFileServiceImpl service = new CorrectWordFileServiceImpl(fileDao, itemDao, mappingDao); + @BeforeAll + static void registerEntityMetadata() { + // 这条用例不起 Spring 上下文,MyBatis-Plus 的实体元数据没人注册, + // LambdaQueryWrapper 拼条件时找不到 lambda 缓存就抛异常。 + // 全量跑的时候是前面的上下文测试顺带注册好的,单独跑就露馅。 + // 这里自己补上,单独跑和跟着全量跑结果一样。 + TableInfoHelper.initTableInfo( + new MapperBuilderAssistant(new MybatisConfiguration(), ""), + CorrectWordItemEntity.class); + TableInfoHelper.initTableInfo( + new MapperBuilderAssistant(new MybatisConfiguration(), ""), + CorrectWordFileEntity.class); + } + @Test void getAllItemsByAgentId_returns_empty_list_when_no_mappings() { when(mappingDao.selectByAgentId(AGENT_ID)).thenReturn(Collections.emptyList()); diff --git a/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java index 768818439..c15a51437 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/device/DeviceTest.java @@ -3,6 +3,7 @@ package xiaozhi.modules.device; import java.util.HashMap; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -15,6 +16,7 @@ import xiaozhi.common.exception.RenException; import xiaozhi.common.redis.RedisUtils; import xiaozhi.modules.sys.dto.SysUserDTO; import xiaozhi.modules.sys.service.SysUserService; +import xiaozhi.testsupport.IntegrationTestEnvironment; @Slf4j @SpringBootTest @@ -22,6 +24,11 @@ import xiaozhi.modules.sys.service.SysUserService; @DisplayName("设备测试") public class DeviceTest { + @BeforeAll + static void checkDependencies() { + IntegrationTestEnvironment.requireDatabaseAndRedis(); + } + @Autowired private RedisUtils redisUtils; @Autowired diff --git a/main/manager-api/src/test/java/xiaozhi/modules/model/service/impl/ModelConfigPersistenceTest.java b/main/manager-api/src/test/java/xiaozhi/modules/model/service/impl/ModelConfigPersistenceTest.java index 279d78ae7..5e9ae4b11 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/model/service/impl/ModelConfigPersistenceTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/model/service/impl/ModelConfigPersistenceTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; @@ -19,12 +20,18 @@ import xiaozhi.common.redis.RedisUtils; import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigDTO; import xiaozhi.modules.model.service.ModelConfigService; +import xiaozhi.testsupport.IntegrationTestEnvironment; @SpringBootTest @ActiveProfiles("dev") @Transactional class ModelConfigPersistenceTest { + @BeforeAll + static void checkDependencies() { + IntegrationTestEnvironment.requireDatabaseAndRedis(); + } + @Autowired private ModelConfigService service; diff --git a/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java b/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java index 4c5128842..885fb0db5 100644 --- a/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java +++ b/main/manager-api/src/test/java/xiaozhi/modules/sys/loginControllerTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -18,12 +19,18 @@ import xiaozhi.modules.security.dto.LoginDTO; import xiaozhi.modules.security.dto.SmsVerificationDTO; import xiaozhi.modules.sys.dto.RetrievePasswordDTO; import xiaozhi.modules.sys.service.SysUserService; +import xiaozhi.testsupport.IntegrationTestEnvironment; @Slf4j @SpringBootTest @ActiveProfiles("dev") class loginControllerTest { + @BeforeAll + static void checkDependencies() { + IntegrationTestEnvironment.requireDatabaseAndRedis(); + } + @Autowired LoginController loginController; diff --git a/main/manager-api/src/test/java/xiaozhi/testsupport/IntegrationTestEnvironment.java b/main/manager-api/src/test/java/xiaozhi/testsupport/IntegrationTestEnvironment.java new file mode 100644 index 000000000..32e33637e --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/testsupport/IntegrationTestEnvironment.java @@ -0,0 +1,149 @@ +package xiaozhi.testsupport; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Duration; + +import org.junit.jupiter.api.Assumptions; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.PropertySourcesPropertyResolver; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import lombok.extern.slf4j.Slf4j; + +/** + * 几个 @SpringBootTest 要真连 MySQL 和 Redis。本地没起这两个依赖时, + * 整类测试跳过,别让 Spring 上下文起不来变成一堆看不懂的报错; + * CI 里依赖必须真的在,探不通就直接让构建红。 + */ +@Slf4j +public final class IntegrationTestEnvironment { + + /** 集成测试用的配置文件,跟应用本身读的是同一套 */ + private static final String[] CONFIG_FILES = {"application.yml", "application-dev.yml"}; + + private static Boolean available; + private static String problem; + + private IntegrationTestEnvironment() { + } + + /** + * 放在要连库的测试类的 @BeforeAll 里。 + * 本地依赖不齐就整类跳过,CI 里依赖不齐就直接失败。 + */ + public static void requireDatabaseAndRedis() { + String issue = probe(); + if (issue == null) { + return; + } + if (isCi()) { + throw new IllegalStateException( + "CI 环境里" + issue + ",这几个集成测试必须真的跑起来,不能跳过"); + } + log.warn("跳过依赖 MySQL 和 Redis 的集成测试:{}", issue); + Assumptions.assumeTrue(false, issue); + } + + /** GitHub Actions 上会带 CI=true */ + public static boolean isCi() { + String value = System.getenv("CI"); + if (value == null) { + return false; + } + String trimmed = value.trim(); + return !trimmed.isEmpty() && !"false".equalsIgnoreCase(trimmed); + } + + /** 依赖都齐返回 null,不齐返回缺什么 */ + static synchronized String probe() { + if (available != null) { + return problem; + } + PropertySourcesPropertyResolver resolver = resolver(); + StringBuilder issues = new StringBuilder(); + + String url = firstNonBlank(resolver.getProperty("spring.datasource.druid.url", ""), + resolver.getProperty("spring.datasource.url", "")); + String username = firstNonBlank(resolver.getProperty("spring.datasource.druid.username", ""), + resolver.getProperty("spring.datasource.username", "")); + String password = firstNonBlank(resolver.getProperty("spring.datasource.druid.password", ""), + resolver.getProperty("spring.datasource.password", "")); + if (url.isBlank()) { + issues.append("配置里找不到数据源地址;"); + } else { + try { + DriverManager.setLoginTimeout(5); + try (Connection connection = DriverManager.getConnection(url, username, password)) { + connection.isValid(3); + } + } catch (Exception e) { + issues.append("连不上 MySQL(").append(e.getMessage()).append(");"); + } + } + + String redisHost = resolver.getProperty("spring.data.redis.host", "localhost"); + int redisPort = resolver.getProperty("spring.data.redis.port", Integer.class, 6379); + String redisPassword = resolver.getProperty("spring.data.redis.password", ""); + try { + RedisURI.Builder builder = RedisURI.builder() + .withHost(redisHost) + .withPort(redisPort) + .withTimeout(Duration.ofSeconds(3)); + if (redisPassword != null && !redisPassword.isBlank()) { + builder.withPassword(redisPassword.toCharArray()); + } + RedisClient client = RedisClient.create(builder.build()); + try { + StatefulRedisConnection connection = client.connect(); + connection.sync().ping(); + connection.close(); + } finally { + client.shutdown(); + } + } catch (Exception e) { + issues.append("连不上 Redis(").append(e.getMessage()).append(");"); + } + + if (issues.length() == 0) { + available = Boolean.TRUE; + problem = null; + } else { + available = Boolean.FALSE; + problem = issues.toString(); + } + return problem; + } + + /** 读应用自己那份配置,命令行上的 -D 参数优先级更高,跟应用保持一致 */ + private static PropertySourcesPropertyResolver resolver() { + ConfigurableEnvironment environment = new StandardEnvironment(); + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + for (String name : CONFIG_FILES) { + Resource resource = new ClassPathResource(name); + if (!resource.exists()) { + continue; + } + try { + for (PropertySource source : loader.load(name, resource)) { + environment.getPropertySources().addLast(source); + } + } catch (IOException e) { + log.warn("读配置 {} 失败:{}", name, e.getMessage()); + } + } + return new PropertySourcesPropertyResolver(environment.getPropertySources()); + } + + private static String firstNonBlank(String first, String second) { + return first != null && !first.isBlank() ? first : (second == null ? "" : second); + } +} diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py index a269bb77f..24af688b6 100644 --- a/main/xiaozhi-server/tests/conftest.py +++ b/main/xiaozhi-server/tests/conftest.py @@ -47,10 +47,29 @@ if str(_PROJECT_ROOT) not in sys.path: # --------------------------------------------------------------------------- try: import opuslib_next # noqa: F401 -except Exception: +except Exception as _opus_import_error: + # opuslib_next 是 ctypes 绑定,pip 装上的是纯 Python 包,真正的编解码靠系统里的 + # libopus.so。runner 上没装 libopus 时 import 会失败,这里换桩顶上。 + # 桩只能撑住 import 链路,真要编解码得先把 libopus 装上 + # (apt-get install libopus0,正式镜像 Dockerfile-server-base 里也是这么装的)。 + print( + f"[conftest] opuslib_next 不可用,改用桩:{_opus_import_error}", + flush=True, + ) + + def _opus_unavailable(_self, *_args, **_kwargs): + raise RuntimeError( + "libopus 没装,Opus 编解码跑不了。" + "装法:apt-get install libopus0(正式镜像 Dockerfile-server-base 里也是这么装的)" + ) + _stub = types.ModuleType("opuslib_next") - _stub.Encoder = type("Encoder", (), {"__init__": lambda *a, **kw: None}) - _stub.Decoder = type("Decoder", (), {"__init__": lambda *a, **kw: None}) + _stub.Encoder = type( + "Encoder", (), {"__init__": lambda *a, **kw: None, "encode": _opus_unavailable} + ) + _stub.Decoder = type( + "Decoder", (), {"__init__": lambda *a, **kw: None, "decode": _opus_unavailable} + ) _stub.APPLICATION_AUDIO = 0 _stub.OpusError = type("OpusError", (Exception,), {}) _stub.constants = types.SimpleNamespace() @@ -323,35 +342,25 @@ def _install_mock_layer() -> None: asyncio.sleep = _fast_sleep # type: ignore[assignment] - # 网络层 mock:如果真实 httpx 已加载,把它的 AsyncClient.send 替换成 + # 网络层 mock:如果真实 httpx 已加载,把它的 send 替换成 # 立即抛 ConnectError 的桩,触发 ``_should_retry`` 走到 ``raise``, # 但避免真发请求。Live 模式完全不安装这层。 if not LIVE_API_TESTS: try: - import httpx as _httpx # noqa: F401 + import httpx as _httpx - class _FakeAsyncClient: - def __init__(self, *args, **kwargs): - pass + async def _fake_async_send(self, request, **kwargs): + raise _httpx.ConnectError("MOCK: connect refused") - async def send(self, *args, **kwargs): - raise _httpx.ConnectError("MOCK: connect refused") + def _fake_send(self, request, **kwargs): + raise _httpx.ConnectError("MOCK: connect refused") - async def aclose(self): - return None - - class _FakeClient: - def __init__(self, *args, **kwargs): - pass - - def send(self, *args, **kwargs): - raise _httpx.ConnectError("MOCK: connect refused") - - def close(self): - return None - - _httpx.AsyncClient = _FakeAsyncClient # type: ignore[misc] - _httpx.Client = _FakeClient # type: ignore[misc] + # 只换 send 这一个方法,不换整个类。有些库(openai 2.x 的 + # SyncHttpxClientWrapper)继承 httpx.Client 再自己拼请求, + # 整个类被换掉的话它们继承到的是假类,拼请求时直接 + # AttributeError,报错还完全看不出是 mock 层的问题 + _httpx.AsyncClient.send = _fake_async_send # type: ignore[assignment] + _httpx.Client.send = _fake_send # type: ignore[assignment] except ImportError: pass diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py index 931a16f9f..5a83f5826 100644 --- a/main/xiaozhi-server/tests/test_llm.py +++ b/main/xiaozhi-server/tests/test_llm.py @@ -65,6 +65,13 @@ def _build_provider(): ptype = get_provider_type("LLM", name) if not ptype: pytest.skip(f"LLM '{name}' 的 type 字段缺失") + if not LIVE_API_TESTS: + # mock 模式把网络拦了,这条链路拿不到真实回复,跑下来只是一次连接失败。 + # 真要验这条链路,用 RUN_LIVE_API_TESTS=1 配真 key 跑 + pytest.skip( + f"mock 模式不发真请求,跳过 LLM '{name}' 的链路验证。" + "真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。" + ) from core.utils.llm import create_instance return create_instance(ptype, cfg) From 7d9f47b0d18a3b59f2083dcc8f2dac8065f3be66 Mon Sep 17 00:00:00 2001 From: Nirupam Bhowmick <48842933+heydryft@users.noreply.github.com> Date: Wed, 4 Nov 2026 02:22:41 +0000 Subject: [PATCH 04/16] =?UTF-8?q?feat(web=5Fsearch):=20=E6=96=B0=E5=A2=9EO?= =?UTF-8?q?utcrawl=E6=90=9C=E7=B4=A2=E6=BA=90=20(#3538)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/web-search-integration.md | 16 ++- .../resources/db/changelog/202611021200.sql | 9 ++ .../db/changelog/db.changelog-master.yaml | 7 ++ main/xiaozhi-server/config.yaml | 7 +- .../plugins_func/functions/web_search.py | 42 +++++++ .../plugins_func/test_web_search_outcrawl.py | 119 ++++++++++++++++++ 6 files changed, 193 insertions(+), 7 deletions(-) create mode 100644 main/manager-api/src/main/resources/db/changelog/202611021200.sql create mode 100644 main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py diff --git a/docs/web-search-integration.md b/docs/web-search-integration.md index cb694e912..77eb171f6 100644 --- a/docs/web-search-integration.md +++ b/docs/web-search-integration.md @@ -2,14 +2,15 @@ ## 功能简介 -联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持三个搜索源:秘塔(Metaso)、Tavily和Serply,用户可根据需要选择其中一个。 +联网搜索插件 `web_search` 支持在对话过程中实时联网搜索信息并返回结果。插件支持四个搜索源:秘塔(Metaso)、Tavily、Serply和Outcrawl,用户可根据需要选择其中一个。 ## API Key申请指南 -目前我们适配了`秘塔搜索`、`Tavily搜索`和`Serply搜索`。 +目前我们适配了`秘塔搜索`、`Tavily搜索`、`Serply搜索`和`Outcrawl搜索`。 - Tavily搜索:每个月1000次免费额度。 - 秘塔搜索:拥有较为优质的国内数据源。 - Serply搜索:返回谷歌搜索结果,注册赠送2500次免费额度,额度用完后需要付费。 +- Outcrawl搜索:面向AI智能体的网页搜索接口,每月1000 credits免费额度。 ## API Key申请指南 @@ -32,6 +33,13 @@ - 复制生成的API Key,这是配置所需的关键信息 - 接口说明见 [Serply文档](https://serply.io/docs) +### 方式四:使用Outcrawl搜索 + +- 访问 [Outcrawl](https://outcrawl.ai),注册并登录账号 +- 在控制台中创建API Key +- 复制生成的API Key,这是配置所需的关键信息 +- 接口说明见 [Outcrawl文档](https://outcrawl.ai/docs/search/overview) + ## 配置方式 ### 方式1. 使用智控台部署(推荐) @@ -40,14 +48,14 @@ - 进入"配置角色"页面,选择要配置的智能体 - 点击"编辑功能"按钮,在右侧参数配置区域找到"联网搜索"插件 - 勾选"联网搜索" -- 填入搜索源(`metaso`、`tavily`或`serply`),并将对应的`API Key`填入配置项 +- 填入搜索源(`metaso`、`tavily`、`serply`或`outcrawl`),并将对应的`API Key`填入配置项 - 保存配置,再保存智能体配置 ### 方式2. 单模块xiaozhi-server部署 在 `data/.config.yaml` 中配置: -- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily` 或 `serply` +- 将搜索源填入 `provider`,可选值为 `metaso`、`tavily`、`serply` 或 `outcrawl` - 将申请到的API Key填入 `api_key` ```yaml diff --git a/main/manager-api/src/main/resources/db/changelog/202611021200.sql b/main/manager-api/src/main/resources/db/changelog/202611021200.sql new file mode 100644 index 000000000..672654907 --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202611021200.sql @@ -0,0 +1,9 @@ +-- 联网搜索插件新增Outcrawl搜索源 + +UPDATE `ai_model_provider` +SET `fields` = JSON_SET( + `fields`, + '$[0].label', + '搜索源:metaso / tavily / serply / outcrawl' +) +WHERE `id` = 'SYSTEM_PLUGIN_WEB_SEARCH'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 1b2eb615a..31ac557f9 100644 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -760,3 +760,10 @@ databaseChangeLog: - sqlFile: encoding: utf8 path: classpath:db/changelog/202610302051.sql + - changeSet: + id: 202611021200 + author: heydryft + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/202611021200.sql diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 2ba213e14..66a97e81a 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -172,18 +172,19 @@ plugins: # ragflow知识库id dataset_ids: ["123456789"] # 联网搜索插件配置 - # 支持秘塔(metaso)、Tavily和Serply三个搜索源 + # 支持秘塔(metaso)、Tavily、Serply和Outcrawl四个搜索源 # 秘塔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 web_search: - # 搜索源:metaso / tavily / serply + # 搜索源:metaso / tavily / serply / outcrawl provider: "metaso" # 工具描述,用于告知LLM何时调用此工具,可根据需要自定义 description: "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。" # 返回结果数量(默认5) max_results: 5 - # 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key + # 秘塔API Key(mk-前缀) / Tavily API Key(tvly-前缀) / Serply API Key / Outcrawl API Key api_key: "mk-xxx" # 声纹识别配置 voiceprint: diff --git a/main/xiaozhi-server/plugins_func/functions/web_search.py b/main/xiaozhi-server/plugins_func/functions/web_search.py index 611733573..fab57ffe4 100644 --- a/main/xiaozhi-server/plugins_func/functions/web_search.py +++ b/main/xiaozhi-server/plugins_func/functions/web_search.py @@ -149,6 +149,46 @@ async def _search_serply(api_key: str, query: str, max_results: int) -> str: return "\n".join(lines) +async def _search_outcrawl(api_key: str, query: str, max_results: int) -> str: + """调用Outcrawl搜索API""" + url = "https://api.outcrawl.ai/v1/search" + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + "User-Agent": "xiaozhi-esp32-server", + } + # Outcrawl单次最多返回20条 + payload = {"query": query, "limit": max(1, min(max_results, 20))} + logger.bind(tag=TAG).debug(f"Outcrawl搜索请求 | 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"Outcrawl搜索响应 | status: {response.status_code}") + + if response.status_code != 200: + detail = data.get("message", "") if isinstance(data, dict) else "" + logger.bind(tag=TAG).error( + f"Outcrawl搜索失败 | status: {response.status_code} | detail: {detail}" + ) + if response.status_code == 402: + return "联网搜索额度已用完,请检查Outcrawl账户余额。" + return "联网搜索请求失败,请检查API Key是否正确。" + + hits = data.get("hits", []) + if not hits: + return "未找到相关搜索结果。" + + lines = ["【联网搜索结果】"] + for i, item in enumerate(hits[:max_results], 1): + title = item.get("title") or "无标题" + snippet = item.get("snippet", "") + lines.append(f"{i}. 标题:{title}") + 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}") @@ -175,6 +215,8 @@ async def web_search(conn: "ConnectionHandler", query: str = None): result_text = await _search_tavily(api_key, query, max_results) elif provider == "serply": result_text = await _search_serply(api_key, query, max_results) + elif provider == "outcrawl": + result_text = await _search_outcrawl(api_key, query, max_results) else: return ActionResponse( Action.REQLLM, diff --git a/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py b/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py new file mode 100644 index 000000000..31006aa36 --- /dev/null +++ b/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py @@ -0,0 +1,119 @@ +"""Tests for the Outcrawl 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={"hits": []}) + 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_outcrawl_sends_bearer_key_and_limit(fake_http): + await web_search_module._search_outcrawl("oc-key", "上海天气", 5) + + [request] = fake_http.requests + assert request["url"] == "https://api.outcrawl.ai/v1/search" + assert request["json"] == {"query": "上海天气", "limit": 5} + assert request["headers"]["Authorization"] == "Bearer oc-key" + assert request["headers"]["User-Agent"] == "xiaozhi-esp32-server" + + +@pytest.mark.parametrize(("max_results", "limit"), [(0, 1), (50, 20)]) +async def test_outcrawl_clamps_limit(fake_http, max_results, limit): + await web_search_module._search_outcrawl("oc-key", "q", max_results) + + assert fake_http.requests[0]["json"]["limit"] == limit + + +async def test_outcrawl_formats_titles_and_snippets_without_urls(fake_http): + fake_http.response = FakeResponse( + payload={ + "hits": [ + {"url": "https://a.example/1", "title": "标题一", "snippet": "摘要一", "rank": 1}, + {"url": "https://a.example/2", "title": None, "snippet": "", "rank": 2}, + {"url": "https://a.example/3", "title": "标题三", "snippet": "摘要三", "rank": 3}, + ], + "usage": {"credits": "1.5"}, + } + ) + + result = await web_search_module._search_outcrawl("oc-key", "q", 2) + + assert result == "【联网搜索结果】\n1. 标题:标题一\n 摘要:摘要一\n2. 标题:无标题" + assert "https://" not in result + + +async def test_outcrawl_empty_hits(fake_http): + fake_http.response = FakeResponse(payload={"hits": []}) + + assert await web_search_module._search_outcrawl("oc-key", "q", 3) == "未找到相关搜索结果。" + + +@pytest.mark.parametrize( + ("status_code", "message"), + [ + (401, "联网搜索请求失败,请检查API Key是否正确。"), + (402, "联网搜索额度已用完,请检查Outcrawl账户余额。"), + (429, "联网搜索请求失败,请检查API Key是否正确。"), + ], +) +async def test_outcrawl_error_status(fake_http, status_code, message): + fake_http.response = FakeResponse(status_code=status_code, payload={"message": "denied"}) + + assert await web_search_module._search_outcrawl("oc-key", "q", 3) == message + + +async def test_web_search_dispatches_to_outcrawl(fake_http): + fake_http.response = FakeResponse(payload={"hits": [{"url": "https://a.example", "title": "T", "snippet": "S"}]}) + conn = FakeConn({"provider": "Outcrawl", "api_key": "oc-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", "limit": 3} From 6589f7f4815d68c8167892150dc1a481ec8d06d3 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Wed, 4 Nov 2026 11:26:20 +0800 Subject: [PATCH 05/16] =?UTF-8?q?=E8=B0=83=E6=95=B4=E4=B8=BAcode=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugins_func/functions/web_search.py | 16 ++++++++++++---- .../plugins_func/test_web_search_outcrawl.py | 15 +++++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/main/xiaozhi-server/plugins_func/functions/web_search.py b/main/xiaozhi-server/plugins_func/functions/web_search.py index fab57ffe4..623fc5f66 100644 --- a/main/xiaozhi-server/plugins_func/functions/web_search.py +++ b/main/xiaozhi-server/plugins_func/functions/web_search.py @@ -166,13 +166,21 @@ async def _search_outcrawl(api_key: str, query: str, max_results: int) -> str: logger.bind(tag=TAG).debug(f"Outcrawl搜索响应 | status: {response.status_code}") if response.status_code != 200: + # 错误信封为 {"code": "...", "message": "...", "details": {}}, + # code 是官方承诺的封闭枚举 + code = data.get("code", "") if isinstance(data, dict) else "" detail = data.get("message", "") if isinstance(data, dict) else "" logger.bind(tag=TAG).error( - f"Outcrawl搜索失败 | status: {response.status_code} | detail: {detail}" + f"Outcrawl搜索失败 | status: {response.status_code} | code: {code} | detail: {detail}" ) - if response.status_code == 402: - return "联网搜索额度已用完,请检查Outcrawl账户余额。" - return "联网搜索请求失败,请检查API Key是否正确。" + if code == "quota_exceeded": + # 该code覆盖两种情况:每分钟请求数限流,或月度credits用尽 + return "联网搜索被限流或额度已用完,请稍后重试或检查Outcrawl账户余额。" + if code == "unauthorized": + return "联网搜索请求失败,请检查API Key是否正确。" + # 其余code(bad_request、no_capacity、search_refused、internal等) + # 多为输入问题或服务端暂时性故障,统一引导重试 + return "联网搜索请求失败,请稍后重试。" hits = data.get("hits", []) if not hits: diff --git a/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py b/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py index 31006aa36..12b9f8d12 100644 --- a/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py +++ b/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py @@ -95,15 +95,18 @@ async def test_outcrawl_empty_hits(fake_http): @pytest.mark.parametrize( - ("status_code", "message"), + ("code", "message"), [ - (401, "联网搜索请求失败,请检查API Key是否正确。"), - (402, "联网搜索额度已用完,请检查Outcrawl账户余额。"), - (429, "联网搜索请求失败,请检查API Key是否正确。"), + ("unauthorized", "联网搜索请求失败,请检查API Key是否正确。"), + ("quota_exceeded", "联网搜索被限流或额度已用完,请稍后重试或检查Outcrawl账户余额。"), + ("bad_request", "联网搜索请求失败,请稍后重试。"), + ("internal", "联网搜索请求失败,请稍后重试。"), ], ) -async def test_outcrawl_error_status(fake_http, status_code, message): - fake_http.response = FakeResponse(status_code=status_code, payload={"message": "denied"}) +async def test_outcrawl_error_code(fake_http, code, message): + fake_http.response = FakeResponse( + status_code=429, payload={"code": code, "message": "denied", "details": {}} + ) assert await web_search_module._search_outcrawl("oc-key", "q", 3) == message From c59b29c7233e76078f3cec96172bc9e2999bb8c2 Mon Sep 17 00:00:00 2001 From: koala553 <3118758825@qq.com> Date: Thu, 5 Nov 2026 10:10:17 +0800 Subject: [PATCH 06/16] fix: prevent tool description cache mutation (#3540) --- .../core/providers/tools/unified_tool_manager.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py index f69a6dc39..8293badc5 100644 --- a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py +++ b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py @@ -47,9 +47,12 @@ class ToolManager: return all_tools def get_function_descriptions(self) -> List[Dict[str, Any]]: - """获取所有工具的函数描述(OpenAI格式)""" + """获取所有工具的函数描述(OpenAI格式) + + 返回缓存的浅拷贝,防止调用方就地修改污染缓存。 + """ if self._cached_function_descriptions is not None: - return self._cached_function_descriptions + return list(self._cached_function_descriptions) descriptions = [] tools = self.get_all_tools() @@ -57,7 +60,7 @@ class ToolManager: descriptions.append(tool_definition.description) self._cached_function_descriptions = descriptions - return descriptions + return list(descriptions) def has_tool(self, tool_name: str) -> bool: """检查是否存在指定工具""" From 70f1a7bfd8e8ef411a379b0fe70417c9dd77e839 Mon Sep 17 00:00:00 2001 From: Bao1573 <77220108+PG2047@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:50:39 +0800 Subject: [PATCH 07/16] =?UTF-8?q?fix(hass):=20devices=20=E5=86=99=E6=88=90?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E6=97=B6=E4=B9=9F=E8=83=BD=E6=8B=BC=E8=BF=9B?= =?UTF-8?q?=E6=8F=90=E7=A4=BA=E8=AF=8D=20(#3541)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit config.yaml 示例和手机端智控台给的 devices 是列表,append_devices_to_prompt 却按字符串直接拼,每次连接都报 can only concatenate str (not "list") to str,设备清单进不了提示词,模型只能猜 entity_id。列表按每项一行拼,字符串原样用,其它当空。附测试。 --- .../plugins_func/functions/hass_init.py | 15 +++- .../tests/plugins_func/test_hass_init.py | 76 +++++++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 main/xiaozhi-server/tests/plugins_func/test_hass_init.py diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py index a106d16d3..2487b5ee7 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_init.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py @@ -5,6 +5,17 @@ TAG = __name__ logger = setup_logging() +def _devices_text(devices) -> str: + """把 devices 配置转成拼进提示词的文字。 + + config.yaml 示例和手机端智控台给的是列表,每项一条"位置,设备名,entity_id",这里拼成每行一条; + 网页端智控台和 HA 集成文档是一段字符串,原样用;其它(如 None)当空。 + """ + if isinstance(devices, (list, tuple)): + return "\n".join(str(d).strip() for d in devices if str(d).strip()) + return devices if isinstance(devices, str) else "" + + def append_devices_to_prompt(conn): if conn.intent_type == "function_call": funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get( @@ -21,7 +32,9 @@ def append_devices_to_prompt(conn): if "hass_get_state" in funcs or "hass_set_state" in funcs: prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" - deviceStr = plugins_config.get(config_source, {}).get("devices", "") + deviceStr = _devices_text( + plugins_config.get(config_source, {}).get("devices", "") + ) conn.prompt += prompt + deviceStr + "\n" # 更新提示词 conn.dialogue.update_system_message(conn.prompt) diff --git a/main/xiaozhi-server/tests/plugins_func/test_hass_init.py b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py new file mode 100644 index 000000000..49b5b2989 --- /dev/null +++ b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py @@ -0,0 +1,76 @@ +"""append_devices_to_prompt:devices 写成列表或一段字符串都能拼进提示词。 + +config.yaml 示例和手机端智控台给的是列表,以前会报 +can only concatenate str (not "list") to str,设备清单进不了提示词,模型只能猜 entity_id。 +""" +import pytest + +from plugins_func.functions.hass_init import append_devices_to_prompt + +HEADER = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" +BASE_PROMPT = "你是小智。" + + +class FakeDialogue: + def __init__(self): + self.system_messages = [] + + def update_system_message(self, prompt): + self.system_messages.append(prompt) + + +class FakeConn: + def __init__(self, plugin, source="home_assistant", functions=("hass_get_state", "hass_set_state")): + self.intent_type = "function_call" + self.config = { + "selected_module": {"Intent": "function_call"}, + "Intent": {"function_call": {"functions": list(functions)}}, + "plugins": {source: plugin}, + } + self.prompt = BASE_PROMPT + self.dialogue = FakeDialogue() + + +def _plugin(**extra): + return {"base_url": "http://homeassistant.local:8123", "api_key": "test-token", **extra} + + +def test_list_devices_one_per_line(): + conn = FakeConn(_plugin(devices=[ + "客厅,玩具灯,switch.toy_lamp", + " 卧室,台灯,switch.desk_lamp ", + "", + ])) + append_devices_to_prompt(conn) + expected = BASE_PROMPT + HEADER + "客厅,玩具灯,switch.toy_lamp\n卧室,台灯,switch.desk_lamp\n" + assert conn.prompt == expected + assert conn.dialogue.system_messages == [expected] + + +def test_string_devices_kept_as_is(): + # 网页端智控台和 HA 集成文档给的是一段字符串 + devices = "客厅,玩具灯,switch.toy_lamp;\n卧室,台灯,switch.desk_lamp;" + conn = FakeConn(_plugin(devices=devices)) + append_devices_to_prompt(conn) + assert conn.prompt == BASE_PROMPT + HEADER + devices + "\n" + + +def test_mobile_console_hass_state_list(): + # 智控台下发的插件配置键是 hass_state;手机端把 array 字段按行切成了列表 + conn = FakeConn(_plugin(devices=["客厅,玩具灯,switch.toy_lamp"]), source="hass_state") + append_devices_to_prompt(conn) + assert conn.prompt.endswith(HEADER + "客厅,玩具灯,switch.toy_lamp\n") + + +@pytest.mark.parametrize("plugin", [_plugin(), _plugin(devices=None), _plugin(devices=[])]) +def test_missing_or_empty_devices_does_not_raise(plugin): + conn = FakeConn(plugin) + append_devices_to_prompt(conn) + assert conn.prompt == BASE_PROMPT + HEADER + "\n" + + +def test_without_hass_functions_prompt_unchanged(): + conn = FakeConn(_plugin(devices=["客厅,玩具灯,switch.toy_lamp"]), functions=("get_weather",)) + append_devices_to_prompt(conn) + assert conn.prompt == BASE_PROMPT + assert conn.dialogue.system_messages == [] From 9f5f52057692255fd32e197d87eee599a4424699 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Thu, 5 Nov 2026 15:36:04 +0800 Subject: [PATCH 08/16] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dha=E8=AF=BB?= =?UTF-8?q?=E5=8F=96=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../providers/intent/intent_llm/intent_llm.py | 14 ++--- .../plugins_func/functions/hass_init.py | 52 +++++++++++-------- .../tests/plugins_func/test_hass_init.py | 8 +++ 3 files changed, 42 insertions(+), 32 deletions(-) diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index cd150bc59..1dd5bb172 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -5,6 +5,7 @@ if TYPE_CHECKING: from core.connection import ConnectionHandler from ..base import IntentProviderBase from plugins_func.functions.play_music import initialize_music_handler +from plugins_func.functions.hass_init import _devices_text, _hass_plugin_config from config.logger import setup_logging from core.utils.util import get_system_error_response import re @@ -181,16 +182,11 @@ class IntentProvider(IntentProviderBase): music_file_names = music_config["music_file_names"] prompt_music = f"{self.promot}\n{music_file_names}\n" - home_assistant_cfg = conn.config["plugins"].get("home_assistant") - if home_assistant_cfg: - devices = home_assistant_cfg.get("devices", []) - else: - devices = [] - if len(devices) > 0: + plugin_config = _hass_plugin_config(conn.config.get("plugins", {})) + devices_text = _devices_text(plugin_config.get("devices", "")) + if devices_text: hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" - for device in devices: - hass_prompt += device + "\n" - prompt_music += hass_prompt + prompt_music += hass_prompt + devices_text + "\n" logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}") diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py index 2487b5ee7..2a0c2edd4 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_init.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py @@ -1,10 +1,19 @@ from config.logger import setup_logging from core.utils.util import check_model_key +from plugins_func.register import module_func_map TAG = __name__ logger = setup_logging() +def _expand_module_names(funcs): + """把 functions 列表里的模块名(如 hass_state)展开成具体函数名,与工具加载口径一致。""" + expanded = [] + for name in funcs: + expanded.extend(module_func_map.get(name, [name])) + return expanded + + def _devices_text(devices) -> str: """把 devices 配置转成拼进提示词的文字。 @@ -12,29 +21,33 @@ def _devices_text(devices) -> str: 网页端智控台和 HA 集成文档是一段字符串,原样用;其它(如 None)当空。 """ if isinstance(devices, (list, tuple)): - return "\n".join(str(d).strip() for d in devices if str(d).strip()) + return "\n".join( + str(d).strip() for d in devices if d is not None and str(d).strip() + ) return devices if isinstance(devices, str) else "" +def _hass_plugin_config(plugins_config: dict) -> dict: + """取 HA 插件配置:优先本地 config.yaml 的 home_assistant,其次智控台下发的 hass_state。""" + for key in ("home_assistant", "hass_state"): + cfg = plugins_config.get(key) + if cfg: + return cfg + return {} + + def append_devices_to_prompt(conn): if conn.intent_type == "function_call": - funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get( - "functions", [] - ) - - # 安全地获取插件配置 - plugins_config = conn.config.get("plugins", {}) - config_source = ( - "home_assistant" - if plugins_config.get("home_assistant") - else "hass_state" + funcs = _expand_module_names( + conn.config["Intent"][conn.config["selected_module"]["Intent"]].get( + "functions", [] + ) ) if "hass_get_state" in funcs or "hass_set_state" in funcs: prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" - deviceStr = _devices_text( - plugins_config.get(config_source, {}).get("devices", "") - ) + plugin_config = _hass_plugin_config(conn.config.get("plugins", {})) + deviceStr = _devices_text(plugin_config.get("devices", "")) conn.prompt += prompt + deviceStr + "\n" # 更新提示词 conn.dialogue.update_system_message(conn.prompt) @@ -45,17 +58,10 @@ def initialize_hass_handler(conn): if not conn.load_function_plugin: return ha_config - # 安全地获取插件配置 - plugins_config = conn.config.get("plugins", {}) - # 确定配置来源 - config_source = ( - "home_assistant" if plugins_config.get("home_assistant") else "hass_state" - ) - if not plugins_config.get(config_source): + plugin_config = _hass_plugin_config(conn.config.get("plugins", {})) + if not plugin_config: return ha_config - # 统一获取配置 - plugin_config = plugins_config[config_source] ha_config["base_url"] = plugin_config.get("base_url") ha_config["api_key"] = plugin_config.get("api_key") diff --git a/main/xiaozhi-server/tests/plugins_func/test_hass_init.py b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py index 49b5b2989..4e2ee69e9 100644 --- a/main/xiaozhi-server/tests/plugins_func/test_hass_init.py +++ b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py @@ -5,6 +5,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 HEADER = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n" @@ -62,6 +63,13 @@ def test_mobile_console_hass_state_list(): assert conn.prompt.endswith(HEADER + "客厅,玩具灯,switch.toy_lamp\n") +def test_module_name_in_functions(): + # functions 里写模块名 hass_state(config.yaml 注释的写法),展开后应能匹配 + conn = FakeConn(_plugin(devices=["客厅,玩具灯,switch.toy_lamp"]), functions=("hass_state",)) + append_devices_to_prompt(conn) + assert conn.prompt.endswith(HEADER + "客厅,玩具灯,switch.toy_lamp\n") + + @pytest.mark.parametrize("plugin", [_plugin(), _plugin(devices=None), _plugin(devices=[])]) def test_missing_or_empty_devices_does_not_raise(plugin): conn = FakeConn(plugin) From b4e144afef63bdcbfab0cfbafbd38251370e33b7 Mon Sep 17 00:00:00 2001 From: Bao1573 <77220108+PG2047@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:07:40 +0800 Subject: [PATCH 09/16] =?UTF-8?q?fix(hass):=20hass=5Fget=5Fstate=20?= =?UTF-8?q?=E7=9A=84=E4=BA=AE=E5=BA=A6=E6=8C=89=E7=99=BE=E5=88=86=E6=AF=94?= =?UTF-8?q?=E6=8A=A5=20(#3542)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HA 的 brightness 量程是 0~255,原样交给模型会被念成"一百五十三";灯关着时是 null,还会报"亮度是:None"。换算成百分比,和设置亮度用的 brightness_pct 同一个单位,开着的灯最低报 1%(同 HA 前端);不是数字时不报这一项。附测试。 --- .../plugins_func/functions/hass_state.py | 13 ++-- .../tests/plugins_func/test_hass_state.py | 71 +++++++++++++++++++ 2 files changed, 77 insertions(+), 7 deletions(-) create mode 100644 main/xiaozhi-server/tests/plugins_func/test_hass_state.py diff --git a/main/xiaozhi-server/plugins_func/functions/hass_state.py b/main/xiaozhi-server/plugins_func/functions/hass_state.py index 240f7cd35..8dd7076d4 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_state.py @@ -142,13 +142,12 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id): + str(response.json()["attributes"]["rgb_color"]) + " " ) - if "brightness" in response.json()["attributes"]: - responsetext = ( - responsetext - + "亮度是:" - + str(response.json()["attributes"]["brightness"]) - + " " - ) + brightness = response.json()["attributes"].get("brightness") + if isinstance(brightness, (int, float)): + # HA 的 brightness 量程是 0~255,原样报出去会被念成"一百五十三"; + # 换算成百分比,和设置亮度(brightness_pct,1~100)同一个单位。开着的灯最低报 1%(同 HA 前端) + percent = max(1, round(brightness * 100 / 255)) if brightness > 0 else 0 + responsetext = responsetext + "亮度是:" + f"{percent}%" + " " logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}") return responsetext else: diff --git a/main/xiaozhi-server/tests/plugins_func/test_hass_state.py b/main/xiaozhi-server/tests/plugins_func/test_hass_state.py new file mode 100644 index 000000000..ed2c15ee2 --- /dev/null +++ b/main/xiaozhi-server/tests/plugins_func/test_hass_state.py @@ -0,0 +1,71 @@ +"""hass_get_state 交回的亮度按百分比报。 + +HA 的 brightness 量程是 0~255,原样报会被念成"一百五十三";灯关着时是 null,以前还会报"亮度是:None"。 +HTTP 层换成假的客户端,不出网。 +""" +import httpx +import pytest + +from plugins_func.functions import hass_state as hass_module + + +class FakeResponse: + def __init__(self, payload, status_code=200): + self.payload = payload + self.status_code = status_code + + def json(self): + return self.payload + + +class FakeAsyncClient: + payload = 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, headers=None): + return FakeResponse(FakeAsyncClient.payload) + + +class FakeConn: + def __init__(self): + self.load_function_plugin = True + self.config = { + "plugins": { + "home_assistant": { + "base_url": "http://homeassistant.local:8123", + "api_key": "test-token", + } + } + } + + +@pytest.fixture +def fake_http(monkeypatch): + monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient) + return FakeAsyncClient + + +async def _get_state(fake_http, attributes, state="on"): + fake_http.payload = {"state": state, "attributes": attributes} + return await hass_module.handle_hass_get_state(FakeConn(), "light.desk_lamp") + + +@pytest.mark.parametrize("raw, shown", [(153, "60%"), (255, "100%"), (128, "50%"), (1, "1%"), (0, "0%")]) +async def test_brightness_reported_as_percent(fake_http, raw, shown): + text = await _get_state(fake_http, {"brightness": raw, "color_temp_kelvin": 4000}) + assert f"亮度是:{shown} " in text + assert text.startswith("设备状态:on ") and "色温是:4000 " in text + + +async def test_no_brightness_line_when_off_or_missing(fake_http): + # 灯关着时 HA 给 brightness: null + assert await _get_state(fake_http, {"brightness": None}, state="off") == "设备状态:off " + assert "亮度" not in await _get_state(fake_http, {"friendly_name": "台灯"}) From dd367c9e43042c67544e3d6b0aeb16a17834ffb4 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Thu, 5 Nov 2026 16:35:18 +0800 Subject: [PATCH 10/16] =?UTF-8?q?=E8=A1=A5=E5=85=85=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugins_func/functions/hass_state.py | 14 ++-- .../tests/plugins_func/test_hass_state.py | 71 ------------------- 2 files changed, 5 insertions(+), 80 deletions(-) delete mode 100644 main/xiaozhi-server/tests/plugins_func/test_hass_state.py diff --git a/main/xiaozhi-server/plugins_func/functions/hass_state.py b/main/xiaozhi-server/plugins_func/functions/hass_state.py index 8dd7076d4..e9d5850ab 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_state.py @@ -121,13 +121,10 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id): + str(response.json()["attributes"]["media_title"]) + " " ) - if "volume_level" in response.json()["attributes"]: - responsetext = ( - responsetext - + "音量是:" - + str(response.json()["attributes"]["volume_level"]) - + " " - ) + volume_level = response.json()["attributes"].get("volume_level") + if isinstance(volume_level, (int, float)): + # volume_level 量程 0~1,换算成百分比(同 volume_set 的 1~100) + responsetext = responsetext + "音量是:" + f"{round(volume_level * 100)}%" + " " if "color_temp_kelvin" in response.json()["attributes"]: responsetext = ( responsetext @@ -144,8 +141,7 @@ async def handle_hass_get_state(conn: "ConnectionHandler", entity_id): ) brightness = response.json()["attributes"].get("brightness") if isinstance(brightness, (int, float)): - # HA 的 brightness 量程是 0~255,原样报出去会被念成"一百五十三"; - # 换算成百分比,和设置亮度(brightness_pct,1~100)同一个单位。开着的灯最低报 1%(同 HA 前端) + # brightness 量程 0~255,换算成百分比(同 brightness_pct 的 1~100),开灯最低报 1% percent = max(1, round(brightness * 100 / 255)) if brightness > 0 else 0 responsetext = responsetext + "亮度是:" + f"{percent}%" + " " logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}") diff --git a/main/xiaozhi-server/tests/plugins_func/test_hass_state.py b/main/xiaozhi-server/tests/plugins_func/test_hass_state.py deleted file mode 100644 index ed2c15ee2..000000000 --- a/main/xiaozhi-server/tests/plugins_func/test_hass_state.py +++ /dev/null @@ -1,71 +0,0 @@ -"""hass_get_state 交回的亮度按百分比报。 - -HA 的 brightness 量程是 0~255,原样报会被念成"一百五十三";灯关着时是 null,以前还会报"亮度是:None"。 -HTTP 层换成假的客户端,不出网。 -""" -import httpx -import pytest - -from plugins_func.functions import hass_state as hass_module - - -class FakeResponse: - def __init__(self, payload, status_code=200): - self.payload = payload - self.status_code = status_code - - def json(self): - return self.payload - - -class FakeAsyncClient: - payload = 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, headers=None): - return FakeResponse(FakeAsyncClient.payload) - - -class FakeConn: - def __init__(self): - self.load_function_plugin = True - self.config = { - "plugins": { - "home_assistant": { - "base_url": "http://homeassistant.local:8123", - "api_key": "test-token", - } - } - } - - -@pytest.fixture -def fake_http(monkeypatch): - monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient) - return FakeAsyncClient - - -async def _get_state(fake_http, attributes, state="on"): - fake_http.payload = {"state": state, "attributes": attributes} - return await hass_module.handle_hass_get_state(FakeConn(), "light.desk_lamp") - - -@pytest.mark.parametrize("raw, shown", [(153, "60%"), (255, "100%"), (128, "50%"), (1, "1%"), (0, "0%")]) -async def test_brightness_reported_as_percent(fake_http, raw, shown): - text = await _get_state(fake_http, {"brightness": raw, "color_temp_kelvin": 4000}) - assert f"亮度是:{shown} " in text - assert text.startswith("设备状态:on ") and "色温是:4000 " in text - - -async def test_no_brightness_line_when_off_or_missing(fake_http): - # 灯关着时 HA 给 brightness: null - assert await _get_state(fake_http, {"brightness": None}, state="off") == "设备状态:off " - assert "亮度" not in await _get_state(fake_http, {"friendly_name": "台灯"}) From 579538478bebfec3c2f8143c15364217196b3396 Mon Sep 17 00:00:00 2001 From: Allen Date: Sat, 7 Nov 2026 22:33:44 +0800 Subject: [PATCH 11/16] =?UTF-8?q?fix(util):=20check=5Fmodel=5Fkey=20?= =?UTF-8?q?=E9=81=87=E5=88=B0=E7=A9=BA=20api=5Fkey=20=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=8A=9B=20TypeError?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象: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) --- main/xiaozhi-server/core/utils/util.py | 8 ++++ .../tests/core/utils/test_check_model_key.py | 38 +++++++++++++++++++ .../tests/plugins_func/test_hass_init.py | 19 +++++++++- 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 main/xiaozhi-server/tests/core/utils/test_check_model_key.py diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index 4db4f3842..c3a201c60 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -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 diff --git a/main/xiaozhi-server/tests/core/utils/test_check_model_key.py b/main/xiaozhi-server/tests/core/utils/test_check_model_key.py new file mode 100644 index 000000000..57e60a4c4 --- /dev/null +++ b/main/xiaozhi-server/tests/core/utils/test_check_model_key.py @@ -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 diff --git a/main/xiaozhi-server/tests/plugins_func/test_hass_init.py b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py index 4e2ee69e9..ee775439f 100644 --- a/main/xiaozhi-server/tests/plugins_func/test_hass_init.py +++ b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py @@ -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 From e41bc98a258d718161687dde1335ee9852b4b182 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Fri, 13 Nov 2026 10:10:20 +0800 Subject: [PATCH 12/16] =?UTF-8?q?fix(tts):=20=E6=B5=81=E5=BC=8F=20TTS=20?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=BB=B6=E8=BF=9F=E5=88=B0=E9=A6=96=E4=B8=AA?= =?UTF-8?q?=E6=9C=89=E6=95=88=E6=96=87=E6=9C=AC=E5=BC=80=E5=90=AF=EF=BC=8C?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=85=A2=20LLM=20=E5=9C=BA=E6=99=AF=E5=90=88?= =?UTF-8?q?=E6=88=90=E7=BB=93=E6=9E=9C=E4=B8=BA=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/providers/tts/alibl_stream.py | 73 +++++++++++------ .../core/providers/tts/aliyun_stream.py | 78 ++++++++++++------ .../xiaozhi-server/core/providers/tts/base.py | 3 + .../providers/tts/huoshan_double_stream.py | 79 ++++++++++++------- .../core/providers/tts/xunfei_stream.py | 56 +++++++------ 5 files changed, 181 insertions(+), 108 deletions(-) diff --git a/main/xiaozhi-server/core/providers/tts/alibl_stream.py b/main/xiaozhi-server/core/providers/tts/alibl_stream.py index 6813ea001..1a750bde1 100644 --- a/main/xiaozhi-server/core/providers/tts/alibl_stream.py +++ b/main/xiaozhi-server/core/providers/tts/alibl_stream.py @@ -74,7 +74,11 @@ class TTSProvider(TTSProviderBase): """确保WebSocket连接可用,支持60秒内连接复用""" try: current_time = time.time() - if self.ws and current_time - self.last_active_time < 60: + if ( + self.ws + and self.ws.close_code is None + and current_time - self.last_active_time < 60 + ): # 一分钟内才可以复用链接进行连续对话 logger.bind(tag=TAG).debug(f"使用已有链接...") return self.ws @@ -110,10 +114,11 @@ class TTSProvider(TTSProviderBase): if self.conn.client_abort: try: logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") - asyncio.run_coroutine_threadsafe( - self.finish_session(self.conn.sentence_id), - loop=self.conn.loop, - ) + if self.activate_session: + asyncio.run_coroutine_threadsafe( + self.finish_session(self.conn.sentence_id), + loop=self.conn.loop, + ) continue except Exception as e: logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}") @@ -132,21 +137,27 @@ class TTSProvider(TTSProviderBase): self.reset_stream_state() # 初始化会话 try: - if not getattr(self.conn, "sentence_id", None): + if not getattr(self.conn, "sentence_id", None): self.conn.sentence_id = uuid.uuid4().hex logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}") - logger.bind(tag=TAG).debug("开始启动TTS会话...") + # 只建连,会话等文本到达再开启 + logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...") + if self.activate_session: + future = asyncio.run_coroutine_threadsafe( + self.close(), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) future = asyncio.run_coroutine_threadsafe( - self.start_session(self.conn.sentence_id), + self._ensure_connection(), loop=self.conn.loop, ) future.result(timeout=self.tts_timeout) self.before_stop_play_files.clear() - logger.bind(tag=TAG).debug("TTS会话启动成功") + logger.bind(tag=TAG).debug("TTS连接准备完成") except Exception as e: - logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") - continue + logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}") elif ContentType.TEXT == message.content_type: if message.content_detail: @@ -174,6 +185,17 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.LAST: try: logger.bind(tag=TAG).debug("开始结束TTS会话...") + # 句尾替换词滑窗残留补发 + if self._pending_prefix: + future = asyncio.run_coroutine_threadsafe( + self.text_to_speak(self._pending_prefix, None), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) + if not self.activate_session: + # 本轮无文本,未开启会话,直接收尾 + self._process_before_stop_play_files() + continue future = asyncio.run_coroutine_threadsafe( self.finish_session(self.conn.sentence_id), loop=self.conn.loop, @@ -194,20 +216,23 @@ class TTSProvider(TTSProviderBase): async def text_to_speak(self, text, _): """发送文本到TTS服务进行合成""" try: - if self.ws is None: - logger.bind(tag=TAG).warning("WebSocket连接不存在,终止发送文本") - return - # 过滤Markdown filtered_text = MarkdownCleaner.clean_markdown(text) if filtered_text: # 使用滑动窗口匹配处理跨分片的替换词 confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text) + confirmed_texts = [txt for txt in confirmed_texts if txt] + if not confirmed_texts: + return + + # 有文本时才开启会话 + if not self.activate_session: + await self.start_session(self.conn.sentence_id) # 发送每个确定的文本片段 for txt in confirmed_texts: - if txt and self.ws: + if self.ws: continue_task_message = { "header": { "action": "continue-task", @@ -237,9 +262,6 @@ class TTSProvider(TTSProviderBase): if self.activate_session: await self.close() - # 设置会话激活标志 - self.activate_session = True - # 确保连接可用 await self._ensure_connection() @@ -248,6 +270,9 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug("启动监听任务...") self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) + # 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志 + self.activate_session = True + # 发送run-task消息启动会话 run_task_message = { "header": { @@ -350,9 +375,6 @@ class TTSProvider(TTSProviderBase): # 只处理当前活跃会话的响应 if task_id and self.conn.sentence_id != task_id: - if event in ["task-finished", "task-failed"]: - logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~") - self.activate_session = False continue if event == "task-started": @@ -376,6 +398,7 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).error( f"TTS任务失败: {error_code} - {error_message}" ) + self.activate_session = False break except json.JSONDecodeError: logger.bind(tag=TAG).warning("收到无效的JSON消息") @@ -392,16 +415,14 @@ class TTSProvider(TTSProviderBase): ) break - # 连接异常时关闭WebSocket + # 监听任务退出时关闭连接并清理引用 + finally: if self.ws: try: await self.ws.close() except: pass self.ws = None - # 监听任务退出时清理引用 - finally: - self.activate_session = False self._monitor_task = None def audio_to_opus_data_stream( diff --git a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py index 37c6077b7..427aa2ac2 100644 --- a/main/xiaozhi-server/core/providers/tts/aliyun_stream.py +++ b/main/xiaozhi-server/core/providers/tts/aliyun_stream.py @@ -186,7 +186,11 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).warning("Token已过期,正在自动刷新...") self._refresh_token() current_time = time.time() - if self.ws and current_time - self.last_active_time < 10: + if ( + self.ws + and self.ws.close_code is None + and current_time - self.last_active_time < 10 + ): # 10秒内才可以复用链接进行连续对话 self.task_id = uuid.uuid4().hex logger.bind(tag=TAG).debug(f"使用已有链接..., task_id: {self.task_id}") @@ -220,12 +224,17 @@ class TTSProvider(TTSProviderBase): message = self.tts_text_queue.get(timeout=1) if self.conn.client_abort: - logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") - asyncio.run_coroutine_threadsafe( - self.finish_session(self.conn.sentence_id), - loop=self.conn.loop, - ) - continue + try: + logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") + if self.activate_session: + asyncio.run_coroutine_threadsafe( + self.finish_session(self.task_id), + loop=self.conn.loop, + ) + continue + except Exception as e: + logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}") + continue # 过滤旧消息:检查sentence_id是否匹配 if message.sentence_id != self.conn.sentence_id: @@ -240,18 +249,24 @@ class TTSProvider(TTSProviderBase): self.reset_stream_state() # 初始化参数 try: - logger.bind(tag=TAG).debug("开始启动TTS会话...") + # 只建连,会话等文本到达再开启 + logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...") + if self.activate_session: + future = asyncio.run_coroutine_threadsafe( + self.close(), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) future = asyncio.run_coroutine_threadsafe( - self.start_session(self.task_id), + self._ensure_connection(), loop=self.conn.loop, ) future.result(timeout=self.tts_timeout) self.before_stop_play_files.clear() - logger.bind(tag=TAG).debug("TTS会话启动成功") + logger.bind(tag=TAG).debug("TTS连接准备完成") except Exception as e: - logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") - continue + logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}") elif ContentType.TEXT == message.content_type: if message.content_detail: @@ -278,6 +293,17 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.LAST: try: logger.bind(tag=TAG).debug("开始结束TTS会话...") + # 句尾替换词滑窗残留补发 + if self._pending_prefix: + future = asyncio.run_coroutine_threadsafe( + self.text_to_speak(self._pending_prefix, None), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) + if not self.activate_session: + # 本轮无文本,未开启会话,直接收尾 + self._process_before_stop_play_files() + continue future = asyncio.run_coroutine_threadsafe( self.finish_session(self.task_id), loop=self.conn.loop, @@ -296,18 +322,22 @@ class TTSProvider(TTSProviderBase): async def text_to_speak(self, text, _): try: - if self.ws is None: - logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本") - return filtered_text = MarkdownCleaner.clean_markdown(text) if filtered_text: # 使用滑动窗口匹配处理跨分片的替换词 confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text) + confirmed_texts = [txt for txt in confirmed_texts if txt] + if not confirmed_texts: + return + + # 有文本时才开启会话 + if not self.activate_session: + await self.start_session(self.task_id) # 发送每个确定的文本片段 for txt in confirmed_texts: - if txt and self.ws: + if self.ws: run_request = { "header": { "message_id": uuid.uuid4().hex, @@ -339,9 +369,6 @@ class TTSProvider(TTSProviderBase): if self.activate_session: await self.close() - # 设置会话激活标志 - self.activate_session = True - # 建立新连接 await self._ensure_connection() @@ -350,6 +377,9 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug("启动监听任务...") self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) + # 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志 + self.activate_session = True + start_request = { "header": { "message_id": uuid.uuid4().hex, @@ -431,9 +461,6 @@ class TTSProvider(TTSProviderBase): # 只处理当前活跃会话的响应 if task_id and self.task_id != task_id: - if event_name in ["SynthesisCompleted", "TaskFailed"]: - logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~") - self.activate_session = False continue if event_name == "SynthesisStarted": @@ -469,16 +496,15 @@ class TTSProvider(TTSProviderBase): f"处理TTS响应时出错: {e}\n{traceback.format_exc()}" ) break - # 连接异常时关闭WebSocket + + # 监听任务退出时关闭连接并清理引用 + finally: if self.ws: try: await self.ws.close() except: pass self.ws = None - # 监听任务退出时清理引用 - finally: - self.activate_session = False self._monitor_task = None def audio_to_opus_data_stream( diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index 34b20a626..061a13411 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -704,3 +704,6 @@ class TTSProviderBase(ABC): def reset_stream_state(self): """重置流式处理状态,用于会话开始时清理残留状态""" self._pending_prefix = "" + # 清理编码器中未满一帧的PCM残留 + if getattr(self, "opus_encoder", None): + self.opus_encoder.reset_state() diff --git a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py index 0e5c7d2e1..540925491 100644 --- a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py +++ b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py @@ -220,7 +220,7 @@ class TTSProvider(TTSProviderBase): async def _ensure_connection(self): """建立新的WebSocket连接,并启动监听任务(仅第一次)""" try: - if self.ws: + if self.ws and self.ws.close_code is None: if self.enable_ws_reuse: logger.bind(tag=TAG).debug(f"使用已有链接...") return self.ws @@ -281,12 +281,12 @@ class TTSProvider(TTSProviderBase): if self.conn.client_abort: try: logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程") - if self.enable_ws_reuse: + if self.activate_session: asyncio.run_coroutine_threadsafe( self.cancel_session(self.conn.sentence_id), loop=self.conn.loop, ) - else: + if not self.enable_ws_reuse: asyncio.run_coroutine_threadsafe( self.finish_connection(), loop=self.conn.loop, @@ -307,26 +307,29 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.FIRST: # 重置流式处理状态 self.reset_stream_state() - # 重置 opus 流式编码器跨轮残留 - if hasattr(self, "opus_encoder") and self.opus_encoder: - self.opus_encoder.reset_state() # 初始化参数 try: - if not getattr(self.conn, "sentence_id", None): + if not getattr(self.conn, "sentence_id", None): self.conn.sentence_id = uuid.uuid4().hex logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}") - logger.bind(tag=TAG).debug("开始启动TTS会话...") + # 只建连,会话等文本到达再开启 + logger.bind(tag=TAG).debug("准备TTS连接(暂不开启会话)...") + if self.activate_session: + future = asyncio.run_coroutine_threadsafe( + self.close(), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) future = asyncio.run_coroutine_threadsafe( - self.start_session(self.conn.sentence_id), + self._ensure_connection(), loop=self.conn.loop, ) future.result(timeout=self.tts_timeout) self.before_stop_play_files.clear() - logger.bind(tag=TAG).debug("TTS会话启动成功") + logger.bind(tag=TAG).debug("TTS连接准备完成") except Exception as e: - logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") - continue + logger.bind(tag=TAG).error(f"准备TTS连接失败: {str(e)}") elif ContentType.TEXT == message.content_type: if message.content_detail: @@ -353,11 +356,29 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.LAST: try: logger.bind(tag=TAG).debug("开始结束TTS会话...") - future = asyncio.run_coroutine_threadsafe( - self.finish_session(self.conn.sentence_id), - loop=self.conn.loop, - ) - future.result(timeout=self.tts_timeout) + # 句尾替换词滑窗残留补发 + if self._pending_prefix: + future = asyncio.run_coroutine_threadsafe( + self.text_to_speak(self._pending_prefix, None), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) + if self.activate_session: + # 结束会话;LAST 与连接释放由监听任务在 SessionFinished 后处理 + future = asyncio.run_coroutine_threadsafe( + self.finish_session(self.conn.sentence_id), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) + else: + # 未开启会话,没有 SessionFinished 事件,需自行收尾 + self._process_before_stop_play_files() + if not self.enable_ws_reuse: + future = asyncio.run_coroutine_threadsafe( + self.finish_connection(), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) except Exception as e: logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}") continue @@ -373,21 +394,23 @@ class TTSProvider(TTSProviderBase): async def text_to_speak(self, text, _): """发送文本到TTS服务""" try: - # 建立新连接 - if self.ws is None: - logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本") - return - # 过滤Markdown filtered_text = MarkdownCleaner.clean_markdown(text) if filtered_text: # 使用滑动窗口匹配处理跨分片的替换词 confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text) + confirmed_texts = [txt for txt in confirmed_texts if txt] + if not confirmed_texts: + return + + # 有文本时才开启会话 + if not self.activate_session: + await self.start_session(self.conn.sentence_id) # 发送每个确定的文本片段 for txt in confirmed_texts: - if txt and self.ws: + if self.ws: await self.send_text(self.voice, txt, self.conn.sentence_id) return @@ -407,12 +430,11 @@ class TTSProvider(TTSProviderBase): # 上个会话处于激活状态时关闭上个连接新建链接 if self.activate_session: await self.close() - - # 设置会话激活标志 - self.activate_session = True - + # 确保连接建立 await self._ensure_connection() + # 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志 + self.activate_session = True header = Header( message_type=FULL_CLIENT_REQUEST, @@ -437,9 +459,6 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}") try: if self.ws: - # 句尾替换词滑动窗口残留先发出去 - if self._pending_prefix: - await self.text_to_speak(self._pending_prefix, None) header = Header( message_type=FULL_CLIENT_REQUEST, message_type_specific_flags=MsgTypeFlagWithEvent, diff --git a/main/xiaozhi-server/core/providers/tts/xunfei_stream.py b/main/xiaozhi-server/core/providers/tts/xunfei_stream.py index 8edc414b4..196fa5b8e 100644 --- a/main/xiaozhi-server/core/providers/tts/xunfei_stream.py +++ b/main/xiaozhi-server/core/providers/tts/xunfei_stream.py @@ -127,7 +127,7 @@ class TTSProvider(TTSProviderBase): raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret") async def _ensure_connection(self): - """确保WebSocket连接可用""" + """建立新的WebSocket连接""" try: logger.bind(tag=TAG).debug("开始建立新连接...") @@ -176,24 +176,14 @@ class TTSProvider(TTSProviderBase): self.text_seq += 1 if message.sentence_type == SentenceType.FIRST: - # 初始化参数 + # 初始化参数,连接在文本到达时建立 try: if not getattr(self.conn, "sentence_id", None): self.conn.sentence_id = uuid.uuid4().hex logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}") - - logger.bind(tag=TAG).debug("开始启动TTS会话...") - future = asyncio.run_coroutine_threadsafe( - self.start_session(self.conn.sentence_id), - loop=self.conn.loop, - ) - future.result(timeout=self.tts_timeout) self.before_stop_play_files.clear() - logger.bind(tag=TAG).debug("TTS会话启动成功") - except Exception as e: - logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}") - continue + logger.bind(tag=TAG).error(f"准备TTS状态失败: {str(e)}") # 处理文本内容 if ContentType.TEXT == message.content_type: @@ -224,6 +214,17 @@ class TTSProvider(TTSProviderBase): if message.sentence_type == SentenceType.LAST: try: logger.bind(tag=TAG).debug("开始结束TTS会话...") + # 句尾替换词滑窗残留补发 + if self._pending_prefix: + future = asyncio.run_coroutine_threadsafe( + self.text_to_speak(self._pending_prefix, None), + loop=self.conn.loop, + ) + future.result(timeout=self.tts_timeout) + if not self.activate_session: + # 本轮无文本,未开启会话,直接收尾 + self._process_before_stop_play_files() + continue asyncio.run_coroutine_threadsafe( self.finish_session(self.conn.sentence_id), loop=self.conn.loop, @@ -242,19 +243,22 @@ class TTSProvider(TTSProviderBase): async def text_to_speak(self, text, _): """发送文本到TTS服务进行合成""" try: - if self.ws is None: - logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本") - return - filtered_text = MarkdownCleaner.clean_markdown(text) if filtered_text: # 使用滑动窗口匹配处理跨分片的替换词 confirmed_texts, self._pending_prefix = self._match_stream_text(filtered_text) + confirmed_texts = [txt for txt in confirmed_texts if txt] + if not confirmed_texts: + return + + # 有文本时才开启会话 + if not self.activate_session: + await self.start_session(self.conn.sentence_id) # 发送每个确定的文本片段 for txt in confirmed_texts: - if txt and self.ws: + if self.ws: # 发送文本合成请求 run_request = self._build_base_request(status=1, text=txt) await self.ws.send(json.dumps(run_request)) @@ -277,9 +281,6 @@ class TTSProvider(TTSProviderBase): if self.activate_session: await self.close() - # 设置会话激活标志 - self.activate_session = True - # 建立新连接 await self._ensure_connection() @@ -288,10 +289,15 @@ class TTSProvider(TTSProviderBase): logger.bind(tag=TAG).debug("启动监听任务...") self._monitor_task = asyncio.create_task(self._start_monitor_tts_response()) - # 发送会话启动请求 + # 连接就绪后再标记会话激活,避免旧监听任务退出时重置标志 + self.activate_session = True + + # 启动帧序号从1开始,避免与后续文本帧重复 + self.text_seq = 1 start_request = self._build_base_request(status=0) await self.ws.send(json.dumps(start_request)) + self.text_seq += 1 logger.bind(tag=TAG).debug("会话启动请求已发送") except Exception as e: logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}") @@ -412,16 +418,14 @@ class TTSProvider(TTSProviderBase): ) break - # 链接不可复用 + # 监听任务退出时关闭连接并清理引用 + finally: if self.ws: try: await self.ws.close() except: pass self.ws = None - # 监听任务退出时清理引用 - finally: - self.activate_session = False self._monitor_task = None def to_tts(self, text: str) -> list: From 0d7180d898bb374eb2d32055876143053e29f4a9 Mon Sep 17 00:00:00 2001 From: zhenglieAllen <139029575+zhenglieAllen@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:31:17 +0800 Subject: [PATCH 13/16] =?UTF-8?q?fix(config):=20=E7=BB=99=20mem=5Freport?= =?UTF-8?q?=5Fonly=20=E8=A1=A5=E4=B8=8A=20Memory=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=9D=97=20(#3547)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(config): 给 mem_report_only 补上 Memory 配置块 现象 把 selected_module.Memory 设成 mem_report_only 后,服务在连接初始化阶段 直接崩: KeyError: 'mem_report_only' 原因 core/providers/memory/mem_report_only/ 下有完整的 provider 实现, core/connection.py 的 _initialize_memory 里也显式处理了它 (`if memory_type == "nomem" or memory_type == "mem_report_only"`), 但 config.yaml 的 Memory 段只配了 mem0ai / powermem / nomem / mem_local_short 四项,没有 mem_report_only。 而 core/connection.py 取配置的方式是直接下标: memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]]["type"] 于是只要在 selected_module 里选了 mem_report_only,这个下标就取不到, 连接初始化阶段 KeyError。data/.config.yaml 那边也是整段替换 (self.config["Memory"] = private_config["Memory"]),用户光改 selected_module 而不重复声明一遍 Memory 段,一样会炸。 改法 在 config.yaml 的 Memory 段补上 mem_report_only 配置块(type: mem_report_only),让出厂配置自洽 —— 选了就能直接用,不需要用户自己 再补一段配置。 测试 新增 tests/config/test_provider_registry.py,钉死两条不变量: - selected_module 里选中的 provider 必须在对应配置段里存在(防启动期 KeyError); - 每个 provider 段的每个键,type 字段都必须指向真实存在的实现 (防「配置有、实现没有」); - Memory 这类一一对应的模块,实现里有的 provider 配置里必须有(防本次 这种「实现有、配置没有」)。 修复前 test_every_implemented_provider_is_configured[Memory] 失败, 修复后通过。本地全量:5 failed / 99 passed / 33 skipped / 8 errors, 失败项与改动前完全一致(本地缺 portalocker / pytest-asyncio / edge_tts, CI 由 requirements.txt 提供),无回归。 * docs(readme): 组件列表补齐 mem_report_only 与科大讯飞视觉模型 现象 README 的「本项目支持的平台/组件列表」有两处和实际出厂配置对不上: 1. VLLM 视觉模型表只列了「阿里百炼、智谱ChatGLMVLLM」,但 config.yaml 的 VLLM 段出厂就带了 XunfeiSparkLLM(讯飞星火)这个 provider。 2. Memory 记忆存储表只列了 mem0ai / powermem / mem_local_short / nomem, 没有 mem_report_only —— 而 core/providers/memory/mem_report_only/ 里有 实现,core/connection.py 里也显式处理了它。 原因 这两个表是手工维护的,新增 provider 时没有同步。VLLM 段的讯飞星火尤其 隐蔽:它的 base_url 还被误填成了火山方舟的地址(ark.cn-beijing.volces.com), 看起来像是没在用,于是没人往表里补。 改法 6 份 README(README.md + docs/readme/ 下的 en/de/es/vi/pt_BR)同步更新: - VLLM 视觉模型表的「支持平台」列补上科大讯飞 / iFLYTEK。免费平台列不动 —— 讯飞星火虽有免费额度,但每个模型要单独开通服务后才能用,不属于开箱免费。 - Memory 记忆存储表补上 mem_report_only 一行(使用方式「仅上报」, 备注「只上报聊天记录,不做记忆总结」,取自 provider 自身的 docstring)。 测试 纯文档改动,无代码路径变化。本次一并把 VLLM 表和 Memory 表跟 config.yaml 的实际内容对齐,避免再出现「文档列的组件在配置里选不到」的情况。 --------- Co-authored-by: Allen --- README.md | 3 +- docs/readme/README_de.md | 3 +- docs/readme/README_en.md | 3 +- docs/readme/README_es.md | 3 +- docs/readme/README_pt_BR.md | 3 +- docs/readme/README_vi.md | 3 +- main/xiaozhi-server/config.yaml | 4 + .../tests/config/test_provider_registry.py | 124 ++++++++++++++++++ 8 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 main/xiaozhi-server/tests/config/test_provider_registry.py diff --git a/README.md b/README.md index e459f92ab..6d01ce1c6 100644 --- a/README.md +++ b/README.md @@ -272,7 +272,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/ | 使用方式 | 支持平台 | 免费平台 | |:---:|:---:|:---:| -| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM | 智谱ChatGLMVLLM | +| OpenAI 接口调用 | 阿里百炼、智谱ChatGLMVLLM、科大讯飞 | 智谱ChatGLMVLLM | 实际上,任何支持 OpenAI 接口调用的 VLLM 均可接入使用。 @@ -322,6 +322,7 @@ Websocket接口地址: wss://2662r3426b.vicp.fun/xiaozhi/v1/ | Memory | [powermem](./docs/powermem-integration.md) | 本地总结 | 取决于LLM和DB | OceanBase开源,支持智能检索 | | Memory | mem_local_short | 本地总结 | 免费 | | | Memory | nomem | 无记忆模式 | 免费 | | +| Memory | mem_report_only | 仅上报 | 免费 | 只上报聊天记录,不做记忆总结 | --- diff --git a/docs/readme/README_de.md b/docs/readme/README_de.md index a65a1acbe..f854a04ff 100644 --- a/docs/readme/README_de.md +++ b/docs/readme/README_de.md @@ -270,7 +270,7 @@ Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, inte | Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen | |:---:|:---:|:---:| -| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM | +| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden. @@ -320,6 +320,7 @@ Die Stimmabdruckerkennung erfordert einen separat bereitgestellten [voiceprint-a | Memory | [powermem](../powermem-integration.md) | Lokale Zusammenfassung | Abhängig von LLM und DB | OceanBase Open Source, unterstützt intelligente Abfrage | | Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | | | Memory | nomem | Kein Gedächtnismodus | Kostenlos | | +| Memory | mem_report_only | Nur Meldung | Kostenlos | Meldet nur Chat-Verläufe, keine Gedächtniszusammenfassung | --- diff --git a/docs/readme/README_en.md b/docs/readme/README_en.md index 3e4d2a1a1..dd2d84082 100644 --- a/docs/readme/README_en.md +++ b/docs/readme/README_en.md @@ -270,7 +270,7 @@ In fact, any LLM that supports OpenAI interface calls can be integrated and used | Usage Method | Supported Platforms | Free Platforms | |:---:|:---:|:---:| -| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM | +| OpenAI interface calls | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | In fact, any VLLM that supports OpenAI interface calls can be integrated and used. @@ -320,6 +320,7 @@ Voiceprint recognition requires a separately deployed [voiceprint-api](https://g | Memory | [powermem](../powermem-integration.md) | Local summarization | Depends on LLM and DB | OceanBase open source, supports intelligent retrieval | | Memory | mem_local_short | Local summarization | Free | | | Memory | nomem | No memory mode | Free | | +| Memory | mem_report_only | Report only | Free | Only reports chat records, no memory summarization | --- diff --git a/docs/readme/README_es.md b/docs/readme/README_es.md index 3fd99a30a..1cded9cbf 100644 --- a/docs/readme/README_es.md +++ b/docs/readme/README_es.md @@ -270,7 +270,7 @@ En la práctica, se puede integrar cualquier LLM que admita llamadas por la inte | Forma de uso | Plataformas compatibles | Plataformas gratuitas | |:---:|:---:|:---:| -| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM | +| Llamadas por la interfaz OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | En la práctica, se puede integrar cualquier VLLM que admita llamadas por la interfaz OpenAI. @@ -320,6 +320,7 @@ El reconocimiento de huella de voz requiere desplegar por separado el servicio [ | Memory | [powermem](../powermem-integration.md) | Resumen local | Depende del LLM y de la base de datos | OceanBase de código abierto; admite búsqueda inteligente | | Memory | mem_local_short | Resumen local | Gratuito | | | Memory | nomem | Modo sin memoria | Gratuito | | +| Memory | mem_report_only | Solo informe | Gratuito | Solo informa el historial de chat, sin resumen de memoria | --- diff --git a/docs/readme/README_pt_BR.md b/docs/readme/README_pt_BR.md index ce18fe7a9..6d423497d 100644 --- a/docs/readme/README_pt_BR.md +++ b/docs/readme/README_pt_BR.md @@ -270,7 +270,7 @@ Na verdade, qualquer LLM que suporte chamadas via interface OpenAI pode ser inte | Método de Uso | Plataformas Suportadas | Plataformas Gratuitas | |:---:|:---:|:---:| -| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM | +| Chamadas via interface OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | Na verdade, qualquer VLLM que suporte chamadas via interface OpenAI pode ser integrado e utilizado. @@ -320,6 +320,7 @@ O reconhecimento de impressão vocal exige um serviço [voiceprint-api](https:// | Memória | [powermem](../powermem-integration.md) | Resumo local | Depende do LLM e BD | OceanBase de código aberto, suporta busca inteligente | | Memória | mem_local_short | Resumo local | Gratuito | | | Memória | nomem | Modo sem memória | Gratuito | | +| Memória | mem_report_only | Apenas relatório | Gratuito | Apenas reporta o histórico de chat, sem resumo de memória | --- diff --git a/docs/readme/README_vi.md b/docs/readme/README_vi.md index 9941c4cc0..d872a8ef9 100644 --- a/docs/readme/README_vi.md +++ b/docs/readme/README_vi.md @@ -271,7 +271,7 @@ Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện OpenAI đề | Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí | |:---:|:---:|:---:| -| Gọi giao diện OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM | +| Gọi giao diện OpenAI | Alibaba Bailian, Zhipu ChatGLMVLLM, iFLYTEK | Zhipu ChatGLMVLLM | Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện OpenAI đều có thể truy cập sử dụng. @@ -321,6 +321,7 @@ Nhận dạng vân giọng cần dịch vụ [voiceprint-api](https://github.com | Memory | [powermem](../powermem-integration.md) | Tóm tắt cục bộ | Phụ thuộc vào LLM và DB | OceanBase mã nguồn mở, hỗ trợ tìm kiếm thông minh | | Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | | | Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | | +| Memory | mem_report_only | Chỉ báo cáo | Miễn phí | Chỉ báo cáo lịch sử trò chuyện, không tóm tắt bộ nhớ | --- diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 66a97e81a..e2cd0dd88 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -348,6 +348,10 @@ Memory: nomem: # 不想使用记忆功能,可以使用nomem type: nomem + mem_report_only: + # 只把聊天记录上报到智控台,不做记忆总结,也不保存记忆 + # 适合只想留存对话记录、又不需要记忆功能的场景 + type: mem_report_only mem_local_short: # 本地记忆功能,通过selected_module的llm总结,数据保存在本地服务器,不会上传到外部服务器 type: mem_local_short diff --git a/main/xiaozhi-server/tests/config/test_provider_registry.py b/main/xiaozhi-server/tests/config/test_provider_registry.py new file mode 100644 index 000000000..ad58e9e50 --- /dev/null +++ b/main/xiaozhi-server/tests/config/test_provider_registry.py @@ -0,0 +1,124 @@ +"""出厂配置与 provider 实现之间的一致性护栏。 + +config.yaml 是出厂默认配置,每个 provider 段(Memory/LLM/TTS/...)下的每个键 +都对应一个可选的 provider 实现。两边一旦脱节,就会出现两种坏情况: + +1. 配置里有、实现里没有 —— 用户选了会在 create_instance 阶段报 + "不支持的服务类型"。 +2. 实现里有、配置里没有 —— 用户想选它,却要么找不到入口,要么在连接初始化 + 阶段直接 KeyError(core/connection.py 里是 + ``self.config["Memory"][selected_module["Memory"]]["type"]``)。 + +Memory 段历史上踩过第 2 种:``mem_report_only`` 的实现在 +core/providers/memory/mem_report_only/ 里,core/connection.py 也显式处理了它, +但 config.yaml 的 Memory 段没有对应配置块 —— 只要在 selected_module 里选了它, +连接初始化就会 KeyError,服务起不来。 + +这里把上面两条不变量钉死。 +""" +from __future__ import annotations + +import os + +import pytest + +from config.config_loader import get_project_dir, read_config + +# 各模块的 provider 发现方式: +# "dir" —— 目录式:core/providers///.py +# "file" —— 文件式:core/providers//.py +MODULES = [ + ("Intent", "intent", "dir"), + ("Memory", "memory", "dir"), + ("LLM", "llm", "dir"), + ("ASR", "asr", "file"), + ("TTS", "tts", "file"), + ("VAD", "vad", "file"), + ("VLLM", "vllm", "file"), +] + +# 目录式模块里,一个实现目录通常只服务一个 provider(目录名 == 配置键 == +# type)。LLM 是例外:core/providers/llm/openai/ 被 ChatGLMLLM、DoubaoLLM +# 等多个配置键共用,所以「实现 -> 配置」的反向检查只对一一对应的模块做。 +ONE_TO_ONE_MODULES = ("Memory",) + + +@pytest.fixture(scope="module") +def default_config(): + """出厂的 config.yaml(未经 data/.config.yaml 覆盖)。""" + return read_config(get_project_dir() + "config.yaml") + + +def _impl_path(mod: str, style: str, type_name: str) -> str: + """provider 实现的绝对路径。""" + root = get_project_dir() + if style == "dir": + return os.path.join(root, "core", "providers", mod, type_name, f"{type_name}.py") + return os.path.join(root, "core", "providers", mod, f"{type_name}.py") + + +def test_selected_module_provider_is_configured(default_config): + """selected_module 里选中的 provider 必须在对应配置段里存在。 + + core/connection.py 初始化各模块时都是直接下标取配置 + (self.config["Memory"][selected_module["Memory"]]["type"]), + 配置段里缺这个键就是启动期 KeyError。 + """ + selected = default_config.get("selected_module") or {} + for module in ("VAD", "ASR", "LLM", "VLLM", "TTS", "Memory", "Intent"): + name = selected.get(module) + assert name, f"selected_module.{module} 没有设置" + block = (default_config.get(module) or {}).get(name) + assert block is not None, ( + f"selected_module.{module} = {name}," + f"但 config.yaml 里没有 {module}.{name} 配置块" + ) + + +@pytest.mark.parametrize( + "section,mod,style", MODULES, ids=[section for section, _, _ in MODULES] +) +def test_every_configured_provider_has_implementation(default_config, section, mod, style): + """配置里的每个 provider,type 字段都必须指向真实存在的实现。 + + 覆盖「配置有、实现没有」:用户选了会在 create_instance 阶段报 + "不支持的服务类型"。 + """ + for name, block in (default_config.get(section) or {}).items(): + if not isinstance(block, dict): + continue + type_name = block.get("type", name) + path = _impl_path(mod, style, type_name) + assert os.path.exists(path), ( + f"{section}.{name} 的 type={type_name} 找不到实现文件 {path}" + ) + + +@pytest.mark.parametrize("section", ONE_TO_ONE_MODULES) +def test_every_implemented_provider_is_configured(default_config, section): + """实现里有的 provider,配置里必须也有一份。 + + 覆盖「实现有、配置没有」:这类 provider 用户根本没法从出厂配置里选到, + 一旦有人手动选了就会在连接初始化阶段 KeyError。 + + mem_report_only 就是这么漏掉的。 + """ + mod = section.lower() + providers_dir = os.path.join(get_project_dir(), "core", "providers", mod) + impls = sorted( + name + for name in os.listdir(providers_dir) + if os.path.isfile(os.path.join(providers_dir, name, f"{name}.py")) + ) + assert impls, f"core/providers/{mod} 下没找到任何 provider 实现" + + for name in impls: + block = (default_config.get(section) or {}).get(name) + assert block is not None, ( + f"core/providers/{mod}/{name} 有实现," + f"但 config.yaml 的 {section} 段没有 {name} 配置块" + ) + assert block.get("type", name) == name, ( + f"config.yaml 的 {section}.{name}.type 应该是 {name}," + f"实际是 {block.get('type')}" + ) From c74a6aaa689f69cf74d8caba43ec1f7246555d6f Mon Sep 17 00:00:00 2001 From: zhenglieAllen <139029575+zhenglieAllen@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:51:00 +0800 Subject: [PATCH 14/16] =?UTF-8?q?fix(config):=20=E4=BF=AE=E6=AD=A3=20Xunfe?= =?UTF-8?q?iSparkLLM=20=E7=9A=84=20base=5Furl=20=E8=AF=AF=E5=A1=AB?= =?UTF-8?q?=E6=88=90=E7=81=AB=E5=B1=B1=E6=96=B9=E8=88=9F=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=20(#3546)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 现象:把 selected_module.VLLM 设为 XunfeiSparkLLM 后,视觉理解请求全部失败 (鉴权失败或 404),而且讯飞的 api_key 会被发到火山引擎。 原因:config.yaml 里 VLLM.XunfeiSparkLLM.base_url 填的是 https://ark.cn-beijing.volces.com/api/v3 —— 那是上面 LLM.DoubaoLLM 的火山 方舟地址,疑似复制粘贴时带串了。core/providers/vllm/openai.py 取端点时 base_url 优先于 url,所以这个值会直接生效;配套的 model_name: lite 是讯飞 的模型名,在火山方舟上并不存在。 改法:base_url 改成讯飞星火官方 OpenAI 兼容端点 https://spark-api-open.xf-yun.com/v1,并在注释里写明端点与模型名的出处。 测试:新增 tests/config/test_provider_endpoints.py,用一张「provider -> 端点主机名」对照表把这类串台钉死。修复前该用例失败,修复后通过。 Co-authored-by: Allen --- main/xiaozhi-server/config.yaml | 6 +- .../tests/config/test_provider_endpoints.py | 81 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 main/xiaozhi-server/tests/config/test_provider_endpoints.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index e2cd0dd88..91328a927 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -769,7 +769,11 @@ VLLM: # 开通应用地址:https://console.xfyun.cn/app/myapp # 有免费额度,但也要开通服务,才能获取api_key # 每一个模型都需要单独开通,每一个模型的 api_key 都不同,例如 Lite 模型在 https://console.xfyun.cn/services/cbm 开通 - base_url: https://ark.cn-beijing.volces.com/api/v3 + # 讯飞星火的 OpenAI 兼容端点,可用模型名(lite / 4.0Ultra 等)见 + # https://www.xfyun.cn/doc/spark/HTTP调用文档.html + # 注意 base_url 必须指向讯飞自己的域名。这里曾误填成火山方舟的 + # ark.cn-beijing.volces.com,会把讯飞的 api_key 发给火山引擎。 + base_url: https://spark-api-open.xf-yun.com/v1 model_name: lite api_key: 你的api_key TTS: diff --git a/main/xiaozhi-server/tests/config/test_provider_endpoints.py b/main/xiaozhi-server/tests/config/test_provider_endpoints.py new file mode 100644 index 000000000..98276e0e5 --- /dev/null +++ b/main/xiaozhi-server/tests/config/test_provider_endpoints.py @@ -0,0 +1,81 @@ +"""供应器默认端点自检:防止不同 provider 的 base_url 被复制粘贴串台。 + +背景:``config.yaml`` 里每个 provider 的 ``base_url`` / ``url`` 都是照抄对应 +厂商文档填的,很容易从相邻的 provider 直接复制粘贴。真实案例:``VLLM`` +段的 ``XunfeiSparkLLM`` 抄了上面 ``LLM.DoubaoLLM`` 的火山方舟地址 +(ark.cn-beijing.volces.com),选它做视觉模型时会把讯飞的 api_key 发给 +火山引擎,而 ``model_name: lite`` 在那个端点上并不存在。 + +这里用一张「配置块 -> 端点主机名」的对照表把这类串台钉死。新增 provider +时顺手往表里加一行即可。 + +注意:本用例读的是仓库里**出厂的** ``config.yaml``,不是用户 +``data/.config.yaml`` 合并后的结果 —— 要守的就是这份出厂默认值。 +""" +from __future__ import annotations + +from urllib.parse import urlparse + +import pytest + +from config.config_loader import get_project_dir, read_config + + +# (模块段, provider 名, 端点主机名里必须出现的片段) +PROVIDER_ENDPOINT_HOSTS = [ + ("LLM", "AliLLM", "dashscope.aliyuncs.com"), + ("LLM", "AliAppLLM", "dashscope.aliyuncs.com"), + ("LLM", "ChatGLMLLM", "bigmodel.cn"), + ("LLM", "DeepSeekLLM", "deepseek.com"), + ("LLM", "DifyLLM", "dify.ai"), + ("LLM", "DoubaoLLM", "volces.com"), + ("LLM", "VolcesAiGatewayLLM", "volces.com"), + ("VLLM", "ChatGLMVLLM", "bigmodel.cn"), + ("VLLM", "QwenVLVLLM", "dashscope.aliyuncs.com"), + ("VLLM", "XunfeiSparkLLM", "xf-yun.com"), + ("ASR", "OpenaiASR", "api.openai.com"), + ("ASR", "GroqASR", "api.groq.com"), + ("ASR", "Qwen3ASRFlash", "dashscope.aliyuncs.com"), + ("TTS", "OpenAITTS", "api.openai.com"), + ("TTS", "DoubaoTTS", "bytedance.com"), + ("TTS", "TTS302AI", "302ai.cn"), + ("TTS", "VolcesAiGatewayTTS", "volces.com"), +] + + +@pytest.fixture(scope="module") +def default_config(): + """仓库里出厂的默认配置(未经用户 data/.config.yaml 覆盖)。""" + return read_config(get_project_dir() + "config.yaml") + + +def _endpoint_of(block: dict) -> str: + """取 provider 配置块里生效的端点。 + + 顺序与运行时一致:``core/providers/vllm/openai.py`` 和 + ``core/providers/llm/openai/openai.py`` 都是 ``base_url`` 优先、 + ``url`` 兜底;部分 TTS 用 ``api_url``。 + """ + return block.get("base_url") or block.get("url") or block.get("api_url") or "" + + +@pytest.mark.parametrize( + "module,provider,expected_host", + PROVIDER_ENDPOINT_HOSTS, + ids=[f"{m}.{p}" for m, p, _ in PROVIDER_ENDPOINT_HOSTS], +) +def test_provider_endpoint_matches_platform( + default_config, module, provider, expected_host +): + """provider 的端点必须落在它自己那家厂商的域名下。""" + block = default_config.get(module, {}).get(provider) + assert block is not None, f"config.yaml 里找不到 {module}.{provider} 配置块" + + endpoint = _endpoint_of(block) + assert endpoint, f"{module}.{provider} 没有配置 base_url / url / api_url" + + host = urlparse(endpoint).netloc + assert expected_host in host, ( + f"{module}.{provider} 的端点 {endpoint!r} 解析出的主机是 {host!r}," + f"与平台不符(期望包含 {expected_host!r})—— 疑似从别的 provider 复制粘贴时带串了" + ) From 63e2bcec8a34e71bac1fc06bf7752ce2ff494734 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Fri, 13 Nov 2026 17:42:16 +0800 Subject: [PATCH 15/16] =?UTF-8?q?revert(config):=20=E7=A7=BB=E9=99=A4=20me?= =?UTF-8?q?m=5Freport=5Fonly=20=E5=87=BA=E5=8E=82=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=9D=97=EF=BC=8C=E7=BB=B4=E6=8C=81=E5=8D=95=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=20fail-fast=20=E5=A5=91=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 回退 #3547 的核心改动。 mem_report_only 仅在智控台模式下有意义:选项及配置块由 manager-api数据库下发,不依赖本地 config.yaml。 --- main/xiaozhi-server/config.yaml | 4 - .../tests/config/test_provider_registry.py | 124 ------------------ 2 files changed, 128 deletions(-) delete mode 100644 main/xiaozhi-server/tests/config/test_provider_registry.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 91328a927..ad9be91c1 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -348,10 +348,6 @@ Memory: nomem: # 不想使用记忆功能,可以使用nomem type: nomem - mem_report_only: - # 只把聊天记录上报到智控台,不做记忆总结,也不保存记忆 - # 适合只想留存对话记录、又不需要记忆功能的场景 - type: mem_report_only mem_local_short: # 本地记忆功能,通过selected_module的llm总结,数据保存在本地服务器,不会上传到外部服务器 type: mem_local_short diff --git a/main/xiaozhi-server/tests/config/test_provider_registry.py b/main/xiaozhi-server/tests/config/test_provider_registry.py deleted file mode 100644 index ad58e9e50..000000000 --- a/main/xiaozhi-server/tests/config/test_provider_registry.py +++ /dev/null @@ -1,124 +0,0 @@ -"""出厂配置与 provider 实现之间的一致性护栏。 - -config.yaml 是出厂默认配置,每个 provider 段(Memory/LLM/TTS/...)下的每个键 -都对应一个可选的 provider 实现。两边一旦脱节,就会出现两种坏情况: - -1. 配置里有、实现里没有 —— 用户选了会在 create_instance 阶段报 - "不支持的服务类型"。 -2. 实现里有、配置里没有 —— 用户想选它,却要么找不到入口,要么在连接初始化 - 阶段直接 KeyError(core/connection.py 里是 - ``self.config["Memory"][selected_module["Memory"]]["type"]``)。 - -Memory 段历史上踩过第 2 种:``mem_report_only`` 的实现在 -core/providers/memory/mem_report_only/ 里,core/connection.py 也显式处理了它, -但 config.yaml 的 Memory 段没有对应配置块 —— 只要在 selected_module 里选了它, -连接初始化就会 KeyError,服务起不来。 - -这里把上面两条不变量钉死。 -""" -from __future__ import annotations - -import os - -import pytest - -from config.config_loader import get_project_dir, read_config - -# 各模块的 provider 发现方式: -# "dir" —— 目录式:core/providers///.py -# "file" —— 文件式:core/providers//.py -MODULES = [ - ("Intent", "intent", "dir"), - ("Memory", "memory", "dir"), - ("LLM", "llm", "dir"), - ("ASR", "asr", "file"), - ("TTS", "tts", "file"), - ("VAD", "vad", "file"), - ("VLLM", "vllm", "file"), -] - -# 目录式模块里,一个实现目录通常只服务一个 provider(目录名 == 配置键 == -# type)。LLM 是例外:core/providers/llm/openai/ 被 ChatGLMLLM、DoubaoLLM -# 等多个配置键共用,所以「实现 -> 配置」的反向检查只对一一对应的模块做。 -ONE_TO_ONE_MODULES = ("Memory",) - - -@pytest.fixture(scope="module") -def default_config(): - """出厂的 config.yaml(未经 data/.config.yaml 覆盖)。""" - return read_config(get_project_dir() + "config.yaml") - - -def _impl_path(mod: str, style: str, type_name: str) -> str: - """provider 实现的绝对路径。""" - root = get_project_dir() - if style == "dir": - return os.path.join(root, "core", "providers", mod, type_name, f"{type_name}.py") - return os.path.join(root, "core", "providers", mod, f"{type_name}.py") - - -def test_selected_module_provider_is_configured(default_config): - """selected_module 里选中的 provider 必须在对应配置段里存在。 - - core/connection.py 初始化各模块时都是直接下标取配置 - (self.config["Memory"][selected_module["Memory"]]["type"]), - 配置段里缺这个键就是启动期 KeyError。 - """ - selected = default_config.get("selected_module") or {} - for module in ("VAD", "ASR", "LLM", "VLLM", "TTS", "Memory", "Intent"): - name = selected.get(module) - assert name, f"selected_module.{module} 没有设置" - block = (default_config.get(module) or {}).get(name) - assert block is not None, ( - f"selected_module.{module} = {name}," - f"但 config.yaml 里没有 {module}.{name} 配置块" - ) - - -@pytest.mark.parametrize( - "section,mod,style", MODULES, ids=[section for section, _, _ in MODULES] -) -def test_every_configured_provider_has_implementation(default_config, section, mod, style): - """配置里的每个 provider,type 字段都必须指向真实存在的实现。 - - 覆盖「配置有、实现没有」:用户选了会在 create_instance 阶段报 - "不支持的服务类型"。 - """ - for name, block in (default_config.get(section) or {}).items(): - if not isinstance(block, dict): - continue - type_name = block.get("type", name) - path = _impl_path(mod, style, type_name) - assert os.path.exists(path), ( - f"{section}.{name} 的 type={type_name} 找不到实现文件 {path}" - ) - - -@pytest.mark.parametrize("section", ONE_TO_ONE_MODULES) -def test_every_implemented_provider_is_configured(default_config, section): - """实现里有的 provider,配置里必须也有一份。 - - 覆盖「实现有、配置没有」:这类 provider 用户根本没法从出厂配置里选到, - 一旦有人手动选了就会在连接初始化阶段 KeyError。 - - mem_report_only 就是这么漏掉的。 - """ - mod = section.lower() - providers_dir = os.path.join(get_project_dir(), "core", "providers", mod) - impls = sorted( - name - for name in os.listdir(providers_dir) - if os.path.isfile(os.path.join(providers_dir, name, f"{name}.py")) - ) - assert impls, f"core/providers/{mod} 下没找到任何 provider 实现" - - for name in impls: - block = (default_config.get(section) or {}).get(name) - assert block is not None, ( - f"core/providers/{mod}/{name} 有实现," - f"但 config.yaml 的 {section} 段没有 {name} 配置块" - ) - assert block.get("type", name) == name, ( - f"config.yaml 的 {section}.{name}.type 应该是 {name}," - f"实际是 {block.get('type')}" - ) From 61a8c04477a1334447679e319dccaad3db3e43dc Mon Sep 17 00:00:00 2001 From: wengzh <107969742+wengzh12138@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:53:37 +0800 Subject: [PATCH 16/16] =?UTF-8?q?feat(web=5Fsearch):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=20SpecStream=20=E6=90=9C=E7=B4=A2=E6=BA=90=20(#3560)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(web_search): 新增SpecStream搜索源 * docs(web_search): SpecStream API Key申请链接指向注册页 * docs: 更新SpecStream搜索的免费额度信息 --------- Co-authored-by: Tarek Etman --- docs/web-search-integration.md | 16 ++- .../resources/db/changelog/202611101200.sql | 9 ++ .../db/changelog/db.changelog-master.yaml | 7 + main/xiaozhi-server/config.yaml | 7 +- .../plugins_func/functions/web_search.py | 54 ++++++++ .../test_web_search_specstream.py | 128 ++++++++++++++++++ 6 files changed, 214 insertions(+), 7 deletions(-) create mode 100644 main/manager-api/src/main/resources/db/changelog/202611101200.sql create mode 100644 main/xiaozhi-server/tests/plugins_func/test_web_search_specstream.py diff --git a/docs/web-search-integration.md b/docs/web-search-integration.md index 77eb171f6..ccc0a1182 100644 --- a/docs/web-search-integration.md +++ b/docs/web-search-integration.md @@ -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 diff --git a/main/manager-api/src/main/resources/db/changelog/202611101200.sql b/main/manager-api/src/main/resources/db/changelog/202611101200.sql new file mode 100644 index 000000000..fee7e54ac --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/202611101200.sql @@ -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'; diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml index 31ac557f9..1bdd43de4 100644 --- a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -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 diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index ad9be91c1..11c87a5f6 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -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/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: diff --git a/main/xiaozhi-server/plugins_func/functions/web_search.py b/main/xiaozhi-server/plugins_func/functions/web_search.py index 623fc5f66..066b629c5 100644 --- a/main/xiaozhi-server/plugins_func/functions/web_search.py +++ b/main/xiaozhi-server/plugins_func/functions/web_search.py @@ -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, diff --git a/main/xiaozhi-server/tests/plugins_func/test_web_search_specstream.py b/main/xiaozhi-server/tests/plugins_func/test_web_search_specstream.py new file mode 100644 index 000000000..f6da7f8a9 --- /dev/null +++ b/main/xiaozhi-server/tests/plugins_func/test_web_search_specstream.py @@ -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}