]*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/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java
index 3db24fdbf..757abfc86 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImpl.java
@@ -95,6 +95,10 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
callerNickname = targetBook.get(bookKey(callerMac));
}
if (StringUtils.isBlank(callerNickname)) {
+ // 主叫显示名取的是主叫方自己那台设备在设备表里的名字,不是对方的。
+ // 对方那边给主叫方起的称呼在上面的 targetBook 里已经查过。
+ // 产品上按「来电显示」的口径处理,所以这里不套通讯录那套「不抄对方私产」的限制
+ // 这个接口没有登录用户上下文,归属校验那个查法在这里会返回空,只能用不校验归属的查法
DeviceEntity callerDevice = deviceService.getDeviceByMacAddress(callerMac);
if (callerDevice != null) {
callerNickname = callerDevice.getAlias();
@@ -212,11 +216,18 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
DeviceAddressBookEntity entity = new DeviceAddressBookEntity();
entity.setMacAddress(macAddress);
entity.setTargetMac(targetMac);
- // 如果 alias 为空,就默认使用设备名称;对方设备尚未登记时退回尾号称呼
+ // 调用方没起名就退回尾号称呼。对方设备在智控台上起的名字是对方的私产,
+ // 抄进调用方的通讯录等于把别人的昵称漏出去,所以别人的设备一律不去设备表取名
if (StringUtils.isBlank(alias)) {
- DeviceEntity targetDevice = deviceService.getDeviceByMacAddress(targetMac);
- if (targetDevice != null) {
- alias = targetDevice.getAlias();
+ // 只有给自己那台设备起名时才用设备表里的名字,那本来就是调用方自己的
+ if (isOwnDevice(macAddress, targetMac)) {
+ // 用带归属校验的那个查法。设备表里同一个 MAC 可能有两行只差大小写,
+ // 一次只准取一条的那种查法撞上这种数据会抛 TooManyResultsException,
+ // 整个保存接口带崩;按 id 取第一条,撞行也不报错
+ DeviceEntity ownDevice = deviceService.getOwnedDeviceByMacAddress(macAddress);
+ if (ownDevice != null && StringUtils.isNotBlank(ownDevice.getAlias())) {
+ alias = ownDevice.getAlias();
+ }
}
// 设备登记了但用户没起过名,alias 建表就是 null,这是默认状态
// 不是异常。这时候落个 null 进去,缓存刷新会把整条跳过,
@@ -304,6 +315,16 @@ public class DeviceAddressBookServiceImpl implements DeviceAddressBookService {
return macAddress == null ? null : macAddress.toLowerCase();
}
+ /**
+ * 目标设备是不是调用方自己那台
+ *
+ *
+ * MAC 不区分大小写,比较前先按通讯录的键归一化,跟别处的比较口径保持一致
+ */
+ private static boolean isOwnDevice(String macAddress, String targetMac) {
+ return bookKey(macAddress) != null && bookKey(macAddress).equals(bookKey(targetMac));
+ }
+
private String formatMacAsDeviceName(String mac) {
if (StringUtils.isBlank(mac) || mac.length() < 2) {
return mac;
diff --git a/main/manager-api/src/main/resources/db/changelog/202610302051.sql b/main/manager-api/src/main/resources/db/changelog/202610302051.sql
new file mode 100644
index 000000000..797ca7733
--- /dev/null
+++ b/main/manager-api/src/main/resources/db/changelog/202610302051.sql
@@ -0,0 +1,22 @@
+-- PaddleSpeechTTS:智控台协议收敛为仅 websocket(与 xiaozhi-server 实现一致)
+
+UPDATE `ai_model_provider`
+SET `fields` = JSON_ARRAY(
+ JSON_OBJECT('key', 'protocol', 'label', '协议类型', 'type', 'string', 'options', JSON_ARRAY('websocket')),
+ JSON_OBJECT('key', 'url', 'label', '服务地址', 'type', 'string'),
+ JSON_OBJECT('key', 'spk_id', 'label', '音色', 'type', 'int'),
+ JSON_OBJECT('key', 'sample_rate', 'label', '采样率', 'type', 'float'),
+ JSON_OBJECT('key', 'speed', 'label', '语速', 'type', 'float'),
+ JSON_OBJECT('key', 'volume', 'label', '音量', 'type', 'float'),
+ JSON_OBJECT('key', 'save_path', 'label', '保存路径', 'type', 'string')
+)
+WHERE `id` = 'SYSTEM_TTS_PaddleSpeechTTS';
+
+UPDATE `ai_model_config`
+SET `remark` = 'PaddleSpeechTTS 配置说明:
+1. PaddleSpeech 是百度飞桨开源的语音合成工具,支持本地离线部署和模型训练。paddlepaddle百度飞浆框架地址:https://www.paddlepaddle.org.cn/
+2. 当前仅支持 WebSocket 协议进行流式传输(参考部署文档:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/paddlespeech-deploy.md)。
+3. 使用前要在本地部署 paddlespeech 服务,服务默认运行在 ws://127.0.0.1:8092/paddlespeech/tts/streaming
+4. 支持自定义发音人、语速、音量和采样率。
+'
+WHERE `id` = 'TTS_PaddleSpeechTTS';
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/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 2737a24d1..dffe33cb7 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,24 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202610261030.sql
+ - changeSet:
+ id: 202610302051
+ author: shinjiyu
+ changes:
+ - sqlFile:
+ encoding: utf8
+ path: classpath:db/changelog/202610302051.sql
+ - changeSet:
+ id: 202611021200
+ author: heydryft
+ changes:
+ - 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/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/device/service/impl/DeviceAddressBookServiceImplTest.java b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImplTest.java
index aa16769f9..7e2d12ee5 100644
--- a/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImplTest.java
+++ b/main/manager-api/src/test/java/xiaozhi/modules/device/service/impl/DeviceAddressBookServiceImplTest.java
@@ -1,5 +1,6 @@
package xiaozhi.modules.device.service.impl;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -21,6 +22,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
+import org.apache.ibatis.exceptions.TooManyResultsException;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
@@ -75,7 +77,7 @@ class DeviceAddressBookServiceImplTest {
addressBookDao, redisUtils, deviceService, sysParamsService);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
- when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(null);
+ when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
@@ -85,10 +87,11 @@ class DeviceAddressBookServiceImplTest {
assertNotNull(entity.getAlias());
assertEquals("尾号为66的设备", entity.getAlias());
assertTrue(entity.getHasPermission());
+ verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
}
@Test
- void blankAliasOnRegisteredTargetWithoutNicknameFallsBackToMacSuffix() {
+ void blankAliasOnAnotherDeviceFallsBackToMacSuffixWithoutAskingTheDeviceTable() {
DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
RedisUtils redisUtils = mock(RedisUtils.class);
DeviceService deviceService = mock(DeviceService.class);
@@ -101,6 +104,7 @@ class DeviceAddressBookServiceImplTest {
registered.setMacAddress(OTHER_MAC);
registered.setAlias(null);
when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
+ when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(registered);
service.saveOrUpdate(MAC, OTHER_MAC, null, true);
@@ -108,6 +112,171 @@ class DeviceAddressBookServiceImplTest {
verify(addressBookDao).insertAddressBook(entityCaptor.capture());
assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
"登记了但没起名的设备落个空名,缓存刷新会跳过这条,对方永远呼不过来");
+ verify(deviceService, never()).getDeviceByMacAddress(anyString());
+ verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
+ }
+
+ @Test
+ void blankAliasOnRegisteredTargetDoesNotTakeOverTheirNickname() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+ DeviceEntity theirs = new DeviceEntity();
+ theirs.setMacAddress(OTHER_MAC);
+ theirs.setAlias("老王的音响");
+ when(deviceService.getDeviceByMacAddress(OTHER_MAC)).thenReturn(theirs);
+ when(deviceService.getOwnedDeviceByMacAddress(OTHER_MAC)).thenReturn(theirs);
+
+ service.saveOrUpdate(MAC, OTHER_MAC, null, true);
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias(),
+ "对方在智控台上给这台设备起的名字被抄进了调用方的通讯录");
+ verify(deviceService, never()).getDeviceByMacAddress(anyString());
+ verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
+ }
+
+ @Test
+ void blankAliasOnOwnDeviceUsesTheNameFromItsOwnDeviceRow() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+ DeviceEntity mine = new DeviceEntity();
+ mine.setMacAddress(MAC);
+ mine.setAlias("我的书房");
+ when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(mine);
+
+ service.saveOrUpdate(MAC, MAC, null, true);
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("我的书房", entityCaptor.getValue().getAlias(),
+ "给自己那台设备起名,用的就是自己设备表里的名字");
+ }
+
+ @Test
+ void ownDeviceWithoutAliasInDeviceTableFallsBackToMacSuffix() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+ DeviceEntity mine = new DeviceEntity();
+ mine.setMacAddress(MAC);
+ mine.setAlias(null);
+ when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(mine);
+
+ service.saveOrUpdate(MAC, MAC, null, true);
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("尾号为55的设备", entityCaptor.getValue().getAlias(),
+ "自己的设备在设备表里也没起名,落个空名的话缓存刷新会跳过这条");
+ }
+
+ @Test
+ void duplicateDeviceRowsDifferingOnlyInCaseDoNotBreakNaming() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+ // 设备表里同一个 MAC 有两行只差大小写,一次只准取一条的那种查法会直接抛异常
+ when(deviceService.getDeviceByMacAddress(anyString()))
+ .thenThrow(new TooManyResultsException("selectOne 撞上两行只差大小写的数据"));
+ DeviceEntity first = new DeviceEntity();
+ first.setMacAddress(MAC);
+ first.setAlias("我的书房");
+ when(deviceService.getOwnedDeviceByMacAddress(MAC)).thenReturn(first);
+
+ assertDoesNotThrow(() -> service.saveOrUpdate(MAC, MAC, null, true),
+ "同 MAC 有两行只差大小写时,取名不能把整个接口带崩");
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("我的书房", entityCaptor.getValue().getAlias(),
+ "撞行时按 id 取第一条那条的名字");
+ }
+
+ @Test
+ void ownDeviceIsRecognizedWhateverCaseTheAddressIsWrittenIn() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+ DeviceEntity mine = new DeviceEntity();
+ mine.setMacAddress(HEX_MAC);
+ mine.setAlias("我的书房");
+ when(deviceService.getOwnedDeviceByMacAddress(HEX_MAC)).thenReturn(mine);
+
+ service.saveOrUpdate(HEX_MAC, HEX_MAC.toUpperCase(), null, true);
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("我的书房", entityCaptor.getValue().getAlias(),
+ "同一个地址写成大小写两种样子,就被当成别人的设备了");
+ }
+
+ @Test
+ void explicitAliasIsKeptAsIs() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+
+ service.saveOrUpdate(MAC, OTHER_MAC, "客厅", true);
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("客厅", entityCaptor.getValue().getAlias(),
+ "自己给别人的设备起名是通讯录的本意,不能被兜底逻辑改掉");
+ verify(deviceService, never()).getDeviceByMacAddress(anyString());
+ verify(deviceService, never()).getOwnedDeviceByMacAddress(anyString());
+ }
+
+ @Test
+ void blankAliasOnUnregisteredTargetDoesNotBlowUp() {
+ DeviceAddressBookDao addressBookDao = mock(DeviceAddressBookDao.class);
+ RedisUtils redisUtils = mock(RedisUtils.class);
+ DeviceService deviceService = mock(DeviceService.class);
+ SysParamsService sysParamsService = mock(SysParamsService.class);
+ DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
+ addressBookDao, redisUtils, deviceService, sysParamsService);
+ when(addressBookDao.selectOne(any())).thenReturn(null);
+ when(addressBookDao.selectList(null)).thenReturn(List.of());
+ when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
+
+ assertDoesNotThrow(() -> service.saveOrUpdate(MAC, OTHER_MAC, null, true),
+ "目标设备没登记时接口得正常返回,不能抛异常");
+
+ ArgumentCaptor entityCaptor = ArgumentCaptor.forClass(DeviceAddressBookEntity.class);
+ verify(addressBookDao).insertAddressBook(entityCaptor.capture());
+ assertEquals("尾号为66的设备", entityCaptor.getValue().getAlias());
}
@Test
@@ -325,7 +494,7 @@ class DeviceAddressBookServiceImplTest {
DeviceService deviceService = mock(DeviceService.class);
when(addressBookDao.selectOne(any())).thenReturn(null);
when(addressBookDao.selectList(null)).thenReturn(List.of());
- when(deviceService.getDeviceByMacAddress(anyString())).thenReturn(null);
+ when(deviceService.getOwnedDeviceByMacAddress(anyString())).thenReturn(null);
DeviceAddressBookServiceImpl service = new DeviceAddressBookServiceImpl(
addressBookDao, redisUtils, deviceService, mock(SysParamsService.class));
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/manager-web/src/components/AddModelDialog.vue b/main/manager-web/src/components/AddModelDialog.vue
index c15ec9b34..347fb5d15 100644
--- a/main/manager-web/src/components/AddModelDialog.vue
+++ b/main/manager-web/src/components/AddModelDialog.vue
@@ -77,7 +77,11 @@
-
+
+
+
({
label: f.label,
prop: f.key,
- type: f.type === 'dict' ? 'json-textarea' : f.type === 'password' ? 'password' : 'text',
+ type: f.type === 'dict' ? 'json-textarea' : f.type === 'password' ? 'password' : (f.type === 'select' ? 'select' : 'text'),
+ options: f.options || [],
placeholder: `请输入${f.key}`
}))
}))
diff --git a/main/manager-web/src/components/ModelEditDialog.vue b/main/manager-web/src/components/ModelEditDialog.vue
index c5c64b253..afa3bc777 100644
--- a/main/manager-web/src/components/ModelEditDialog.vue
+++ b/main/manager-web/src/components/ModelEditDialog.vue
@@ -81,6 +81,11 @@
">
+
+
+
+
1 表示加快,<1 表示减慢
volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index ec5c442c9..f1be4cde4 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -781,7 +781,7 @@ class ConnectionHandler:
self.voiceprint_provider = voiceprint_provider
self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
else:
- self.logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整")
+ self.logger.bind(tag=TAG).debug("声纹识别功能启用但配置不完整")
else:
self.logger.bind(tag=TAG).info("声纹识别功能未启用")
except Exception as e:
diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py
index 62d4063a8..10c9d49f0 100644
--- a/main/xiaozhi-server/core/handle/helloHandle.py
+++ b/main/xiaozhi-server/core/handle/helloHandle.py
@@ -4,6 +4,7 @@ import uuid
import random
import asyncio
from typing import TYPE_CHECKING
+from config.logger import setup_logging
if TYPE_CHECKING:
from core.connection import ConnectionHandler
@@ -13,9 +14,14 @@ from core.providers.tts.dto.dto import SentenceType
from core.utils.wakeup_word import WakeupWordsConfig
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
-from core.providers.tools.device_mcp import MCPClient, send_mcp_initialize_message
+from core.providers.tools.device_mcp import (
+ MCPClient,
+ send_mcp_initialize_message,
+ send_mcp_tools_list_request,
+)
TAG = __name__
+_wakeup_logger = setup_logging()
WAKEUP_CONFIG = {
"refresh_time": 10,
@@ -63,6 +69,8 @@ async def handleHelloMessage(conn: "ConnectionHandler", msg_json):
# The device waits for the server hello before processing MCP messages.
if features and features.get("mcp"):
asyncio.create_task(send_mcp_initialize_message(conn))
+ # 并发预发 tools/list,让帧排在 audio 流之前到达 client
+ asyncio.create_task(send_mcp_tools_list_request(conn))
async def checkWakeupWords(conn: "ConnectionHandler", text):
@@ -105,19 +113,19 @@ async def checkWakeupWords(conn: "ConnectionHandler", text):
}
# 获取音频数据
- opus_packets = await audio_to_data(response.get("file_path"), use_cache=False)
+ opus_packets = await audio_to_data(response.get("file_path"), use_cache=True)
# 播放唤醒词回复
conn.client_abort = False
# 将唤醒词回复视为新会话,生成新的 sentence_id,确保流控器重置
conn.sentence_id = str(uuid.uuid4().hex)
- conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
- await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
- await sendAudioMessage(conn, SentenceType.LAST, [], None)
-
# 补充对话
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
+ conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
+
+ await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
+ asyncio.create_task(_finish_wakeup_reply(conn))
# 检查是否需要更新唤醒词回复
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
@@ -126,6 +134,16 @@ async def checkWakeupWords(conn: "ConnectionHandler", text):
return True
+async def _finish_wakeup_reply(conn: "ConnectionHandler"):
+ """等音频队列清空后再发 stop(时序:全部音频帧→stop),期间不阻塞接收循环"""
+ try:
+ await sendAudioMessage(conn, SentenceType.LAST, [], None)
+ except asyncio.CancelledError:
+ raise
+ except Exception as e:
+ conn.logger.bind(tag=TAG).error(f"唤醒词回复收尾失败: {e}")
+
+
async def wakeupWordsResponse(conn: "ConnectionHandler"):
if not conn.tts:
return
@@ -160,7 +178,32 @@ async def wakeupWordsResponse(conn: "ConnectionHandler"):
f.write(wav_bytes)
# 更新配置
wakeup_words_config.update_wakeup_response(voice, file_path, result)
+ # 覆写文件后 mtime 变化使旧缓存失效,此处立刻预编码新文件,
+ # 下次唤醒直接命中缓存,编码成本不占用唤醒响应路径
+ await audio_to_data(file_path, use_cache=True)
finally:
# 确保在任何情况下都释放锁
if _wakeup_response_lock.locked():
_wakeup_response_lock.release()
+
+
+async def preheat_wakeup_audio_cache():
+ """进程启动时预热唤醒词音频编码缓存
+
+ 把 wakeup_words/{voice}.wav 在 Opus 编码结果一次性算好塞进全局 cache,
+ 后续每条连接上来就能直接命中,省掉 wav→PCM→Opus 的数百毫秒开销。
+ """
+ # 进程启动时 tts 还未初始化,无法拿到 conn.tts.voice,按常见 fallback 列表预热
+ preheat_voices = ["default", "female-shaonv", "male-qn-jingying"]
+ fallback_path = "config/assets/wakeup_words_short.wav"
+ for voice in preheat_voices:
+ file_path = fallback_path
+ try:
+ response = wakeup_words_config.get_wakeup_response(voice)
+ if response and response.get("file_path"):
+ file_path = response["file_path"]
+ await audio_to_data(file_path, use_cache=True)
+ except Exception as e:
+ _wakeup_logger.bind(tag=TAG).warning(
+ f"预热 voice={voice} 失败: {e}"
+ )
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 509938c37..cdd944742 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -12,10 +12,8 @@ from core.providers.tts.dto.dto import SentenceType
from core.utils.audioRateController import AudioRateController
TAG = __name__
-# 音频帧时长(毫秒)
-AUDIO_FRAME_DURATION = 60
-# 预缓冲包数量,直接发送以减少延迟
-PRE_BUFFER_COUNT = 5
+AUDIO_FRAME_DURATION = 60 # 音频帧时长(毫秒),与 Opus 编码 60ms/帧对齐
+PRE_BUFFER_COUNT = 2 # 首段发送时不入队的帧数,避免流控延迟拉高首帧到达时间
async def sendAudioMessage(conn: "ConnectionHandler", sentenceType, audios, text, sentence_id=None):
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/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py
index e67c8333f..0229b4314 100644
--- a/main/xiaozhi-server/core/providers/llm/openai/openai.py
+++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py
@@ -16,12 +16,20 @@ THINKING_DISABLED_DOMAINS = {
"bigmodel.cn": {"thinking": {"type": "disabled"}},
"moonshot.cn": {"thinking": {"type": "disabled"}},
"volces.com": {"thinking": {"type": "disabled"}},
+ "modelarts-maas.com": {"thinking": {"type": "disabled"}},
+}
+
+# 域名规则的模型名豁免表: 强制思考模型不接受该参数注入(如 MaaS glm-5.3 传 thinking 必 400)
+THINKING_DISABLED_MODEL_EXCLUSIONS = {
+ "modelarts-maas.com": ("glm-5.3",),
}
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.model_name = config.get("model_name")
+ # 可选实例级思考强度: off/disabled/none/disable | low/medium/high | 空/其他=按域名默认
+ self.thinking_mode = str(config.get("thinking") or "").strip().lower()
self.api_key = config.get("api_key")
if "base_url" in config:
self.base_url = config.get("base_url")
@@ -80,14 +88,34 @@ class LLMProvider(LLMProviderBase):
return dialogue
def _apply_thinking_disabled(self, request_params: dict):
- """根据域名自动禁用思考模式"""
+ """思考模式控制: 实例配置(thinking)优先, 否则按域名默认表"""
+ mode = getattr(self, "thinking_mode", "")
+ if mode in ("keep", "passthrough", "default"):
+ # 不干预: 既不发 thinking 参数也不查域名表(适用于强制思考/拒绝该参数的模型, 如 MaaS glm-5.3)
+ return
+ if mode in ("off", "disabled", "none", "disable"):
+ request_params.setdefault("extra_body", {}).update({"thinking": {"type": "disabled"}})
+ logger.bind(tag=TAG).info("思考强度=off: 已禁用思考模式(实例配置)")
+ return
+ if mode in ("low", "medium", "high"):
+ request_params.setdefault("extra_body", {}).update(
+ {"reasoning_effort": mode, "thinking": {"type": "enabled"}})
+ logger.bind(tag=TAG).info(f"思考强度={mode}: reasoning_effort 已设置(实例配置)")
+ return
parsed_url = urlparse(self.base_url)
domain = parsed_url.netloc
+ model_name = (self.model_name or "").lower()
for disabled_domain, params in THINKING_DISABLED_DOMAINS.items():
- if disabled_domain in domain:
- request_params.setdefault("extra_body", {}).update(params)
- logger.bind(tag=TAG).info(f"为域名 {domain} 禁用思考模式,参数: {params}")
+ if disabled_domain not in domain:
+ continue
+ exclusions = THINKING_DISABLED_MODEL_EXCLUSIONS.get(disabled_domain, ())
+ if any(ex in model_name for ex in exclusions):
+ logger.bind(tag=TAG).info(
+ f"域名 {domain} 命中禁思考规则, 但模型 {self.model_name} 强制思考且拒绝该参数, 跳过注入")
break
+ request_params.setdefault("extra_body", {}).update(params)
+ logger.bind(tag=TAG).info(f"为域名 {domain} 禁用思考模式,参数: {params}")
+ break
def response(self, session_id, dialogue, **kwargs):
dialogue = self.normalize_dialogue(dialogue)
diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py
index 75aa22b55..a6a8edc15 100644
--- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py
+++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py
@@ -17,7 +17,11 @@ class MCPClient:
self.name_mapping = {}
self.ready = False
self.call_results = {} # To store Futures for tool call responses
- self.next_id = 1
+ # Handshake hardcodes id=1 (initialize) and id=2 (tools/list) in mcp_handler.
+ # JSON-RPC 2.0 forbids reusing request ids on the same connection, and
+ # compliant device MCP servers reject tools/call with id 1/2 (see #3461).
+ # Official protocol sequence expects the first tools/call to use id=3.
+ self.next_id = 3
self.lock = asyncio.Lock()
self._cached_available_tools = None # Cache for get_available_tools
diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py
index 76994cabb..d0371596d 100644
--- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py
+++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py
@@ -3,10 +3,10 @@
import json
import asyncio
import re
-from concurrent.futures import Future
-from core.utils.util import get_vision_url, sanitize_tool_name
+from core.utils.util import get_vision_url
from core.utils.auth import AuthToken
from config.logger import setup_logging
+from .mcp_client import MCPClient
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@@ -15,91 +15,6 @@ if TYPE_CHECKING:
TAG = __name__
logger = setup_logging()
-
-class MCPClient:
- """设备端MCP客户端,用于管理MCP状态和工具"""
-
- def __init__(self):
- self.tools = {} # sanitized_name -> tool_data
- self.name_mapping = {}
- self.ready = False
- self.call_results = {} # To store Futures for tool call responses
- self.next_id = 1
- self.lock = asyncio.Lock()
- self._cached_available_tools = None # Cache for get_available_tools
-
- def has_tool(self, name: str) -> bool:
- return name in self.tools
-
- def get_available_tools(self) -> list:
- # Check if the cache is valid
- if self._cached_available_tools is not None:
- return self._cached_available_tools
-
- # If cache is not valid, regenerate the list
- result = []
- for tool_name, tool_data in self.tools.items():
- function_def = {
- "name": tool_name,
- "description": tool_data["description"],
- "parameters": {
- "type": tool_data["inputSchema"].get("type", "object"),
- "properties": tool_data["inputSchema"].get("properties", {}),
- "required": tool_data["inputSchema"].get("required", []),
- },
- }
- result.append({"type": "function", "function": function_def})
-
- self._cached_available_tools = result # Store the generated list in cache
- return result
-
- async def is_ready(self) -> bool:
- async with self.lock:
- return self.ready
-
- async def set_ready(self, status: bool):
- async with self.lock:
- self.ready = status
-
- async def add_tool(self, tool_data: dict):
- async with self.lock:
- sanitized_name = sanitize_tool_name(tool_data["name"])
- self.tools[sanitized_name] = tool_data
- self.name_mapping[sanitized_name] = tool_data["name"]
- self._cached_available_tools = (
- None # Invalidate the cache when a tool is added
- )
-
- async def get_next_id(self) -> int:
- async with self.lock:
- current_id = self.next_id
- self.next_id += 1
- return current_id
-
- async def register_call_result_future(self, id: int, future: Future):
- async with self.lock:
- self.call_results[id] = future
-
- async def resolve_call_result(self, id: int, result: any):
- async with self.lock:
- if id in self.call_results:
- future = self.call_results.pop(id)
- if not future.done():
- future.set_result(result)
-
- async def reject_call_result(self, id: int, exception: Exception):
- async with self.lock:
- if id in self.call_results:
- future = self.call_results.pop(id)
- if not future.done():
- future.set_exception(exception)
-
- async def cleanup_call_result(self, id: int):
- async with self.lock:
- if id in self.call_results:
- self.call_results.pop(id)
-
-
async def send_mcp_message(conn: "ConnectionHandler", payload: dict):
"""Helper to send MCP messages, encapsulating common logic."""
if not conn.features.get("mcp"):
@@ -147,11 +62,6 @@ async def handle_mcp_message(
logger.bind(tag=TAG).debug(
f"客户端MCP服务器信息: name={name}, version={version}"
)
-
- await asyncio.sleep(1)
- logger.bind(tag=TAG).debug("初始化完成,开始请求MCP工具列表")
- await send_mcp_tools_list_request(conn)
-
return
elif msg_id == 2: # mcpToolsListID
diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py
index 4e9e5303f..b20ee6221 100644
--- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py
+++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py
@@ -18,7 +18,9 @@ class MCPEndpointClient:
self.name_mapping = {}
self.ready = False
self.call_results = {} # To store Futures for tool call responses
- self.next_id = 1
+ # Handshake hardcodes id=1 (initialize) and id=2 (tools/list) in
+ # mcp_endpoint_handler; tools/call must start at 3 to avoid id reuse.
+ self.next_id = 3
self.lock = asyncio.Lock()
self._cached_available_tools = None # Cache for get_available_tools
self.websocket = None # WebSocket连接
diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py
index f03f1a9bd..cd1749940 100644
--- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py
+++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py
@@ -107,7 +107,7 @@ class ServerMCPClient:
"function": {
"name": name,
"description": tool.description,
- "parameters": tool.inputSchema,
+ "parameters": tool.input_schema,
},
}
for name, tool in self.tools_dict.items()
diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py
index b1fc0aa34..cbd08392a 100644
--- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py
+++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py
@@ -24,7 +24,7 @@ class ServerMCPManager:
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
if not os.path.exists(self.config_path):
self.config_path = ""
- logger.bind(tag=TAG).warning(
+ logger.bind(tag=TAG).debug(
f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
)
self.clients: Dict[str, ServerMCPClient] = {}
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 67e724be7..4e991c4ee 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,8 @@
"""服务端插件工具执行器"""
import asyncio
+import functools
+from concurrent.futures import ThreadPoolExecutor
from typing import Dict, Any, TYPE_CHECKING
if TYPE_CHECKING:
@@ -8,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):
"""服务端插件工具执行器"""
@@ -28,23 +34,21 @@ class ServerPluginExecutor(ToolExecutor):
try:
# 根据工具类型决定如何调用
- 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)
- else:
- # 默认不传conn参数
- result = func_item.func(**arguments)
+ 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)
- # 兼容 async def 工具函数
- if asyncio.iscoroutine(result):
- result = await result
+ if asyncio.iscoroutinefunction(func_item.func):
+ result = await call()
+ else:
+ # 同步函数在 loop 线程上直接执行会卡住整个事件循环,放专用线程池。
+ result = await asyncio.get_running_loop().run_in_executor(_PLUGIN_POOL, call)
+ # 兼容同步函数返回协程的写法
+ if asyncio.iscoroutine(result):
+ result = await result
return result
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 864c18b82..d38dcf120 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:
"""检查是否存在指定工具"""
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/paddle_speech.py b/main/xiaozhi-server/core/providers/tts/paddle_speech.py
index e9562d60e..d39dce273 100644
--- a/main/xiaozhi-server/core/providers/tts/paddle_speech.py
+++ b/main/xiaozhi-server/core/providers/tts/paddle_speech.py
@@ -23,9 +23,11 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
- self.url = config.get("url", "ws://192.168.1.10:8092/paddlespeech/tts/streaming")
+ self.url = config.get("url", "ws://127.0.0.1:8092/paddlespeech/tts/streaming")
self.protocol = config.get("protocol", "websocket")
-
+ if self.protocol != "websocket":
+ raise ValueError("Unsupported protocol. Please use 'websocket'.")
+
if config.get("private_voice"):
self.spk_id = int(config.get("private_voice"))
else:
@@ -82,7 +84,7 @@ class TTSProvider(TTSProviderBase):
if self.protocol == "websocket":
return await self.text_streaming(text, output_file)
else:
- raise ValueError("Unsupported protocol. Please use 'websocket' or 'http'.")
+ raise ValueError("Unsupported protocol. Please use 'websocket'.")
async def text_streaming(self, text, output_file):
try:
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:
diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py
index edae6e9a1..8a5e7c988 100644
--- a/main/xiaozhi-server/core/utils/prompt_manager.py
+++ b/main/xiaozhi-server/core/utils/prompt_manager.py
@@ -5,6 +5,7 @@
import os
import asyncio
+import hashlib
import threading
from typing import Dict, Any, TYPE_CHECKING
@@ -120,8 +121,9 @@ class PromptManager:
# 使用传入的提示词并缓存(如果有设备ID)
if device_id:
- device_cache_key = f"device_prompt:{device_id}"
- self.cache_manager.set(self.CacheType.DEVICE_PROMPT, device_cache_key, user_prompt)
+ self.cache_manager.set(
+ self.CacheType.DEVICE_PROMPT, device_cache_key, user_prompt
+ )
self.logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存")
self.logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...")
@@ -253,6 +255,18 @@ class PromptManager:
if not self.base_prompt_template:
return user_prompt
+ # 缓存键须覆盖所有渲染输入:emoji 开关、设备 prompt 变更否则会命中过期提示词
+ emoji_enabled = kwargs.get("emoji_enabled", True)
+ prompt_hash = hashlib.md5(user_prompt.encode("utf-8")).hexdigest()[:8]
+ enhanced_cache_key = (
+ f"enhanced_prompt:{device_id}:{emoji_enabled}:{prompt_hash}"
+ )
+ cached_prompt = self.cache_manager.get(
+ self.CacheType.DEVICE_PROMPT, enhanced_cache_key
+ )
+ if cached_prompt is not None:
+ return cached_prompt
+
try:
# 获取最新的时间信息(不缓存)
today_date, today_weekday, lunar_date = self._get_current_time_info()
@@ -301,11 +315,13 @@ class PromptManager:
*args,
**kwargs,
)
- device_cache_key = f"device_prompt:{device_id}"
self.cache_manager.set(
- self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt
+ self.CacheType.DEVICE_PROMPT,
+ enhanced_cache_key,
+ enhanced_prompt,
+ ttl=300,
)
- self.logger.bind(tag=TAG).info(
+ self.logger.bind(tag=TAG).debug(
f"构建增强提示词成功,长度: {len(enhanced_prompt)}"
)
return enhanced_prompt
diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py
index c5fa3fa9b..c3a201c60 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")}
# 存入缓存
@@ -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
@@ -310,8 +318,12 @@ async def audio_to_data(
from core.utils.cache.manager import cache_manager
from core.utils.cache.config import CacheType
- # 生成缓存键,包含文件路径和编码类型
- cache_key = f"{audio_file_path}:{is_opus}"
+ # 缓存键含 mtime:文件被原地覆写时旧缓存自动失效(如唤醒词回复重新 TTS),避免播到过期音频
+ try:
+ mtime = os.path.getmtime(audio_file_path)
+ cache_key = f"{audio_file_path}:{mtime}:{is_opus}"
+ except OSError:
+ cache_key = f"{audio_file_path}:{is_opus}"
# 尝试从缓存获取结果
if use_cache:
diff --git a/main/xiaozhi-server/performance_tester.py b/main/xiaozhi-server/performance_tester.py
index f8346ba26..b39944a31 100644
--- a/main/xiaozhi-server/performance_tester.py
+++ b/main/xiaozhi-server/performance_tester.py
@@ -2,7 +2,7 @@ import os
import importlib.util
import asyncio
-print("使用前请根据doc/performance_testerer.md的说明准备配置。")
+print("使用前请根据仓库根目录下 docs/performance_tester.md 的说明准备配置。")
def list_performance_tester_modules():
diff --git a/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py b/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py
index 7496b22b1..9eff67afc 100644
--- a/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py
+++ b/main/xiaozhi-server/performance_tester/performance_tester_stream_tts.py
@@ -647,8 +647,9 @@ class StreamTTSPerformanceTester:
self.results.append(result)
# 测试Linkerai TTS
- result = await self.test_linkerai_tts(test_text, test_count)
- self.results.append(result)
+ if self.config.get("TTS", {}).get("LinkeraiTTS"):
+ result = await self.test_linkerai_tts(test_text, test_count)
+ self.results.append(result)
# 测试IndexStreamTTS
result = await self.test_indexstream_tts(test_text, test_count)
diff --git a/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py b/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py
index 631b3027d..c30987d4d 100644
--- a/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py
+++ b/main/xiaozhi-server/plugins_func/functions/get_news_from_newsnow.py
@@ -1,6 +1,7 @@
import random
import httpx
from io import BytesIO
+from urllib.parse import quote, urlsplit, urlunsplit, parse_qsl
from markitdown import MarkItDown, StreamInfo
from config.logger import setup_logging
from plugins_func.register import register_function, ToolType, ActionResponse, Action
@@ -54,6 +55,27 @@ CHANNEL_MAP = {
# 默认新闻来源字典,当配置中没有指定时使用
DEFAULT_NEWS_SOURCES = "澎湃新闻;百度热搜;财联社"
+DEFAULT_NEWS_API_URL = "https://newsnow.busiyi.world/api/s?id="
+
+
+def _build_news_api_url(source, configured_url=None):
+ """拼出新闻接口的请求地址和查询参数。
+
+ 配置里带 {source} 占位符就替换占位符;否则把 id 设成新闻源 id,
+ 这样配置里已经写了 id 时也不会拼出脏串。
+ """
+ api_url = str(configured_url).strip() if configured_url else DEFAULT_NEWS_API_URL
+ if "{source}" in api_url:
+ return api_url.replace("{source}", quote(source, safe="")), None
+ parts = urlsplit(api_url)
+ query = dict(parse_qsl(parts.query, keep_blank_values=True))
+ query["id"] = source
+ return (
+ urlunsplit((parts.scheme, parts.netloc, parts.path, "", parts.fragment)),
+ query,
+ )
+
+
def _get_newsnow_config(conn):
# 从连接配置获取
plugins = conn.config.get("plugins", {})
@@ -61,6 +83,8 @@ def _get_newsnow_config(conn):
sources = newsnow.get("news_sources", "")
if isinstance(sources, str) and sources.strip():
return sources
+ if isinstance(sources, (list, tuple)):
+ return ";".join(str(item).strip() for item in sources if str(item).strip())
return ""
@@ -113,23 +137,26 @@ GET_NEWS_FROM_NEWSNOW_FUNCTION_DESC = {
async def fetch_news_from_api(conn: "ConnectionHandler", source="thepaper"):
"""从API获取新闻列表"""
try:
- api_url = f"https://newsnow.busiyi.world/api/s?id={source}"
-
news_config = conn.config.get("plugins", {}).get("get_news_from_newsnow", {})
- if news_config.get("url"):
- api_url = news_config["url"] + source
+ configured_url = news_config.get("url") if isinstance(news_config, dict) else None
+ api_url, request_params = _build_news_api_url(source, configured_url)
headers = {"User-Agent": "Mozilla/5.0"}
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
- response = await client.get(api_url, headers=headers)
+ response = await client.get(api_url, params=request_params, headers=headers)
+ if response.status_code != 200:
+ logger.bind(tag=TAG).error(
+ f"获取新闻API失败:HTTP {response.status_code},source={source}"
+ )
+ return []
data = response.json()
- if "items" in data:
- return data["items"]
- else:
+ items = data.get("items") if isinstance(data, dict) else None
+ if not isinstance(items, list):
logger.bind(tag=TAG).error(f"获取新闻API响应格式错误: {data}")
return []
+ return [item for item in items if isinstance(item, dict) and item.get("title")]
except Exception as e:
logger.bind(tag=TAG).error(f"获取新闻API失败: {e}")
@@ -239,18 +266,24 @@ async def get_news_from_newsnow(
english_source_id = None
# 检查输入的中文名称是否在配置的新闻源中
- news_sources_list = [
- name.strip() for name in news_sources.split(";") if name.strip()
- ]
+ news_sources_list = [name.strip() for name in news_sources.split(";") if name.strip()]
if source in news_sources_list:
- # 如果输入的中文名称在配置的新闻源中,在 CHANNEL_MAP 中查找对应的英文ID
+ english_source_id = CHANNEL_MAP.get(source)
+ elif not source and news_sources_list:
+ source = news_sources_list[0]
english_source_id = CHANNEL_MAP.get(source)
# 如果找不到对应的英文ID,使用默认源
if not english_source_id:
- logger.bind(tag=TAG).warning(f"无效的新闻源: {source},使用默认源澎湃新闻")
- english_source_id = "thepaper"
- source = "澎湃新闻"
+ fallback_source = next(
+ (name for name in news_sources_list if CHANNEL_MAP.get(name)),
+ "澎湃新闻",
+ )
+ logger.bind(tag=TAG).warning(
+ f"无效的新闻源: {source},使用配置中的默认源{fallback_source}"
+ )
+ english_source_id = CHANNEL_MAP[fallback_source]
+ source = fallback_source
logger.bind(tag=TAG).info(f"获取新闻: 新闻源={source}({english_source_id})")
@@ -266,20 +299,21 @@ async def get_news_from_newsnow(
# 随机选择一条新闻
selected_news = random.choice(news_items)
+ title = selected_news.get("title", "未知标题")
# 保存当前新闻链接到连接对象,以便后续查询详情
if not hasattr(conn, "last_newsnow_link"):
conn.last_newsnow_link = {}
conn.last_newsnow_link = {
"url": selected_news.get("url", "#"),
- "title": selected_news.get("title", "未知标题"),
+ "title": title,
"source_id": english_source_id,
}
# 构建新闻报告
news_report = (
f"根据下列数据,用{lang}回应用户的新闻查询请求:\n\n"
- f"新闻标题: {selected_news['title']}\n"
+ f"新闻标题: {title}\n"
# f"新闻来源: {source}\n"
f"(请以自然、流畅的方式向用户播报这条新闻标题,"
f"提示用户可以要求获取详细内容,此时会获取新闻的详细内容。)"
diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py
index c0c4118e0..6cee939a5 100644
--- a/main/xiaozhi-server/plugins_func/functions/get_weather.py
+++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py
@@ -1,3 +1,4 @@
+import asyncio
import httpx
from bs4 import BeautifulSoup
from config.logger import setup_logging
@@ -112,20 +113,106 @@ WEATHER_CODE_MAP = {
async def fetch_city_info(location, api_key, api_host):
- url = f"https://{api_host}/geo/v2/city/lookup?key={api_key}&location={location}&lang=zh"
+ url = f"https://{api_host}/geo/v2/city/lookup"
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0, connect=3.0)) as client:
- response = await client.get(url, headers=HEADERS)
- data = response.json()
- if data.get("error") is not None:
+ response = await client.get(
+ url,
+ params={
+ "key": api_key,
+ "location": location,
+ "lang": "zh",
+ "number": 1,
+ },
+ headers=HEADERS,
+ )
+ try:
+ data = response.json()
+ except ValueError:
logger.bind(tag=TAG).error(
- f"获取天气失败,原因:{data.get('error', {}).get('detail')}"
+ f"获取天气城市失败:HTTP {response.status_code} 返回了非 JSON 内容"
+ )
+ return None
+ if not isinstance(data, dict):
+ logger.bind(tag=TAG).error("获取天气城市失败:响应不是 JSON 对象")
+ return None
+ if response.status_code != 200 or data.get("code") != "200":
+ logger.bind(tag=TAG).error(
+ f"获取天气城市失败:HTTP {response.status_code},代码 {data.get('code')}"
)
return None
return data.get("location", [])[0] if data.get("location") else None
+async def fetch_weather_data(city_info, api_key, api_host):
+ location_id = city_info.get("id")
+ if not location_id:
+ return None
+
+ base_url = f"https://{api_host}/v7/weather"
+ params = {"key": api_key, "location": location_id, "lang": "zh"}
+
+ async def request(client, endpoint):
+ response = await client.get(f"{base_url}/{endpoint}", params=params, headers=HEADERS)
+ try:
+ data = response.json()
+ except ValueError:
+ return None
+ if response.status_code != 200 or data.get("code") != "200":
+ logger.bind(tag=TAG).error(
+ f"获取天气数据失败:接口={endpoint} HTTP {response.status_code},代码 {data.get('code')}"
+ )
+ return None
+ return data
+
+ try:
+ async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
+ now, daily = await asyncio.gather(
+ request(client, "now"), request(client, "7d")
+ )
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"获取天气 JSON 接口失败,将尝试网页接口: {e}")
+ return None
+ if now is None or daily is None:
+ return None
+ return now, daily
+
+
+def build_weather_report(city_info, now_data, daily_data):
+ city_name = city_info.get("name") or city_info.get("adm2") or "未知位置"
+ now = now_data.get("now", {})
+ weather_report = f"您查询的位置是:{city_name}\n\n"
+ weather_report += f"当前天气: {now.get('text', '未知')}\n"
+
+ current_basic = {
+ "温度": f"{now['temp']}℃" if now.get("temp") is not None else None,
+ "体感温度": f"{now['feelsLike']}℃" if now.get("feelsLike") is not None else None,
+ "湿度": f"{now['humidity']}%" if now.get("humidity") is not None else None,
+ "风向": now.get("windDir"),
+ "风力": now.get("windScale"),
+ "能见度": f"{now['vis']}公里" if now.get("vis") is not None else None,
+ "气压": f"{now['pressure']}百帕" if now.get("pressure") is not None else None,
+ "降水量": f"{now['precip']}毫米" if now.get("precip") is not None else None,
+ }
+ current_basic = {key: value for key, value in current_basic.items() if value}
+ if current_basic:
+ weather_report += "详细参数:\n"
+ weather_report += "".join(f" · {key}: {value}\n" for key, value in current_basic.items())
+
+ weather_report += "\n未来7天预报:\n"
+ for item in daily_data.get("daily", [])[:7]:
+ date = item.get("fxDate", "未知日期")
+ weather = item.get("textDay") or WEATHER_CODE_MAP.get(item.get("iconDay"), "未知")
+ high = item.get("tempMax", "未知")
+ low = item.get("tempMin", "未知")
+ weather_report += f"{date}: {weather},气温 {low}~{high}℃\n"
+ weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
+ return weather_report
+
+
async def fetch_weather_page(url):
- async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
+ async with httpx.AsyncClient(
+ timeout=httpx.Timeout(10.0, connect=3.0), follow_redirects=True
+ ) as client:
response = await client.get(url, headers=HEADERS)
return BeautifulSoup(response.text, "html.parser") if response.status_code == 200 else None
@@ -181,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")
@@ -201,29 +289,31 @@ async def get_weather(conn: "ConnectionHandler", location: str = None, lang: str
city_info = await fetch_city_info(location, api_key, api_host)
if not city_info:
return ActionResponse(
- Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None
+ Action.REQLLM,
+ f"暂时查不到 {location} 的天气(城市未找到或天气服务不可用),请稍后再试",
+ None,
)
- soup = await fetch_weather_page(city_info["fxLink"])
- if not soup:
- return ActionResponse(Action.REQLLM, None, "请求失败")
- city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
-
- weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_abstract}\n"
-
- # 添加有效的当前天气参数
- if current_basic:
- weather_report += "详细参数:\n"
- for key, value in current_basic.items():
- if value != "0": # 过滤无效值
- weather_report += f" · {key}: {value}\n"
-
- # 添加7天预报
- weather_report += "\n未来7天预报:\n"
- for date, weather, high, low in temps_list:
- weather_report += f"{date}: {weather},气温 {low}~{high}\n"
-
- # 提示语
- weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
+ weather_data = await fetch_weather_data(city_info, api_key, api_host)
+ if weather_data:
+ weather_report = build_weather_report(city_info, *weather_data)
+ else:
+ fx_link = city_info.get("fxLink")
+ soup = await fetch_weather_page(fx_link) if fx_link else None
+ if not soup:
+ return ActionResponse(Action.REQLLM, None, "请求天气数据失败")
+ city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
+ weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_abstract}\n"
+ if current_basic:
+ weather_report += "详细参数:\n"
+ weather_report += "".join(
+ f" · {key}: {value}\n" for key, value in current_basic.items() if value != "0"
+ )
+ weather_report += "\n未来7天预报:\n"
+ weather_report += "".join(
+ f"{date}: {weather},气温 {low}~{high}\n"
+ for date, weather, high, low in temps_list
+ )
+ weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
# 缓存完整的天气报告
cache_manager.set(CacheType.WEATHER, weather_cache_key, weather_report)
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py
index a106d16d3..2a0c2edd4 100644
--- a/main/xiaozhi-server/plugins_func/functions/hass_init.py
+++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py
@@ -1,27 +1,53 @@
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 配置转成拼进提示词的文字。
+
+ config.yaml 示例和手机端智控台给的是列表,每项一条"位置,设备名,entity_id",这里拼成每行一条;
+ 网页端智控台和 HA 集成文档是一段字符串,原样用;其它(如 None)当空。
+ """
+ if isinstance(devices, (list, tuple)):
+ 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 = 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)
@@ -32,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/plugins_func/functions/hass_state.py b/main/xiaozhi-server/plugins_func/functions/hass_state.py
index 240f7cd35..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
@@ -142,13 +139,11 @@ 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)):
+ # 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}")
return responsetext
else:
diff --git a/main/xiaozhi-server/plugins_func/functions/web_search.py b/main/xiaozhi-server/plugins_func/functions/web_search.py
index 611733573..066b629c5 100644
--- a/main/xiaozhi-server/plugins_func/functions/web_search.py
+++ b/main/xiaozhi-server/plugins_func/functions/web_search.py
@@ -149,6 +149,106 @@ 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:
+ # 错误信封为 {"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} | code: {code} | detail: {detail}"
+ )
+ 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:
+ 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)
+
+
+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}")
@@ -175,6 +275,10 @@ 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)
+ elif provider == "specstream":
+ result_text = await _search_specstream(api_key, query, max_results)
else:
return ActionResponse(
Action.REQLLM,
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/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 复制粘贴时带串了"
+ )
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/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..2ae45c389
--- /dev/null
+++ b/main/xiaozhi-server/tests/core/providers/tools/test_plugin_executor_offload.py
@@ -0,0 +1,134 @@
+"""服务端插件执行器:同步插件函数在线程池里跑,不卡事件循环;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
+
+
+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():
+ 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) # 模拟阻塞 IO
+ 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 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) >= 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", {})
+ 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)
+
+
+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)
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
new file mode 100644
index 000000000..ee775439f
--- /dev/null
+++ b/main/xiaozhi-server/tests/plugins_func/test_hass_init.py
@@ -0,0 +1,101 @@
+"""append_devices_to_prompt:devices 写成列表或一段字符串都能拼进提示词。
+
+config.yaml 示例和手机端智控台给的是列表,以前会报
+can only concatenate str (not "list") to str,设备清单进不了提示词,模型只能猜 entity_id。
+"""
+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, initialize_hass_handler
+
+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")
+
+
+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)
+ 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 == []
+
+
+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
diff --git a/main/xiaozhi-server/tests/plugins_func/test_weather_news_plugins.py b/main/xiaozhi-server/tests/plugins_func/test_weather_news_plugins.py
new file mode 100644
index 000000000..669ca11c6
--- /dev/null
+++ b/main/xiaozhi-server/tests/plugins_func/test_weather_news_plugins.py
@@ -0,0 +1,336 @@
+"""Tests for the weather and newsnow plugin helpers.
+
+The two plugins talk to external APIs, so 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 get_news_from_newsnow as news_module
+from plugins_func.functions import get_weather as weather_module
+
+
+class FakeResponse:
+ def __init__(self, status_code=200, payload=None, text="", json_error=None):
+ self.status_code = status_code
+ self.payload = payload
+ self.text = text
+ self.json_error = json_error
+
+ def json(self):
+ if self.json_error is not None:
+ raise self.json_error
+ return self.payload
+
+
+class FakeAsyncClient:
+ """Stands in for httpx.AsyncClient and records what was requested."""
+
+ requests = []
+ responder = None
+ init_kwargs = {}
+
+ def __init__(self, *args, **kwargs):
+ FakeAsyncClient.init_kwargs = kwargs
+
+ 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})
+ return FakeAsyncClient.responder(url, params)
+
+
+@pytest.fixture
+def fake_http(monkeypatch):
+ """Replace httpx.AsyncClient with the recording fake."""
+ FakeAsyncClient.requests = []
+ FakeAsyncClient.responder = lambda url, params: FakeResponse(payload={"code": "200"})
+ FakeAsyncClient.init_kwargs = {}
+ monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient)
+ return FakeAsyncClient
+
+
+class FakeConn:
+ def __init__(self, plugins=None):
+ self.config = {"plugins": plugins or {}}
+ self.client_ip = None
+
+
+# ---------------------------------------------------------------------------
+# 城市查询
+# ---------------------------------------------------------------------------
+
+
+async def test_city_lookup_returns_none_on_error_code(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(payload={"code": "402"})
+
+ result = await weather_module.fetch_city_info("杭州", "key", "host")
+
+ assert result is None
+
+
+async def test_city_lookup_returns_none_on_non_json_body(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(
+ text="oops", json_error=ValueError("not json")
+ )
+
+ result = await weather_module.fetch_city_info("杭州", "key", "host")
+
+ assert result is None
+
+
+async def test_city_lookup_returns_none_on_non_dict_body(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(payload=["not", "an", "object"])
+
+ result = await weather_module.fetch_city_info("杭州", "key", "host")
+
+ assert result is None
+
+
+async def test_city_lookup_returns_none_on_empty_location(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(
+ payload={"code": "200", "location": []}
+ )
+
+ result = await weather_module.fetch_city_info("杭州", "key", "host")
+
+ assert result is None
+
+
+async def test_city_lookup_searches_all_cities(fake_http):
+ """不带 range 参数就是全球检索,写死 cn 会查不到境外城市。"""
+ fake_http.responder = lambda url, params: FakeResponse(
+ payload={"code": "200", "location": [{"id": "101210101", "name": "杭州"}]}
+ )
+
+ result = await weather_module.fetch_city_info("杭州", "key", "host")
+
+ assert result == {"id": "101210101", "name": "杭州"}
+ sent = fake_http.requests[0]["params"]
+ assert "range" not in sent
+ assert sent["location"] == "杭州"
+ assert sent["number"] == 1
+
+
+# ---------------------------------------------------------------------------
+# 天气数据
+# ---------------------------------------------------------------------------
+
+
+def _weather_responder(now_payload, daily_payload):
+ def responder(url, params):
+ if url.endswith("/now"):
+ return now_payload if isinstance(now_payload, FakeResponse) else FakeResponse(
+ payload=now_payload
+ )
+ return daily_payload if isinstance(daily_payload, FakeResponse) else FakeResponse(
+ payload=daily_payload
+ )
+
+ return responder
+
+
+async def test_weather_data_needs_both_now_and_daily(fake_http):
+ fake_http.responder = _weather_responder(
+ {"code": "200", "now": {"text": "晴"}},
+ FakeResponse(status_code=401, payload={"code": "401"}),
+ )
+
+ assert await weather_module.fetch_weather_data({"id": "1"}, "key", "host") is None
+
+
+async def test_weather_data_needs_daily_when_now_failed(fake_http):
+ fake_http.responder = _weather_responder(
+ FakeResponse(status_code=401, payload={"code": "401"}),
+ {"code": "200", "daily": [{"fxDate": "2026-10-24"}]},
+ )
+
+ assert await weather_module.fetch_weather_data({"id": "1"}, "key", "host") is None
+
+
+async def test_weather_data_returns_both_when_all_succeed(fake_http):
+ fake_http.responder = _weather_responder(
+ {"code": "200", "now": {"text": "晴"}},
+ {"code": "200", "daily": [{"fxDate": "2026-10-24"}]},
+ )
+
+ now, daily = await weather_module.fetch_weather_data({"id": "1"}, "key", "host")
+
+ assert now["now"]["text"] == "晴"
+ assert daily["daily"][0]["fxDate"] == "2026-10-24"
+
+
+async def test_weather_page_follows_redirects(fake_http):
+ """旧形态 fxLink 会 302,不跟随重定向就拿不到内容。"""
+ fake_http.responder = lambda url, params: FakeResponse(text="")
+
+ await weather_module.fetch_weather_page("https://www.qweather.com/weather/101210101.html")
+
+ assert fake_http.init_kwargs.get("follow_redirects") is True
+
+
+def test_weather_report_keeps_pressure_and_precipitation():
+ report = weather_module.build_weather_report(
+ {"name": "杭州"},
+ {"now": {"text": "多云", "temp": "24", "pressure": "1003", "precip": "0.0"}},
+ {"daily": []},
+ )
+
+ assert "气压: 1003百帕" in report
+ assert "降水量: 0.0毫米" in report
+
+
+async def test_weather_report_keeps_pressure_and_precipitation_in_flow(monkeypatch):
+ """走完整条链路时报告里也要有气压和降水量。"""
+ monkeypatch.setattr(
+ weather_module,
+ "fetch_city_info",
+ _async_value({"id": "1", "name": "杭州"}),
+ )
+ monkeypatch.setattr(
+ weather_module,
+ "fetch_weather_data",
+ _async_value(
+ ({"now": {"text": "多云", "pressure": "1003", "precip": "0.0"}}, {"daily": []})
+ ),
+ )
+
+ response = await weather_module.get_weather(
+ FakeConn({"get_weather": {"api_key": "k", "api_host": "h"}}), location="气压测试市"
+ )
+
+ assert "气压: 1003百帕" in response.result
+ assert "降水量: 0.0毫米" in response.result
+
+
+async def test_missing_fxlink_does_not_call_web_fallback(monkeypatch):
+ """城市信息里没有 fxLink 时不该去抓网页,直接报失败。"""
+ called = []
+
+ async def fake_city_info(*args, **kwargs):
+ return {"id": "1", "name": "杭州"}
+
+ async def fake_weather_data(*args, **kwargs):
+ return None
+
+ async def fake_page(url):
+ called.append(url)
+ return None
+
+ monkeypatch.setattr(weather_module, "fetch_city_info", fake_city_info)
+ monkeypatch.setattr(weather_module, "fetch_weather_data", fake_weather_data)
+ monkeypatch.setattr(weather_module, "fetch_weather_page", fake_page)
+
+ response = await weather_module.get_weather(
+ FakeConn({"get_weather": {"api_key": "k", "api_host": "h"}}), location="无链接市"
+ )
+
+ assert called == []
+ assert response.response == "请求天气数据失败"
+
+
+async def test_city_not_found_message_does_not_blame_the_place_name(monkeypatch):
+ """key 失效和城市找不到都落到这句话,不能让用户去核对地名。"""
+
+ async def fake_city_info(*args, **kwargs):
+ return None
+
+ monkeypatch.setattr(weather_module, "fetch_city_info", fake_city_info)
+
+ response = await weather_module.get_weather(
+ FakeConn({"get_weather": {"api_key": "k", "api_host": "h"}}), location="随便什么市"
+ )
+
+ assert "请确认地点是否正确" not in response.result
+ assert "天气服务不可用" in response.result
+
+
+# ---------------------------------------------------------------------------
+# 新闻接口
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "configured_url, expected_url, expected_params",
+ [
+ (None, "https://newsnow.busiyi.world/api/s", {"id": "thepaper"}),
+ (
+ "https://newsnow.busiyi.world/api/s?id=thepaper",
+ "https://newsnow.busiyi.world/api/s",
+ {"id": "thepaper"},
+ ),
+ (
+ "https://newsnow.busiyi.world/api/s?id={source}",
+ "https://newsnow.busiyi.world/api/s?id=thepaper",
+ None,
+ ),
+ (
+ "https://newsnow.busiyi.world/api/s",
+ "https://newsnow.busiyi.world/api/s",
+ {"id": "thepaper"},
+ ),
+ (
+ "https://newsnow.busiyi.world/api/s?id=",
+ "https://newsnow.busiyi.world/api/s",
+ {"id": "thepaper"},
+ ),
+ (
+ "https://newsnow.busiyi.world/api/s?id=thepaper&limit=5",
+ "https://newsnow.busiyi.world/api/s",
+ {"id": "thepaper", "limit": "5"},
+ ),
+ ],
+)
+def test_news_api_url_forms(configured_url, expected_url, expected_params):
+ url, params = news_module._build_news_api_url("thepaper", configured_url)
+
+ assert url == expected_url
+ assert params == expected_params
+
+
+async def test_news_api_url_forms_are_actually_requested(fake_http):
+ """配置里写了 id 也不能拼出脏串。"""
+ fake_http.responder = lambda url, params: FakeResponse(
+ payload={"items": [{"id": "1", "title": "标题"}]}
+ )
+ conn = FakeConn({"get_news_from_newsnow": {"url": "https://newsnow.busiyi.world/api/s?id=thepaper"}})
+
+ await news_module.fetch_news_from_api(conn, "thepaper")
+
+ assert fake_http.requests[0]["url"] == "https://newsnow.busiyi.world/api/s"
+ assert fake_http.requests[0]["params"] == {"id": "thepaper"}
+
+
+async def test_news_items_must_be_a_list(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(payload={"items": "oops"})
+
+ assert await news_module.fetch_news_from_api(FakeConn(), "thepaper") == []
+
+
+async def test_news_items_without_title_are_filtered_out(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(
+ payload={"items": [{"id": "1"}, {"id": "2", "title": ""}]}
+ )
+
+ assert await news_module.fetch_news_from_api(FakeConn(), "thepaper") == []
+
+
+async def test_news_items_keep_valid_entries(fake_http):
+ fake_http.responder = lambda url, params: FakeResponse(
+ payload={"items": [{"id": "1", "title": ""}, {"id": "2", "title": "有效标题"}]}
+ )
+
+ items = await news_module.fetch_news_from_api(FakeConn(), "thepaper")
+
+ assert items == [{"id": "2", "title": "有效标题"}]
+
+
+def _async_value(value):
+ async def _inner(*args, **kwargs):
+ return value
+
+ return _inner
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..12b9f8d12
--- /dev/null
+++ b/main/xiaozhi-server/tests/plugins_func/test_web_search_outcrawl.py
@@ -0,0 +1,122 @@
+"""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(
+ ("code", "message"),
+ [
+ ("unauthorized", "联网搜索请求失败,请检查API Key是否正确。"),
+ ("quota_exceeded", "联网搜索被限流或额度已用完,请稍后重试或检查Outcrawl账户余额。"),
+ ("bad_request", "联网搜索请求失败,请稍后重试。"),
+ ("internal", "联网搜索请求失败,请稍后重试。"),
+ ],
+)
+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
+
+
+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}
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}
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)