-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/main/manager-web/src/router/index.js b/main/manager-web/src/router/index.js
index a19b4ec6f..7e304f76d 100644
--- a/main/manager-web/src/router/index.js
+++ b/main/manager-web/src/router/index.js
@@ -39,6 +39,13 @@ const routes = [
return import('../views/register.vue')
}
},
+ {
+ path: '/retrieve-password',
+ name: 'RetrievePassword',
+ component: function () {
+ return import('../views/retrievePassword.vue')
+ }
+ },
// 设备管理页面路由
{
path: '/device-management',
@@ -73,6 +80,18 @@ const routes = [
title: '参数管理'
}
},
+
+ {
+ path: '/server-side-management',
+ name: 'ServerSideManager',
+ component: function () {
+ return import('../views/ServerSideManager.vue')
+ },
+ meta: {
+ requiresAuth: true,
+ title: '服务端管理'
+ }
+ },
{
path: '/ota-management',
name: 'OtaManagement',
diff --git a/main/manager-web/src/store/index.js b/main/manager-web/src/store/index.js
index 7a33ed61e..08dd50427 100644
--- a/main/manager-web/src/store/index.js
+++ b/main/manager-web/src/store/index.js
@@ -13,6 +13,8 @@ export default new Vuex.Store({
isSuperAdmin: false, // 添加superAdmin状态
pubConfig: { // 添加公共配置存储
version: '',
+ beianIcpNum: 'null',
+ beianGaNum: 'null',
allowUserRegister: false
}
},
diff --git a/main/manager-web/src/views/DeviceManagement.vue b/main/manager-web/src/views/DeviceManagement.vue
index 14138bd89..25cd5a688 100644
--- a/main/manager-web/src/views/DeviceManagement.vue
+++ b/main/manager-web/src/views/DeviceManagement.vue
@@ -1,12 +1,12 @@
@@ -102,7 +113,7 @@ import AddDeviceDialog from "@/components/AddDeviceDialog.vue";
import HeaderBar from "@/components/HeaderBar.vue";
export default {
- components: { HeaderBar, AddDeviceDialog },
+ components: {HeaderBar, AddDeviceDialog},
data() {
return {
addDeviceDialogVisible: false,
@@ -125,18 +136,15 @@ export default {
const keyword = this.activeSearchKeyword.toLowerCase();
if (!keyword) return this.deviceList;
return this.deviceList.filter(device =>
- (device.model && device.model.toLowerCase().includes(keyword)) ||
- (device.macAddress && device.macAddress.toLowerCase().includes(keyword))
+ (device.model && device.model.toLowerCase().includes(keyword)) ||
+ (device.macAddress && device.macAddress.toLowerCase().includes(keyword))
);
},
paginatedDeviceList() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
- return this.filteredDeviceList.slice(start, end).map(item => ({
- ...item,
- selected: false
- }));
+ return this.filteredDeviceList.slice(start, end);
},
pageCount() {
return Math.ceil(this.filteredDeviceList.length / this.pageSize);
@@ -212,11 +220,10 @@ export default {
this.batchUnbindDevices(deviceIds);
});
},
-
batchUnbindDevices(deviceIds) {
const promises = deviceIds.map(id => {
return new Promise((resolve, reject) => {
- Api.device.unbindDevice(id, ({ data }) => {
+ Api.device.unbindDevice(id, ({data}) => {
if (data.code === 0) {
resolve();
} else {
@@ -225,33 +232,61 @@ export default {
});
});
});
-
Promise.all(promises)
- .then(() => {
- this.$message.success({
- message: `成功解绑 ${deviceIds.length} 台设备`,
- showClose: true
+ .then(() => {
+ this.$message.success({
+ message: `成功解绑 ${deviceIds.length} 台设备`,
+ showClose: true
+ });
+ this.fetchBindDevices(this.currentAgentId);
+ this.selectedDevices = [];
+ this.isAllSelected = false;
+ })
+ .catch(error => {
+ this.$message.error({
+ message: error || '批量解绑过程中出现错误',
+ showClose: true
+ });
});
- this.fetchBindDevices(this.currentAgentId);
- this.selectedDevices = [];
- this.isAllSelected = false;
- })
- .catch(error => {
- this.$message.error({
- message: error || '批量解绑过程中出现错误',
- showClose: true
- });
- });
},
-
handleAddDevice() {
this.addDeviceDialogVisible = true;
},
- startEditRemark(index, row) {
- this.deviceList[index].isEdit = true;
+ submitRemark(row) {
+ if (row._submitting) return;
+
+ const text = (row.remark || '').trim();
+ if (text.length > 64) {
+ this.$message.warning('备注不能超过 64 字符');
+ return;
+ }
+ if (text === row._originalRemark) {
+ return;
+ }
+
+ row._submitting = true;
+ this.updateDeviceInfo(row.device_id, { alias: text }, (ok, resp) => {
+ if (ok) {
+ row._originalRemark = text;
+ this.$message.success('备注已保存');
+ } else {
+ row.remark = row._originalRemark;
+ this.$message.error(resp.msg || '备注保存失败');
+ }
+ row._submitting = false;
+ });
},
- stopEditRemark(index) {
- this.deviceList[index].isEdit = false;
+ // 备注输入框:失焦时提交
+ onRemarkBlur(row) {
+ row.isEdit = false;
+ setTimeout(() => {
+ this.submitRemark(row);
+ }, 100); // 延迟 100ms,避开 enter+blur 同时触发的窗口
+ },
+ // 备注输入框:按回车时提交
+ onRemarkEnter(row) {
+ row.isEdit = false;
+ this.submitRemark(row);
},
handleUnbind(device_id) {
this.$confirm('确认要解绑该设备吗?', '警告', {
@@ -259,7 +294,7 @@ export default {
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
- Api.device.unbindDevice(device_id, ({ data }) => {
+ Api.device.unbindDevice(device_id, ({data}) => {
if (data.code === 0) {
this.$message.success({
message: '设备解绑成功',
@@ -290,7 +325,7 @@ export default {
fetchBindDevices(agentId) {
this.loading = true;
- Api.device.getAgentBindDevices(agentId, ({ data }) => {
+ Api.device.getAgentBindDevices(agentId, ({data}) => {
this.loading = false;
if (data.code === 0) {
this.deviceList = data.data.map(device => {
@@ -302,12 +337,14 @@ export default {
bindTime: device.createDate,
lastConversation: device.lastConnectedAt,
remark: device.alias,
+ _originalRemark: device.alias,
isEdit: false,
+ _submitting: false,
otaSwitch: device.autoUpdate === 1,
rawBindTime: new Date(device.createDate).getTime()
};
})
- .sort((a, b) => a.rawBindTime - b.rawBindTime);
+ .sort((a, b) => a.rawBindTime - b.rawBindTime);
this.activeSearchKeyword = "";
this.searchKeyword = "";
} else {
@@ -315,7 +352,7 @@ export default {
}
});
},
- headerCellClassName({ columnIndex }) {
+ headerCellClassName({columnIndex}) {
if (columnIndex === 0) {
return "custom-selection-header";
}
@@ -325,14 +362,19 @@ export default {
const firmwareType = this.firmwareTypes.find(item => item.key === type)
return firmwareType ? firmwareType.name : type
},
+ updateDeviceInfo(device_id, payload, callback) {
+ return Api.device.updateDeviceInfo(device_id, payload, ({data}) => {
+ callback(data.code === 0, data);
+ })
+ },
handleOtaSwitchChange(row) {
- Api.device.enableOtaUpgrade(row.device_id, row.otaSwitch ? 1 : 0, ({ data }) => {
- if (data.code === 0) {
- this.$message.success(row.otaSwitch ? '已设置成自动升级' : '已关闭自动升级')
- } else {
- row.otaSwitch = !row.otaSwitch
- this.$message.error(data.msg || '操作失败')
+ this.updateDeviceInfo(row.device_id, {autoUpdate: row.otaSwitch ? 1 : 0}, (result, {msg}) => {
+ if (result) {
+ this.$message.success(row.otaSwitch ? '已设置成自动升级' : '已关闭自动升级');
+ return;
}
+ row.otaSwitch = !row.otaSwitch
+ this.$message.error(msg || '操作失败')
})
},
}
@@ -645,7 +687,6 @@ export default {
}
-
:deep(.el-table .el-button--text) {
color: #7079aa;
}
diff --git a/main/manager-web/src/views/DictManagement.vue b/main/manager-web/src/views/DictManagement.vue
index f4de8350b..9f6c80ac4 100644
--- a/main/manager-web/src/views/DictManagement.vue
+++ b/main/manager-web/src/views/DictManagement.vue
@@ -538,7 +538,7 @@ export default {
.data-table {
border-radius: 6px;
- overflow-y: auto;
+ overflow-y: hidden;
background-color: transparent !important;
--table-max-height: calc(100vh - 40vh);
max-height: var(--table-max-height);
diff --git a/main/manager-web/src/views/ModelConfig.vue b/main/manager-web/src/views/ModelConfig.vue
index aa788f2f6..5a88c9aab 100644
--- a/main/manager-web/src/views/ModelConfig.vue
+++ b/main/manager-web/src/views/ModelConfig.vue
@@ -30,6 +30,9 @@
@@ -173,6 +176,7 @@ export default {
vad: '语言活动检测模型(VAD)',
asr: '语音识别模型(ASR)',
llm: '大语言模型(LLM)',
+ vllm: '视觉大模型(VLLM)',
intent: '意图识别模型(Intent)',
tts: '语音合成模型(TTS)',
memory: '记忆模型(Memory)'
@@ -467,7 +471,7 @@ export default {
.main-wrapper {
margin: 5px 22px;
border-radius: 15px;
- min-height: calc(100vh - 24vh);
+ min-height: calc(100vh - 26vh);
height: auto;
max-height: 80vh;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
diff --git a/main/manager-web/src/views/ParamsManagement.vue b/main/manager-web/src/views/ParamsManagement.vue
index afb0dc1d8..71d0866b8 100644
--- a/main/manager-web/src/views/ParamsManagement.vue
+++ b/main/manager-web/src/views/ParamsManagement.vue
@@ -5,7 +5,7 @@
参数管理
-
搜索
diff --git a/main/manager-web/src/views/ProviderManagement.vue b/main/manager-web/src/views/ProviderManagement.vue
index 7634b511d..394e7ce40 100644
--- a/main/manager-web/src/views/ProviderManagement.vue
+++ b/main/manager-web/src/views/ProviderManagement.vue
@@ -3,7 +3,7 @@
-
供应器管理
+
字段管理
@@ -143,9 +143,11 @@ export default {
{ value: "ASR", label: "语音识别" },
{ value: "TTS", label: "语音合成" },
{ value: "LLM", label: "大语言模型" },
+ { value: "VLLM", label: "视觉大语言模型" },
{ value: "Intent", label: "意图识别" },
{ value: "Memory", label: "记忆模块" },
- { value: "VAD", label: "语音活动检测" }
+ { value: "VAD", label: "语音活动检测" },
+ { value: "Plugin", label: "插件工具" }
],
currentPage: 1,
loading: false,
diff --git a/main/manager-web/src/views/ServerSideManager.vue b/main/manager-web/src/views/ServerSideManager.vue
new file mode 100644
index 000000000..973fcd6f5
--- /dev/null
+++ b/main/manager-web/src/views/ServerSideManager.vue
@@ -0,0 +1,475 @@
+
+
+
+
+
+
服务端管理
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 重启
+ 更新配置
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/main/manager-web/src/views/login.vue b/main/manager-web/src/views/login.vue
index f082721e0..e31d51806 100644
--- a/main/manager-web/src/views/login.vue
+++ b/main/manager-web/src/views/login.vue
@@ -56,12 +56,13 @@
登录
-
+
@@ -214,6 +215,9 @@ export default {
goToRegister() {
goToPage('/register')
},
+ goToForgetPassword() {
+ goToPage('/retrieve-password')
+ },
}
}
diff --git a/main/manager-web/src/views/register.vue b/main/manager-web/src/views/register.vue
index 744da3e47..7eac511b2 100644
--- a/main/manager-web/src/views/register.vue
+++ b/main/manager-web/src/views/register.vue
@@ -201,6 +201,7 @@ export default {
// 验证图形验证码
if (!this.validateInput(this.form.captcha, '请输入图形验证码')) {
+ this.fetchCaptcha();
return;
}
diff --git a/main/manager-web/src/views/retrievePassword.vue b/main/manager-web/src/views/retrievePassword.vue
new file mode 100644
index 000000000..9072baaed
--- /dev/null
+++ b/main/manager-web/src/views/retrievePassword.vue
@@ -0,0 +1,275 @@
+
+
+
+
+
+
+

+

+
+
+
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/main/manager-web/src/views/roleConfig.vue b/main/manager-web/src/views/roleConfig.vue
index 03ec80604..209ff9dac 100644
--- a/main/manager-web/src/views/roleConfig.vue
+++ b/main/manager-web/src/views/roleConfig.vue
@@ -64,7 +64,27 @@
+
功能名称: {{ func.name }}
-
-
参数配置:
-
- {{ key }}: {{ value }}
-
-
-
无参数配置
{{ func.name.charAt(0) }}
-
编辑功能
@@ -118,7 +131,7 @@
-
@@ -148,6 +161,7 @@ export default {
vadModelId: "",
asrModelId: "",
llmModelId: "",
+ vllmModelId: "",
memModelId: "",
intentModelId: "",
}
@@ -156,6 +170,7 @@ export default {
{ label: '语音活动检测(VAD)', key: 'vadModelId', type: 'VAD' },
{ label: '语音识别(ASR)', key: 'asrModelId', type: 'ASR' },
{ label: '大语言模型(LLM)', key: 'llmModelId', type: 'LLM' },
+ { label: '视觉大模型(VLLM)', key: 'vllmModelId', type: 'VLLM' },
{ label: '意图识别(Intent)', key: 'intentModelId', type: 'Intent' },
{ label: '记忆(Memory)', key: 'memModelId', type: 'Memory' },
{ label: '语音合成(TTS)', key: 'ttsModelId', type: 'TTS' },
@@ -170,12 +185,8 @@ export default {
'#FF6B6B', '#4ECDC4', '#45B7D1',
'#96CEB4', '#FFEEAD', '#D4A5A5', '#A2836E'
],
- allFunctions: [
- { name: '天气', params: {} },
- { name: '新闻', params: {} },
- { name: '工具', params: {} },
- { name: '退出', params: {} }
- ],
+ allFunctions: [],
+ originalFunctions: [],
}
},
methods: {
@@ -189,6 +200,7 @@ export default {
asrModelId: this.form.model.asrModelId,
vadModelId: this.form.model.vadModelId,
llmModelId: this.form.model.llmModelId,
+ vllmModelId: this.form.model.vllmModelId,
ttsModelId: this.form.model.ttsModelId,
ttsVoiceId: this.form.ttsVoiceId,
chatHistoryConf: this.form.chatHistoryConf,
@@ -199,7 +211,12 @@ export default {
langCode: this.form.langCode,
language: this.form.language,
sort: this.form.sort,
- functions: this.currentFunctions
+ functions: this.currentFunctions.map(item => {
+ return ({
+ pluginId: item.id,
+ paramInfo: item.params
+ })
+ })
};
Api.agent.updateAgentConfig(this.$route.query.agentId, configData, ({ data }) => {
if (data.code === 0) {
@@ -236,6 +253,7 @@ export default {
vadModelId: "",
asrModelId: "",
llmModelId: "",
+ vllmModelId: "",
memModelId: "",
intentModelId: "",
}
@@ -245,7 +263,8 @@ export default {
message: '配置已重置',
showClose: true
})
- }).catch(() => { });
+ }).catch(() => {
+ });
},
fetchTemplates() {
Api.agent.getAgentTemplate(({ data }) => {
@@ -289,6 +308,7 @@ export default {
vadModelId: templateData.vadModelId || this.form.model.vadModelId,
asrModelId: templateData.asrModelId || this.form.model.asrModelId,
llmModelId: templateData.llmModelId || this.form.model.llmModelId,
+ vllmModelId: templateData.vllmModelId || this.form.model.vllmModelId,
memModelId: templateData.memModelId || this.form.model.memModelId,
intentModelId: templateData.intentModelId || this.form.model.intentModelId
}
@@ -305,11 +325,38 @@ export default {
vadModelId: data.data.vadModelId,
asrModelId: data.data.asrModelId,
llmModelId: data.data.llmModelId,
+ vllmModelId: data.data.vllmModelId,
memModelId: data.data.memModelId,
intentModelId: data.data.intentModelId
}
};
- this.currentFunctions = data.data.functions || [];
+ // 后端只给了最小映射:[{ id, agentId, pluginId }, ...]
+ const savedMappings = data.data.functions || [];
+
+ // 先保证 allFunctions 已经加载(如果没有,则先 fetchAllFunctions)
+ const ensureFuncs = this.allFunctions.length
+ ? Promise.resolve()
+ : this.fetchAllFunctions();
+
+ ensureFuncs.then(() => {
+ // 合并:按照 pluginId(id 字段)把全量元数据信息补齐
+ this.currentFunctions = savedMappings.map(mapping => {
+ const meta = this.allFunctions.find(f => f.id === mapping.pluginId);
+ if (!meta) {
+ // 插件定义没找到,退化处理
+ return { id: mapping.pluginId, name: mapping.pluginId, params: {} };
+ }
+ return {
+ id: mapping.pluginId,
+ name: meta.name,
+ // 后端如果还有 paramInfo 字段就用 mapping.paramInfo,否则用 meta.params 默认值
+ params: mapping.paramInfo || { ...meta.params },
+ fieldsMeta: meta.fieldsMeta // 保留以便对话框渲染 tooltip
+ };
+ });
+ // 备份原始,以备取消时恢复
+ this.originalFunctions = JSON.parse(JSON.stringify(this.currentFunctions));
+ });
} else {
this.$message.error(data.msg || '获取配置失败');
}
@@ -347,17 +394,15 @@ export default {
},
getFunctionColor(name) {
const hash = [...name].reduce((acc, char) => acc + char.charCodeAt(0), 0);
- return this.functionColorMap[hash % 7];
+ return this.functionColorMap[hash % this.functionColorMap.length];
},
showFunctionIcons(type) {
- // TODO 暂时不放出来
- return false;
- // return type === 'Intent' &&
- // this.form.model.intentModelId !== 'Intent_nointent';
+ return type === 'Intent' &&
+ this.form.model.intentModelId !== 'Intent_nointent';
},
handleModelChange(type, value) {
if (type === 'Intent' && value !== 'Intent_nointent') {
- this.fetchFunctionList();
+ this.fetchAllFunctions();
}
if (type === 'Memory' && value === 'Memory_nomem') {
this.form.chatHistoryConf = 0;
@@ -366,28 +411,44 @@ export default {
this.form.chatHistoryConf = 2;
}
},
- fetchFunctionList() {
- // 使用假数据代替API调用
- return new Promise(resolve => {
- setTimeout(() => {
- this.currentFunctions = [
- { name: '天气', params: { city: '北京' } },
- { name: '新闻', params: { type: '科技' } }
- ];
- resolve();
- }, 500);
+ fetchAllFunctions() {
+ return new Promise((resolve, reject) => {
+ Api.model.getPluginFunctionList(null, ({ data }) => {
+ if (data.code === 0) {
+ this.allFunctions = data.data.map(item => {
+ const meta = JSON.parse(item.fields || '[]');
+ const params = meta.reduce((m, f) => {
+ m[f.key] = f.default;
+ return m;
+ }, {});
+ return { ...item, fieldsMeta: meta, params };
+ });
+ resolve();
+ } else {
+ this.$message.error(data.msg || '获取插件列表失败');
+ reject();
+ }
+ });
});
},
+ openFunctionDialog() {
+ // 显示编辑对话框时,确保 allFunctions 已经加载
+ if (this.allFunctions.length === 0) {
+ this.fetchAllFunctions().then(() => this.showFunctionDialog = true);
+ } else {
+ this.showFunctionDialog = true;
+ }
+ },
handleUpdateFunctions(selected) {
this.currentFunctions = selected;
- console.log('保存的功能列表:', selected);
- this.$message.success('功能配置已保存');
},
handleDialogClosed(saved) {
if (!saved) {
- // 如果未保存,恢复原始功能列表
this.currentFunctions = JSON.parse(JSON.stringify(this.originalFunctions));
+ } else {
+ this.originalFunctions = JSON.parse(JSON.stringify(this.currentFunctions));
}
+ this.showFunctionDialog = false;
},
updateChatHistoryConf() {
if (this.form.model.memModelId === 'Memory_nomem') {
@@ -420,9 +481,7 @@ export default {
const agentId = this.$route.query.agentId;
if (agentId) {
this.fetchAgentConfig(agentId);
- this.fetchFunctionList().then(() => {
- this.originalFunctions = JSON.parse(JSON.stringify(this.currentFunctions));
- });
+ this.fetchAllFunctions();
}
this.fetchModelOptions();
this.fetchTemplates();
@@ -587,6 +646,25 @@ export default {
width: 100%;
}
+.model-row {
+ display: flex;
+ gap: 20px;
+ margin-bottom: 6px;
+}
+
+.model-row .model-item {
+ flex: 1;
+ margin-bottom: 0;
+}
+
+.model-row .el-form-item__label {
+ font-size: 12px !important;
+ color: #3d4566 !important;
+ font-weight: 400;
+ line-height: 22px;
+ padding-bottom: 2px;
+}
+
.function-icons {
display: flex;
align-items: center;
diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py
index 619fb5c7b..2088e1838 100644
--- a/main/xiaozhi-server/app.py
+++ b/main/xiaozhi-server/app.py
@@ -1,13 +1,14 @@
-import asyncio
import sys
+import uuid
import signal
+import asyncio
+from aioconsole import ainput
from config.settings import load_config
-from core.websocket_server import WebSocketServer
-from core.ota_server import SimpleOtaServer
-from core.utils.util import check_ffmpeg_installed
from config.logger import setup_logging
from core.utils.util import get_local_ip
-from aioconsole import ainput
+from core.http_server import SimpleHttpServer
+from core.websocket_server import WebSocketServer
+from core.utils.util import check_ffmpeg_installed
TAG = __name__
logger = setup_logging()
@@ -45,25 +46,37 @@ async def main():
check_ffmpeg_installed()
config = load_config()
+ # 默认使用manager-api的secret作为auth_key
+ # 如果secret为空,则生成随机密钥
+ # auth_key用于jwt认证,比如视觉分析接口的jwt认证
+ auth_key = config.get("manager-api", {}).get("secret", "")
+ if not auth_key or len(auth_key) == 0 or "你" in auth_key:
+ auth_key = str(uuid.uuid4().hex)
+ config["server"]["auth_key"] = auth_key
+
# 添加 stdin 监控任务
stdin_task = asyncio.create_task(monitor_stdin())
# 启动 WebSocket 服务器
ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start())
- ota_task = None
+ # 启动 Simple http 服务器
+ ota_server = SimpleHttpServer(config)
+ ota_task = asyncio.create_task(ota_server.start())
read_config_from_api = config.get("read_config_from_api", False)
+ port = int(config["server"].get("http_port", 8003))
if not read_config_from_api:
- # 启动 Simple OTA 服务器
- ota_server = SimpleOtaServer(config)
- ota_task = asyncio.create_task(ota_server.start())
-
logger.bind(tag=TAG).info(
"OTA接口是\t\thttp://{}:{}/xiaozhi/ota/",
get_local_ip(),
- config["server"]["ota_port"],
+ port,
)
+ logger.bind(tag=TAG).info(
+ "视觉分析接口是\thttp://{}:{}/mcp/vision/explain",
+ get_local_ip(),
+ port,
+ )
# 获取WebSocket配置,使用安全的默认值
websocket_port = 8000
@@ -102,7 +115,7 @@ async def main():
await asyncio.wait(
[stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
timeout=3.0,
- return_when=asyncio.ALL_COMPLETED
+ return_when=asyncio.ALL_COMPLETED,
)
print("服务器已关闭,程序退出。")
diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index 0efde59bf..a1362ce56 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -2,6 +2,7 @@
# 然后你想修改覆盖修改什么配置,就修改【.config.yaml】文件,而不是修改【config.yaml】文件
# 系统会优先读取【data/.config.yaml】文件的配置,如果【.config.yaml】文件里的配置不存在,系统会自动去读取【config.yaml】文件的配置。
# 这样做,可以最简化配置,保护您的密钥安全。
+# 如果你使用了智控台,那么以下所有配置,都不会生效,请在智控台中修改配置
# #####################################################################################
# #############################以下是服务器基本运行配置####################################
@@ -9,13 +10,21 @@ server:
# 服务器监听地址和端口(Server listening address and port)
ip: 0.0.0.0
port: 8000
- # OTA接口的端口号
- ota_port: 8002
+ # http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口
+ http_port: 8003
# 这个websocket配置是指ota接口向设备发送的websocket地址
- # 如果按默认的写法,ota接口会自动生成websocket地址。这个地址你可以直接用浏览器访问ota接口确认一下
+ # 如果按默认的写法,ota接口会自动生成websocket地址,并输出在启动日志里,这个地址你可以直接用浏览器访问ota接口确认一下
# 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
- # 所以如果你使用docker部署或使用公网部署时,请设置正确的websocket地址
+ # 所以如果你使用docker部署时,将websocket设置成局域网地址
+ # 如果你使用公网部署时,将vwebsocket设置成公网地址
websocket: ws://你的ip或者域名:端口号/xiaozhi/v1/
+ # 视觉分析接口地址
+ # 向设备发送的视觉分析的接口地址
+ # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下
+ # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
+ # 所以如果你使用docker部署时,将vision_explain设置成局域网地址
+ # 如果你使用公网部署时,将vision_explain设置成公网地址
+ vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
# OTA返回信息时区偏移量
timezone_offset: +8
# 认证配置
@@ -110,10 +119,9 @@ plugins:
# 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/
get_news_from_chinanews:
default_rss_url: "https://www.chinanews.com.cn/rss/society.xml"
- category_urls:
- society: "https://www.chinanews.com.cn/rss/society.xml"
- world: "https://www.chinanews.com.cn/rss/world.xml"
- finance: "https://www.chinanews.com.cn/rss/finance.xml"
+ society_rss_url: "https://www.chinanews.com.cn/rss/society.xml"
+ world_rss_url: "https://www.chinanews.com.cn/rss/world.xml"
+ finance_rss_url: "https://www.chinanews.com.cn/rss/finance.xml"
get_news_from_newsnow: {"url": "https://newsnow.busiyi.world/api/s?id="}
home_assistant:
devices:
@@ -162,6 +170,8 @@ selected_module:
ASR: FunASR
# 将根据配置名称对应的type调用实际的LLM适配器
LLM: ChatGLMLLM
+ # 视觉语言大模型
+ VLLM: ChatGLMVLLM
# TTS将根据配置名称对应的type调用实际的TTS适配器
TTS: EdgeTTS
# 记忆模块,默认不开启记忆;如果想使用超长记忆,推荐使用mem0ai;如果注重隐私,请使用本地的mem_local_short
@@ -222,8 +232,12 @@ Memory:
# 不想使用记忆功能,可以使用nomem
type: nomem
mem_local_short:
- # 本地记忆功能,通过selected_module的llm总结,数据保存在本地,不会上传到服务器
+ # 本地记忆功能,通过selected_module的llm总结,数据保存在本地服务器,不会上传到外部服务器
type: mem_local_short
+ # 配备记忆存储独立的思考模型
+ # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型
+ # 如果你的不想使用selected_module.LLM记忆存储,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM
+ llm: ChatGLMLLM
ASR:
FunASR:
@@ -252,6 +266,8 @@ ASR:
DoubaoASR:
# 可以在这里申请相关Key等信息
# https://console.volcengine.com/speech/app
+ # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费
+ # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
type: doubao
appid: 你的火山引擎语音合成服务appid
access_token: 你的火山引擎语音合成服务access_token
@@ -260,6 +276,20 @@ ASR:
boosting_table_name: (选填)你的热词文件名称
correct_table_name: (选填)你的替换词文件名称
output_dir: tmp/
+ DoubaoStreamASR:
+ # 可以在这里申请相关Key等信息
+ # https://console.volcengine.com/speech/app
+ # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费
+ # 开通地址https://console.volcengine.com/speech/service/10011
+ # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
+ type: doubao_stream
+ appid: 你的火山引擎语音合成服务appid
+ access_token: 你的火山引擎语音合成服务access_token
+ cluster: volcengine_input_common
+ # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
+ boosting_table_name: (选填)你的热词文件名称
+ correct_table_name: (选填)你的替换词文件名称
+ output_dir: tmp/
TencentASR:
# token申请地址:https://console.cloud.tencent.com/cam/capi
# 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle
@@ -296,7 +326,7 @@ VAD:
type: silero
threshold: 0.5
model_dir: models/snakers4_silero-vad
- min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些
+ min_silence_duration_ms: 200 # 如果说话停顿比较长,可以把这个值设置大一些
LLM:
# 所有openai类型均可以修改超参,以AliLLM为例
@@ -329,7 +359,7 @@ LLM:
# 定义LLM API类型
type: openai
# 先开通服务,打开以下网址,开通的服务搜索Doubao-1.5-pro,开通它
- # 开通改地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false
+ # 开通地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false
# 免费额度500000token
# 开通后,进入这里获取密钥:https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D
base_url: https://ark.cn-beijing.volces.com/api/v3
@@ -415,7 +445,7 @@ LLM:
base_url: https://host/api/v1
# 你可以在这里找到你的api_key
# https://cloud.tryfastgpt.ai/account/apikey
- api_key: fastgpt-xxx
+ api_key: 你的fastgpt密钥
variables:
k: "v"
k2: "v2"
@@ -431,6 +461,21 @@ LLM:
# Xinference服务地址和模型名称
model_name: qwen2.5:3b-AWQ # 使用的小模型名称,用于意图识别
base_url: http://localhost:9997 # Xinference服务地址
+# VLLM配置(视觉语言大模型)
+VLLM:
+ ChatGLMVLLM:
+ type: openai
+ # glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key
+ # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
+ model_name: glm-4v-flash # 智谱AI的视觉模型
+ url: https://open.bigmodel.cn/api/paas/v4/
+ api_key: 你的api_key
+ QwenVLVLLM:
+ type: openai
+ model_name: qwen2.5-vl-3b-instruct
+ url: https://dashscope.aliyuncs.com/compatible-mode/v1
+ # 可在这里找到你的api key https://bailian.console.aliyun.com/?apiKey=1#/api-key
+ api_key: 你的api_key
TTS:
# 当前支持的type为edge、doubao,可自行适配
EdgeTTS:
@@ -456,6 +501,19 @@ TTS:
speed_ratio: 1.0
volume_ratio: 1.0
pitch_ratio: 1.0
+ #火山tts,支持双向流式tts
+ HuoshanDoubleStreamTTS:
+ type: huoshan_double_stream
+ # 访问 https://console.volcengine.com/speech/service/10007 开通语音合成大模型,购买音色
+ # 在页面底部获取appid和access_token
+ # 资源ID固定为:volc.service_type.10029(大模型语音合成及混音)
+ # 如果是机智云,把接口地址换成wss://bytedance.gizwitsapi.com/api/v3/tts/bidirection
+ # 机智云不需要天填 appid
+ ws_url: wss://openspeech.bytedance.com/api/v3/tts/bidirection
+ appid: 你的火山引擎语音合成服务appid
+ access_token: 你的火山引擎语音合成服务access_token
+ resource_id: volc.service_type.10029
+ speaker: zh_female_wanwanxiaohe_moon_bigtts
CosyVoiceSiliconflow:
type: siliconflow
# 硅基流动TTS
@@ -679,17 +737,40 @@ TTS:
speed: 1
output_dir: tmp/
CustomTTS:
- # 自定义的TTS接口服务,请求参数可自定义
- # 要求接口使用GET方式请求,并返回音频文件
+ # 自定义的TTS接口服务,请求参数可自定义,可接入众多TTS服务
+ # 以本地部署的KokoroTTS为例
+ # 如果只有cpu运行:docker run -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-cpu:latest
+ # 如果只有gpu运行:docker run --gpus all -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-gpu:latest
+ # 要求接口使用POST方式请求,并返回音频文件
type: custom
- url: "http://127.0.0.1:9880/tts"
+ method: POST
+ url: "http://127.0.0.1:8880/v1/audio/speech"
params: # 自定义请求参数
- # text: "{prompt_text}" # {prompt_text}会被替换为实际的提示词内容
- # speaker: jok老师
- # speed: 1
- # foo: bar
- # testabc: 123456
+ input: "{prompt_text}"
+ response_format: "mp3"
+ download_format: "mp3"
+ voice: "zf_xiaoxiao"
+ lang_code: "z"
+ return_download_link: true
+ speed: 1
+ stream: false
headers: # 自定义请求头
# Authorization: Bearer xxxx
+<<<<<<< HEAD
format: wav # 接口返回的音频格式
output_dir: tmp/
+=======
+ format: mp3 # 接口返回的音频格式
+ output_dir: tmp/
+ LinkeraiTTS:
+ type: linkerai
+ api_url: https://tts.linkerai.cn/tts
+ audio_format: "pcm"
+ # 默认的access_token供大家测试时免费使用的,此access_token请勿用于商业用途
+ # 如果效果不错,可自行申请token,申请地址:https://linkerai.cn
+ # 各参数意义见开发文档:https://tts.linkerai.cn/docs
+ # 支持声音克隆,可自行上传音频,填入voice参数,voice参数为空时,使用默认声音
+ access_token: "U4YdYXVfpwWnk2t5Gp822zWPCuORyeJL"
+ voice: "OUeAo1mhq6IBExi"
+ output_dir: tmp/
+>>>>>>> 8c1a8f7d559e57ac726db3fd6ebb38d867475444
diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py
index 35802a67c..b1b45f07f 100644
--- a/main/xiaozhi-server/config/config_loader.py
+++ b/main/xiaozhi-server/config/config_loader.py
@@ -59,10 +59,14 @@ def get_config_from_api(config):
"url": config["manager-api"].get("url", ""),
"secret": config["manager-api"].get("secret", ""),
}
+ # server的配置以本地为准
if config.get("server"):
config_data["server"] = {
"ip": config["server"].get("ip", ""),
"port": config["server"].get("port", ""),
+ "http_port": config["server"].get("http_port", ""),
+ "vision_explain": config["server"].get("vision_explain", ""),
+ "auth_key": config["server"].get("auth_key", ""),
}
return config_data
@@ -82,6 +86,8 @@ def ensure_directories(config):
# ASR/TTS模块输出目录
for module in ["ASR", "TTS"]:
+ if config.get(module) is None:
+ continue
for provider in config.get(module, {}).values():
output_dir = provider.get("output_dir", "")
if output_dir:
@@ -93,6 +99,10 @@ def ensure_directories(config):
selected_provider = selected_modules.get(module_type)
if not selected_provider:
continue
+ if config.get(module) is None:
+ continue
+ if config.get(selected_provider) is None:
+ continue
provider_config = config.get(module_type, {}).get(selected_provider, {})
output_dir = provider_config.get("output_dir")
if output_dir:
diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py
index 5588e00fc..1cc947461 100644
--- a/main/xiaozhi-server/config/logger.py
+++ b/main/xiaozhi-server/config/logger.py
@@ -3,8 +3,10 @@ import sys
from loguru import logger
from config.config_loader import load_config
from config.settings import check_config_file
+from datetime import datetime
-SERVER_VERSION = "0.4.4"
+SERVER_VERSION = "0.5.8"
+_logger_initialized = False
def get_module_abbreviation(module_name, module_dict):
@@ -43,41 +45,129 @@ def setup_logging():
"""从配置文件中读取日志配置,并设置日志输出格式和级别"""
config = load_config()
log_config = config["log"]
- log_format = log_config.get(
- "log_format",
- "
{time:YYMMDD HH:mm:ss}[{version}_{selected_module}][
{extra[tag]}]-
{level}-
{message}",
- )
- log_format_file = log_config.get(
- "log_format_file",
- "{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}",
- )
- selected_module_str = build_module_string(config.get("selected_module", {}))
+ global _logger_initialized
- log_format = log_format.replace("{version}", SERVER_VERSION)
- log_format = log_format.replace("{selected_module}", selected_module_str)
- log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
- log_format_file = log_format_file.replace("{selected_module}", selected_module_str)
+ # 第一次初始化时配置日志
+ if not _logger_initialized:
+ logger.configure(
+ extra={
+ "selected_module": log_config.get("selected_module", "00000000000000")
+ }
+ ) # 新增配置
+ log_format = log_config.get(
+ "log_format",
+ "
{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][
{extra[tag]}]-
{level}-
{message}",
+ )
+ log_format_file = log_config.get(
+ "log_format_file",
+ "{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}",
+ )
+ selected_module_str = logger._core.extra["selected_module"]
- log_level = log_config.get("log_level", "INFO")
- log_dir = log_config.get("log_dir", "tmp")
- log_file = log_config.get("log_file", "server.log")
- data_dir = log_config.get("data_dir", "data")
+ log_format = log_format.replace("{version}", SERVER_VERSION)
+ log_format = log_format.replace("{selected_module}", selected_module_str)
+ log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
+ log_format_file = log_format_file.replace(
+ "{selected_module}", selected_module_str
+ )
- os.makedirs(log_dir, exist_ok=True)
- os.makedirs(data_dir, exist_ok=True)
+ log_level = log_config.get("log_level", "INFO")
+ log_dir = log_config.get("log_dir", "tmp")
+ log_file = log_config.get("log_file", "server.log")
+ data_dir = log_config.get("data_dir", "data")
- # 配置日志输出
- logger.remove()
+ os.makedirs(log_dir, exist_ok=True)
+ os.makedirs(data_dir, exist_ok=True)
- # 输出到控制台
- logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
+ # 配置日志输出
+ logger.remove()
- # 输出到文件
- logger.add(
- os.path.join(log_dir, log_file),
- format=log_format_file,
- level=log_level,
- filter=formatter,
- )
+ # 输出到控制台
+ logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
+
+ # 输出到文件 - 统一目录,按大小轮转
+ # 日志文件完整路径
+ log_file_path = os.path.join(log_dir, log_file)
+
+ # 添加日志处理器
+ logger.add(
+ log_file_path,
+ format=log_format_file,
+ level=log_level,
+ filter=formatter,
+ rotation="10 MB", # 每个文件最大10MB
+ retention="30 days", # 保留30天
+ compression=None,
+ encoding="utf-8",
+ enqueue=True, # 异步安全
+ backtrace=True,
+ diagnose=True,
+ )
+ _logger_initialized = True # 标记为已初始化
return logger
+
+
+def update_module_string(selected_module_str):
+ """更新模块字符串并重新配置日志处理器"""
+ logger.debug(f"更新日志配置组件")
+ current_module = logger._core.extra["selected_module"]
+
+ if current_module == selected_module_str:
+ logger.debug(f"组件未更改无需更新")
+ return
+
+ try:
+ logger.configure(extra={"selected_module": selected_module_str})
+
+ config = load_config()
+ log_config = config["log"]
+
+ log_format = log_config.get(
+ "log_format",
+ "
{time:YYMMDD HH:mm:ss}[{version}_{extra[selected_module]}][
{extra[tag]}]-
{level}-
{message}",
+ )
+ log_format_file = log_config.get(
+ "log_format_file",
+ "{time:YYYY-MM-DD HH:mm:ss} - {version}_{extra[selected_module]} - {name} - {level} - {extra[tag]} - {message}",
+ )
+
+ log_format = log_format.replace("{version}", SERVER_VERSION)
+ log_format = log_format.replace("{selected_module}", selected_module_str)
+ log_format_file = log_format_file.replace("{version}", SERVER_VERSION)
+ log_format_file = log_format_file.replace(
+ "{selected_module}", selected_module_str
+ )
+
+ logger.remove()
+ logger.add(
+ sys.stdout,
+ format=log_format,
+ level=log_config.get("log_level", "INFO"),
+ filter=formatter,
+ )
+
+ # 更新文件日志配置 - 统一目录,按大小轮转
+ log_dir = log_config.get("log_dir", "tmp")
+ log_file = log_config.get("log_file", "server.log")
+
+ # 日志文件完整路径
+ log_file_path = os.path.join(log_dir, log_file)
+
+ logger.add(
+ log_file_path,
+ format=log_format_file,
+ level=log_config.get("log_level", "INFO"),
+ filter=formatter,
+ rotation="10 MB", # 每个文件最大10MB
+ retention="30 days", # 保留30天
+ compression=None,
+ encoding="utf-8",
+ enqueue=True, # 异步安全
+ backtrace=True,
+ diagnose=True,
+ )
+
+ except Exception as e:
+ logger.error(f"日志配置更新失败: {str(e)}")
+ raise
diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py
index 11e0ecbe7..cd3f86c42 100644
--- a/main/xiaozhi-server/config/manage_api_client.py
+++ b/main/xiaozhi-server/config/manage_api_client.py
@@ -160,7 +160,7 @@ def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[Dict]:
def report(
- mac_address: str, session_id: str, chat_type: int, content: str, audio
+ mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]:
"""带熔断的业务方法示例"""
if not content or not ManageApiClient._instance:
@@ -174,6 +174,7 @@ def report(
"sessionId": session_id,
"chatType": chat_type,
"content": content,
+ "reportTime": report_time,
"audioBase64": (
base64.b64encode(audio).decode("utf-8") if audio else None
),
diff --git a/main/xiaozhi-server/config_from_api.yaml b/main/xiaozhi-server/config_from_api.yaml
index 15962bb65..ad936ec11 100644
--- a/main/xiaozhi-server/config_from_api.yaml
+++ b/main/xiaozhi-server/config_from_api.yaml
@@ -8,6 +8,15 @@
server:
ip: 0.0.0.0
port: 8000
+ # http服务的端口,用于视觉分析接口
+ http_port: 8003
+ # 视觉分析接口地址
+ # 向设备发送的视觉分析的接口地址
+ # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下
+ # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
+ # 所以如果你使用docker部署时,将vision_explain设置成局域网地址
+ # 如果你使用公网部署时,将vision_explain设置成公网地址
+ vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
manager-api:
# 你的manager-api的地址,最好使用局域网ip
url: http://127.0.0.1:8002/xiaozhi
diff --git a/main/xiaozhi-server/core/api/base_handler.py b/main/xiaozhi-server/core/api/base_handler.py
new file mode 100644
index 000000000..7330185e4
--- /dev/null
+++ b/main/xiaozhi-server/core/api/base_handler.py
@@ -0,0 +1,16 @@
+from aiohttp import web
+from config.logger import setup_logging
+
+
+class BaseHandler:
+ def __init__(self, config: dict):
+ self.config = config
+ self.logger = setup_logging()
+
+ def _add_cors_headers(self, response):
+ """添加CORS头信息"""
+ response.headers["Access-Control-Allow-Headers"] = (
+ "client-id, content-type, device-id"
+ )
+ response.headers["Access-Control-Allow-Credentials"] = "true"
+ response.headers["Access-Control-Allow-Origin"] = "*"
diff --git a/main/xiaozhi-server/core/ota_server.py b/main/xiaozhi-server/core/api/ota_handler.py
similarity index 56%
rename from main/xiaozhi-server/core/ota_server.py
rename to main/xiaozhi-server/core/api/ota_handler.py
index 383725d91..763c9c49e 100644
--- a/main/xiaozhi-server/core/ota_server.py
+++ b/main/xiaozhi-server/core/api/ota_handler.py
@@ -1,18 +1,15 @@
import json
import time
-import asyncio
from aiohttp import web
-from config.logger import setup_logging
-from core.connection import ConnectionHandler
-from core.utils.util import get_local_ip, initialize_modules
+from core.utils.util import get_local_ip
+from core.api.base_handler import BaseHandler
TAG = __name__
-class SimpleOtaServer:
+class OTAHandler(BaseHandler):
def __init__(self, config: dict):
- self.config = config
- self.logger = setup_logging()
+ super().__init__(config)
def _get_websocket_url(self, local_ip: str, port: int) -> str:
"""获取websocket地址
@@ -25,41 +22,15 @@ class SimpleOtaServer:
str: websocket地址
"""
server_config = self.config["server"]
- websocket_config = server_config.get("websocket")
+ websocket_config = server_config.get("websocket", "")
- if websocket_config and "你" not in websocket_config:
+ if "你的" not in websocket_config:
return websocket_config
else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
- async def start(self):
- server_config = self.config["server"]
- host = server_config.get("ip", "0.0.0.0")
- port = int(server_config.get("ota_port"))
-
- if port:
- app = web.Application()
- # 添加路由
- app.add_routes(
- [
- web.get("/xiaozhi/ota/", self._handle_ota_get_request),
- web.post("/xiaozhi/ota/", self._handle_ota_request),
- web.options("/xiaozhi/ota/", self._handle_ota_request),
- ]
- )
-
- # 运行服务
- runner = web.AppRunner(app)
- await runner.setup()
- site = web.TCPSite(runner, host, port)
- await site.start()
-
- # 保持服务运行
- while True:
- await asyncio.sleep(3600) # 每隔 1 小时检查一次
-
- async def _handle_ota_request(self, request):
- """处理 /xiaozhi/ota/ 的 POST 请求"""
+ async def handle_post(self, request):
+ """处理 OTA POST 请求"""
try:
data = await request.text()
self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}")
@@ -75,11 +46,9 @@ class SimpleOtaServer:
data_json = json.loads(data)
server_config = self.config["server"]
- host = server_config.get("ip", "0.0.0.0")
port = int(server_config.get("port", 8000))
local_ip = get_local_ip()
- # OTA基础信息
return_json = {
"server_time": {
"timestamp": int(round(time.time() * 1000)),
@@ -98,23 +67,17 @@ class SimpleOtaServer:
content_type="application/json",
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"OTA请求异常: {e}")
return_json = {"success": False, "message": "request error."}
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
)
finally:
- # 添加header,允许跨域访问
- response.headers["Access-Control-Allow-Headers"] = (
- "client-id, content-type, device-id"
- )
- response.headers["Access-Control-Allow-Credentials"] = "true"
- response.headers["Access-Control-Allow-Origin"] = "*"
+ self._add_cors_headers(response)
return response
- async def _handle_ota_get_request(self, request):
- """处理 /xiaozhi/ota/ 的 GET 请求"""
+ async def handle_get(self, request):
+ """处理 OTA GET 请求"""
try:
server_config = self.config["server"]
local_ip = get_local_ip()
@@ -126,10 +89,5 @@ class SimpleOtaServer:
self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}")
response = web.Response(text="OTA接口异常", content_type="text/plain")
finally:
- # 添加header,允许跨域访问
- response.headers["Access-Control-Allow-Headers"] = (
- "client-id, content-type, device-id"
- )
- response.headers["Access-Control-Allow-Credentials"] = "true"
- response.headers["Access-Control-Allow-Origin"] = "*"
+ self._add_cors_headers(response)
return response
diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py
new file mode 100644
index 000000000..70be247af
--- /dev/null
+++ b/main/xiaozhi-server/core/api/vision_handler.py
@@ -0,0 +1,182 @@
+import json
+import copy
+from aiohttp import web
+from config.logger import setup_logging
+from core.utils.util import get_vision_url, is_valid_image_file
+from core.utils.vllm import create_instance
+from config.config_loader import get_private_config_from_api
+from core.utils.auth import AuthToken
+import base64
+from typing import Tuple, Optional
+from plugins_func.register import Action
+
+TAG = __name__
+
+# 设置最大文件大小为5MB
+MAX_FILE_SIZE = 5 * 1024 * 1024
+
+
+class VisionHandler:
+ def __init__(self, config: dict):
+ self.config = config
+ self.logger = setup_logging()
+ # 初始化认证工具
+ self.auth = AuthToken(config["server"]["auth_key"])
+
+ def _create_error_response(self, message: str) -> dict:
+ """创建统一的错误响应格式"""
+ return {"success": False, "message": message}
+
+ def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
+ """验证认证token"""
+ auth_header = request.headers.get("Authorization", "")
+ if not auth_header.startswith("Bearer "):
+ return False, None
+
+ token = auth_header[7:] # 移除"Bearer "前缀
+ return self.auth.verify_token(token)
+
+ async def handle_post(self, request):
+ """处理 MCP Vision POST 请求"""
+ response = None # 初始化response变量
+ try:
+ # 验证token
+ is_valid, token_device_id = self._verify_auth_token(request)
+ if not is_valid:
+ response = web.Response(
+ text=json.dumps(
+ self._create_error_response("无效的认证token或token已过期")
+ ),
+ content_type="application/json",
+ status=401,
+ )
+ return response
+
+ # 获取请求头信息
+ device_id = request.headers.get("Device-Id", "")
+ client_id = request.headers.get("Client-Id", "")
+ if device_id != token_device_id:
+ raise ValueError("设备ID与token不匹配")
+ # 解析multipart/form-data请求
+ reader = await request.multipart()
+
+ # 读取question字段
+ question_field = await reader.next()
+ if question_field is None:
+ raise ValueError("缺少问题字段")
+ question = await question_field.text()
+ self.logger.bind(tag=TAG).debug(f"Question: {question}")
+
+ # 读取图片文件
+ image_field = await reader.next()
+ if image_field is None:
+ raise ValueError("缺少图片文件")
+
+ # 读取图片数据
+ image_data = await image_field.read()
+ if not image_data:
+ raise ValueError("图片数据为空")
+
+ # 检查文件大小
+ if len(image_data) > MAX_FILE_SIZE:
+ raise ValueError(
+ f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB"
+ )
+
+ # 检查文件格式
+ if not is_valid_image_file(image_data):
+ raise ValueError(
+ "不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)"
+ )
+
+ # 将图片转换为base64编码
+ image_base64 = base64.b64encode(image_data).decode("utf-8")
+
+ # 如果开启了智控台,则从智控台获取模型配置
+ current_config = copy.deepcopy(self.config)
+ read_config_from_api = current_config.get("read_config_from_api", False)
+ if read_config_from_api:
+ current_config = get_private_config_from_api(
+ current_config,
+ device_id,
+ client_id,
+ )
+
+ select_vllm_module = current_config["selected_module"].get("VLLM")
+ if not select_vllm_module:
+ raise ValueError("您还未设置默认的视觉分析模块")
+
+ vllm_type = (
+ select_vllm_module
+ if "type" not in current_config["VLLM"][select_vllm_module]
+ else current_config["VLLM"][select_vllm_module]["type"]
+ )
+
+ if not vllm_type:
+ raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}")
+
+ vllm = create_instance(
+ vllm_type, current_config["VLLM"][select_vllm_module]
+ )
+
+ result = vllm.response(question, image_base64)
+
+ return_json = {
+ "success": True,
+ "action": Action.RESPONSE.name,
+ "response": result,
+ }
+
+ response = web.Response(
+ text=json.dumps(return_json, separators=(",", ":")),
+ content_type="application/json",
+ )
+ except ValueError as e:
+ self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
+ return_json = self._create_error_response(str(e))
+ response = web.Response(
+ text=json.dumps(return_json, separators=(",", ":")),
+ content_type="application/json",
+ )
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
+ return_json = self._create_error_response("处理请求时发生错误")
+ response = web.Response(
+ text=json.dumps(return_json, separators=(",", ":")),
+ content_type="application/json",
+ )
+ finally:
+ if response:
+ self._add_cors_headers(response)
+ return response
+
+ async def handle_get(self, request):
+ """处理 MCP Vision GET 请求"""
+ try:
+ vision_explain = get_vision_url(self.config)
+ if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
+ message = (
+ f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}"
+ )
+ else:
+ message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址"
+
+ response = web.Response(text=message, content_type="text/plain")
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}")
+ return_json = self._create_error_response("服务器内部错误")
+ response = web.Response(
+ text=json.dumps(return_json, separators=(",", ":")),
+ content_type="application/json",
+ )
+ finally:
+ self._add_cors_headers(response)
+ return response
+
+ def _add_cors_headers(self, response):
+ """添加CORS头信息"""
+ response.headers["Access-Control-Allow-Headers"] = (
+ "client-id, content-type, device-id"
+ )
+ response.headers["Access-Control-Allow-Credentials"] = "true"
+ response.headers["Access-Control-Allow-Origin"] = "*"
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 0abb3cec1..3ad945923 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -1,39 +1,44 @@
import os
+import sys
import copy
import json
-import subprocess
-import sys
import uuid
import time
import queue
import asyncio
-import traceback
-
import threading
+import traceback
+import subprocess
import websockets
-from typing import Dict, Any
-from plugins_func.loadplugins import auto_import_modules
-from config.logger import setup_logging
-from core.utils.dialogue import Message, Dialogue
-from core.handle.textHandle import handleTextMessage
+from core.handle.mcpHandle import call_mcp_tool
from core.utils.util import (
- get_string_no_punctuation_or_emoji,
extract_json_from_string,
- initialize_modules,
check_vad_update,
check_asr_update,
+ filter_sensitive_info,
)
-from concurrent.futures import ThreadPoolExecutor, TimeoutError
-from core.handle.sendAudioHandle import sendAudioMessage
-from core.handle.receiveAudioHandle import handleAudioMessage
+from typing import Dict, Any
+from core.mcp.manager import MCPManager
+from core.utils.modules_initialize import (
+ initialize_modules,
+ initialize_tts,
+ initialize_asr,
+)
+from core.handle.reportHandle import report
+from core.providers.tts.default import DefaultTTS
+from concurrent.futures import ThreadPoolExecutor
+from core.utils.dialogue import Message, Dialogue
+from core.providers.asr.dto.dto import InterfaceType
+from core.handle.textHandle import handleTextMessage
from core.handle.functionHandler import FunctionHandler
+from plugins_func.loadplugins import auto_import_modules
from plugins_func.register import Action, ActionResponse
from core.auth import AuthMiddleware, AuthenticationError
-from core.mcp.manager import MCPManager
from config.config_loader import get_private_config_from_api
+from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
+from config.logger import setup_logging, build_module_string, update_module_string
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
-from core.utils.output_counter import add_device_output
-from core.handle.reportHandle import enqueue_tts_report, report
+
TAG = __name__
@@ -51,7 +56,6 @@ class ConnectionHandler:
_vad,
_asr,
_llm,
- _tts,
_memory,
_intent,
server=None,
@@ -76,32 +80,32 @@ class ConnectionHandler:
self.welcome_msg = None
self.max_output_size = 0
self.chat_history_conf = 0
+ self.audio_format = "opus"
# 客户端状态相关
self.client_abort = False
+ self.client_is_speaking = False
self.client_listen_mode = "auto"
# 线程任务相关
self.loop = asyncio.get_event_loop()
self.stop_event = threading.Event()
- self.tts_queue = queue.Queue()
- self.audio_play_queue = queue.Queue()
- self.executor = ThreadPoolExecutor(max_workers=10)
+ self.executor = ThreadPoolExecutor(max_workers=5)
- # 上报线程
+ # 添加上报线程池
self.report_queue = queue.Queue()
self.report_thread = None
- # TODO(haotian): 2025/5/12 可以通过修改此处,调节asr的上报和tts的上报
+ # 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启
self.report_asr_enable = self.read_config_from_api
self.report_tts_enable = self.read_config_from_api
# 依赖的组件
self.vad = None
self.asr = None
+ self.tts = None
self._asr = _asr
self._vad = _vad
self.llm = _llm
- self.tts = _tts
self.memory = _memory
self.intent = _intent
@@ -111,18 +115,20 @@ class ConnectionHandler:
self.client_have_voice_last_time = 0.0
self.client_no_voice_last_time = 0.0
self.client_voice_stop = False
+ self.client_voice_frame_count = 0
# asr相关变量
+ # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
+ # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量
self.asr_audio = []
- self.asr_server_receive = True
+ self.asr_audio_queue = queue.Queue()
# llm相关变量
- self.llm_finish_task = False
+ self.llm_finish_task = True
self.dialogue = Dialogue()
# tts相关变量
- self.tts_first_text_index = -1
- self.tts_last_text_index = -1
+ self.sentence_id = None
# iot相关变量
self.iot_descriptors = {}
@@ -144,7 +150,8 @@ class ConnectionHandler:
int(self.config.get("close_connection_no_voice_time", 120)) + 60
) # 在原来第一道关闭的基础上加60秒,进行二道关闭
- self.audio_format = "opus"
+ # {"mcp":true} 表示启用MCP功能
+ self.features = None
async def handle_connection(self, ws):
try:
@@ -193,17 +200,6 @@ class ConnectionHandler:
self._initialize_private_config()
# 异步初始化
self.executor.submit(self._initialize_components)
- # tts 消化线程
- self.tts_priority_thread = threading.Thread(
- target=self._tts_priority_thread, daemon=True
- )
- self.tts_priority_thread.start()
-
- # 音频播放 消化线程
- self.audio_play_priority_thread = threading.Thread(
- target=self._audio_play_priority_thread, daemon=True
- )
- self.audio_play_priority_thread.start()
try:
async for message in self.websocket:
@@ -261,7 +257,11 @@ class ConnectionHandler:
if isinstance(message, str):
await handleTextMessage(self, message)
elif isinstance(message, bytes):
- await handleAudioMessage(self, message)
+ if self.vad is None:
+ return
+ if self.asr is None:
+ return
+ self.asr_audio_queue.put(message)
async def handle_restart(self, message):
"""处理服务器重启请求"""
@@ -273,9 +273,10 @@ class ConnectionHandler:
await self.websocket.send(
json.dumps(
{
- "type": "server_response",
+ "type": "server",
"status": "success",
"message": "服务器重启中...",
+ "content": {"action": "restart"},
}
)
)
@@ -302,33 +303,52 @@ class ConnectionHandler:
await self.websocket.send(
json.dumps(
{
- "type": "server_response",
+ "type": "server",
"status": "error",
"message": f"Restart failed: {str(e)}",
+ "content": {"action": "restart"},
}
)
)
def _initialize_components(self):
- """初始化组件"""
- if self.config.get("prompt") is not None:
- self.prompt = self.config["prompt"]
- self.change_system_prompt(self.prompt)
- self.logger.bind(tag=TAG).info(
- f"初始化组件: prompt成功 {self.prompt[:50]}..."
+ try:
+ self.selected_module_str = build_module_string(
+ self.config.get("selected_module", {})
+ )
+ update_module_string(self.selected_module_str)
+ """初始化组件"""
+ if self.config.get("prompt") is not None:
+ self.prompt = self.config["prompt"]
+ self.change_system_prompt(self.prompt)
+ self.logger.bind(tag=TAG).info(
+ f"初始化组件: prompt成功 {self.prompt[:50]}..."
+ )
+
+ """初始化本地组件"""
+ if self.vad is None:
+ self.vad = self._vad
+ if self.asr is None:
+ self.asr = self._initialize_asr()
+ # 打开语音识别通道
+ asyncio.run_coroutine_threadsafe(
+ self.asr.open_audio_channels(self), self.loop
+ )
+ if self.tts is None:
+ self.tts = self._initialize_tts()
+ # 打开语音合成通道
+ asyncio.run_coroutine_threadsafe(
+ self.tts.open_audio_channels(self), self.loop
)
- """初始化本地组件"""
- if self.vad is None:
- self.vad = self._vad
- if self.asr is None:
- self.asr = self._asr
- """加载记忆"""
- self._initialize_memory()
- """加载意图识别"""
- self._initialize_intent()
- """初始化上报线程"""
- self._init_report_threads()
+ """加载记忆"""
+ self._initialize_memory()
+ """加载意图识别"""
+ self._initialize_intent()
+ """初始化上报线程"""
+ self._init_report_threads()
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
def _init_report_threads(self):
"""初始化ASR和TTS上报线程"""
@@ -343,6 +363,30 @@ class ConnectionHandler:
self.report_thread.start()
self.logger.bind(tag=TAG).info("TTS上报线程已启动")
+ def _initialize_tts(self):
+ """初始化TTS"""
+ tts = None
+ if not self.need_bind:
+ tts = initialize_tts(self.config)
+
+ if tts is None:
+ tts = DefaultTTS(self.config, delete_audio_file=True)
+
+ return tts
+
+ def _initialize_asr(self):
+ """初始化ASR"""
+ if self._asr.interface_type == InterfaceType.LOCAL:
+ # 如果公共ASR是本地服务,则直接返回
+ # 因为本地一个实例ASR,可以被多个连接共享
+ asr = self._asr
+ else:
+ # 如果公共ASR是远程服务,则初始化一个新实例
+ # 因为远程ASR,涉及到websocket连接和接收线程,需要每个连接一个实例
+ asr = initialize_asr(self.config)
+
+ return asr
+
def _initialize_private_config(self):
"""如果是从配置文件获取,则进行二次实例化"""
if not self.read_config_from_api:
@@ -381,6 +425,16 @@ class ConnectionHandler:
init_vad = check_vad_update(self.common_config, private_config)
init_asr = check_asr_update(self.common_config, private_config)
+ if init_vad:
+ self.config["VAD"] = private_config["VAD"]
+ self.config["selected_module"]["VAD"] = private_config["selected_module"][
+ "VAD"
+ ]
+ if init_asr:
+ self.config["ASR"] = private_config["ASR"]
+ self.config["selected_module"]["ASR"] = private_config["selected_module"][
+ "ASR"
+ ]
if private_config.get("TTS", None) is not None:
init_tts = True
self.config["TTS"] = private_config["TTS"]
@@ -402,9 +456,17 @@ class ConnectionHandler:
if private_config.get("Intent", None) is not None:
init_intent = True
self.config["Intent"] = private_config["Intent"]
- self.config["selected_module"]["Intent"] = private_config[
- "selected_module"
- ]["Intent"]
+ model_intent = private_config.get("selected_module", {}).get("Intent", {})
+ self.config["selected_module"]["Intent"] = model_intent
+ # 加载插件配置
+ if model_intent != "Intent_nointent":
+ plugin_from_server = private_config.get("plugins", {})
+ for plugin, config_str in plugin_from_server.items():
+ plugin_from_server[plugin] = json.loads(config_str)
+ self.config["plugins"] = plugin_from_server
+ self.config["Intent"][self.config["selected_module"]["Intent"]][
+ "functions"
+ ] = plugin_from_server.keys()
if private_config.get("prompt", None) is not None:
self.config["prompt"] = private_config["prompt"]
if private_config.get("summaryMemory", None) is not None:
@@ -441,6 +503,8 @@ class ConnectionHandler:
self.memory = modules["memory"]
def _initialize_memory(self):
+ if self.memory is None:
+ return
"""初始化记忆模块"""
self.memory.init_memory(
role_id=self.device_id,
@@ -449,7 +513,40 @@ class ConnectionHandler:
save_to_file=not self.read_config_from_api,
)
+ # 获取记忆总结配置
+ memory_config = self.config["Memory"]
+ memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
+ "type"
+ ]
+ # 如果使用 nomen,直接返回
+ if memory_type == "nomem":
+ return
+ # 使用 mem_local_short 模式
+ elif memory_type == "mem_local_short":
+ memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
+ "llm"
+ ]
+ if memory_llm_name and memory_llm_name in self.config["LLM"]:
+ # 如果配置了专用LLM,则创建独立的LLM实例
+ from core.utils import llm as llm_utils
+
+ memory_llm_config = self.config["LLM"][memory_llm_name]
+ memory_llm_type = memory_llm_config.get("type", memory_llm_name)
+ memory_llm = llm_utils.create_instance(
+ memory_llm_type, memory_llm_config
+ )
+ self.logger.bind(tag=TAG).info(
+ f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}"
+ )
+ self.memory.set_llm(memory_llm)
+ else:
+ # 否则使用主LLM
+ self.memory.set_llm(self.llm)
+ self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
+
def _initialize_intent(self):
+ if self.intent is None:
+ return
self.intent_type = self.config["Intent"][
self.config["selected_module"]["Intent"]
]["type"]
@@ -503,106 +600,26 @@ class ConnectionHandler:
# 更新系统prompt至上下文
self.dialogue.update_system_message(self.prompt)
- def chat(self, query):
-
- self.dialogue.put(Message(role="user", content=query))
-
- response_message = []
- processed_chars = 0 # 跟踪已处理的字符位置
- try:
- # 使用带记忆的对话
- memory_str = None
- if self.memory is not None:
- future = asyncio.run_coroutine_threadsafe(
- self.memory.query_memory(query), self.loop
- )
- memory_str = future.result()
-
- self.logger.bind(tag=TAG).debug(f"记忆内容: {memory_str}")
- llm_responses = self.llm.response(
- self.session_id, self.dialogue.get_llm_dialogue_with_memory(memory_str)
- )
- except Exception as e:
- self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
- return None
-
+ def chat(self, query, tool_call=False):
+ self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
self.llm_finish_task = False
- text_index = 0
- for content in llm_responses:
- response_message.append(content)
- if self.client_abort:
- break
-
- # 合并当前全部文本并处理未分割部分
- full_text = "".join(response_message)
- current_text = full_text[processed_chars:] # 从未处理的位置开始
-
- # 查找最后一个有效标点
- punctuations = ("。", ".", "?", "?", "!", "!", ";", ";", ":")
- last_punct_pos = -1
- number_flag = True
- for punct in punctuations:
- pos = current_text.rfind(punct)
- prev_char = current_text[pos - 1] if pos - 1 >= 0 else ""
- # 如果.前面是数字统一判断为小数
- if prev_char.isdigit() and punct == ".":
- number_flag = False
- if pos > last_punct_pos and number_flag:
- last_punct_pos = pos
-
- # 找到分割点则处理
- if last_punct_pos != -1:
- segment_text_raw = current_text[: last_punct_pos + 1]
- segment_text = get_string_no_punctuation_or_emoji(segment_text_raw)
- if segment_text:
- # 强制设置空字符,测试TTS出错返回语音的健壮性
- # if text_index % 2 == 0:
- # segment_text = " "
- text_index += 1
- self.recode_first_last_text(segment_text, text_index)
- future = self.executor.submit(
- self.speak_and_play, segment_text, text_index
- )
- self.tts_queue.put((future, text_index))
- processed_chars += len(segment_text_raw) # 更新已处理字符位置
-
- # 处理最后剩余的文本
- full_text = "".join(response_message)
- remaining_text = full_text[processed_chars:]
- if remaining_text:
- segment_text = get_string_no_punctuation_or_emoji(remaining_text)
- if segment_text:
- text_index += 1
- self.recode_first_last_text(segment_text, text_index)
- future = self.executor.submit(
- self.speak_and_play, segment_text, text_index
- )
- self.tts_queue.put((future, text_index))
-
- self.llm_finish_task = True
- self.dialogue.put(Message(role="assistant", content="".join(response_message)))
- self.logger.bind(tag=TAG).debug(
- json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)
- )
- return True
-
- def chat_with_function_calling(self, query, tool_call=False):
- self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}")
- """Chat with function calling for intent detection using streaming"""
if not tool_call:
self.dialogue.put(Message(role="user", content=query))
# Define intent functions
functions = None
- if hasattr(self, "func_handler"):
+ if self.intent_type == "function_call" and hasattr(self, "func_handler"):
functions = self.func_handler.get_functions()
+ if hasattr(self, "mcp_client"):
+ mcp_tools = self.mcp_client.get_available_tools()
+ if mcp_tools is not None and len(mcp_tools) > 0:
+ if functions is None:
+ functions = []
+ functions.extend(mcp_tools)
response_message = []
- processed_chars = 0 # 跟踪已处理的字符位置
try:
- start_time = time.time()
-
# 使用带记忆的对话
memory_str = None
if self.memory is not None:
@@ -611,94 +628,78 @@ class ConnectionHandler:
)
memory_str = future.result()
- # self.logger.bind(tag=TAG).info(f"对话记录: {self.dialogue.get_llm_dialogue_with_memory(memory_str)}")
+ self.sentence_id = str(uuid.uuid4().hex)
- # 使用支持functions的streaming接口
- llm_responses = self.llm.response_with_functions(
- self.session_id,
- self.dialogue.get_llm_dialogue_with_memory(memory_str),
- functions=functions,
- )
+
+ if self.intent_type == "function_call" and functions is not None:
+ # 使用支持functions的streaming接口
+ llm_responses = self.llm.response_with_functions(
+ self.session_id,
+ self.dialogue.get_llm_dialogue_with_memory(memory_str),
+ functions=functions,
+ )
+ else:
+ llm_responses = self.llm.response(
+ self.session_id,
+ self.dialogue.get_llm_dialogue_with_memory(memory_str),
+ )
except Exception as e:
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
return None
- self.llm_finish_task = False
- text_index = 0
-
# 处理流式响应
tool_call_flag = False
function_name = None
function_id = None
function_arguments = ""
content_arguments = ""
-
+ text_index = 0
+ self.client_abort = False
for response in llm_responses:
- content, tools_call = response
+ if self.client_abort:
+ break
+ if self.intent_type == "function_call" and functions is not None:
+ content, tools_call = response
+ if "content" in response:
+ content = response["content"]
+ tools_call = None
+ if content is not None and len(content) > 0:
+ content_arguments += content
- if "content" in response:
- content = response["content"]
- tools_call = None
- if content is not None and len(content) > 0:
- content_arguments += content
-
- if not tool_call_flag and content_arguments.startswith("
"):
- # print("content_arguments", content_arguments)
- tool_call_flag = True
-
- if tools_call is not None:
- tool_call_flag = True
- if tools_call[0].id is not None:
- function_id = tools_call[0].id
- if tools_call[0].function.name is not None:
- function_name = tools_call[0].function.name
- if tools_call[0].function.arguments is not None:
- function_arguments += tools_call[0].function.arguments
+ if not tool_call_flag and content_arguments.startswith(""):
+ # print("content_arguments", content_arguments)
+ tool_call_flag = True
+ if tools_call is not None and len(tools_call) > 0:
+ tool_call_flag = True
+ if tools_call[0].id is not None:
+ function_id = tools_call[0].id
+ if tools_call[0].function.name is not None:
+ function_name = tools_call[0].function.name
+ if tools_call[0].function.arguments is not None:
+ function_arguments += tools_call[0].function.arguments
+ else:
+ content = response
if content is not None and len(content) > 0:
if not tool_call_flag:
response_message.append(content)
-
- if self.client_abort:
- break
-
- end_time = time.time()
- # self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}")
-
- # 处理文本分段和TTS逻辑
- # 合并当前全部文本并处理未分割部分
- full_text = "".join(response_message)
- current_text = full_text[processed_chars:] # 从未处理的位置开始
-
- # 查找最后一个有效标点
- punctuations = ("。", ".", "?", "?", "!", "!", ";", ";", ":")
- last_punct_pos = -1
- number_flag = True
- for punct in punctuations:
- pos = current_text.rfind(punct)
- prev_char = current_text[pos - 1] if pos - 1 >= 0 else ""
- # 如果.前面是数字统一判断为小数
- if prev_char.isdigit() and punct == ".":
- number_flag = False
- if pos > last_punct_pos and number_flag:
- last_punct_pos = pos
-
- # 找到分割点则处理
- if last_punct_pos != -1:
- segment_text_raw = current_text[: last_punct_pos + 1]
- segment_text = get_string_no_punctuation_or_emoji(
- segment_text_raw
- )
- if segment_text:
- text_index += 1
- self.recode_first_last_text(segment_text, text_index)
- future = self.executor.submit(
- self.speak_and_play, segment_text, text_index
+ if text_index == 0:
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.FIRST,
+ content_type=ContentType.ACTION,
)
- self.tts_queue.put((future, text_index))
- # 更新已处理字符位置
- processed_chars += len(segment_text_raw)
-
+ )
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.MIDDLE,
+ content_type=ContentType.TEXT,
+ content_detail=content,
+ )
+ )
+ text_index += 1
# 处理function call
if tool_call_flag:
bHasError = False
@@ -733,35 +734,74 @@ class ConnectionHandler:
"arguments": function_arguments,
}
- # 处理MCP工具调用
+ # 处理Server端MCP工具调用
if self.mcp_manager.is_mcp_tool(function_name):
result = self._handle_mcp_tool_call(function_call_data)
+ elif hasattr(self, "mcp_client") and self.mcp_client.has_tool(
+ function_name
+ ):
+ # 如果是小智端MCP工具调用
+ self.logger.bind(tag=TAG).debug(
+ f"调用小智端MCP工具: {function_name}, 参数: {function_arguments}"
+ )
+ try:
+ result = asyncio.run_coroutine_threadsafe(
+ call_mcp_tool(
+ self, self.mcp_client, function_name, function_arguments
+ ),
+ self.loop,
+ ).result()
+ self.logger.bind(tag=TAG).debug(f"MCP工具调用结果: {result}")
+
+ resultJson = None
+ if isinstance(result, str):
+ try:
+ resultJson = json.loads(result)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(
+ f"解析MCP工具返回结果失败: {e}"
+ )
+
+ # 视觉大模型不经过二次LLM处理
+ if (
+ resultJson is not None
+ and isinstance(resultJson, dict)
+ and "action" in resultJson
+ ):
+ result = ActionResponse(
+ action=Action[resultJson["action"]],
+ result=None,
+ response=resultJson.get("response", ""),
+ )
+ else:
+ result = ActionResponse(
+ action=Action.REQLLM, result=result, response=""
+ )
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"MCP工具调用失败: {e}")
+ result = ActionResponse(
+ action=Action.REQLLM, result="MCP工具调用失败", response=""
+ )
else:
# 处理系统函数
result = self.func_handler.handle_llm_function_call(
self, function_call_data
)
- self._handle_function_result(result, function_call_data, text_index + 1)
-
- # 处理最后剩余的文本
- full_text = "".join(response_message)
- remaining_text = full_text[processed_chars:]
- if remaining_text:
- segment_text = get_string_no_punctuation_or_emoji(remaining_text)
- if segment_text:
- text_index += 1
- self.recode_first_last_text(segment_text, text_index)
- future = self.executor.submit(
- self.speak_and_play, segment_text, text_index
- )
- self.tts_queue.put((future, text_index))
+ self._handle_function_result(result, function_call_data)
# 存储对话内容
if len(response_message) > 0:
self.dialogue.put(
Message(role="assistant", content="".join(response_message))
)
-
+ if text_index > 0:
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.ACTION,
+ )
+ )
self.llm_finish_task = True
self.logger.bind(tag=TAG).debug(
json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)
@@ -811,12 +851,10 @@ class ConnectionHandler:
return ActionResponse(action=Action.REQLLM, result="工具调用出错", response="")
- def _handle_function_result(self, result, function_call_data, text_index):
+ def _handle_function_result(self, result, function_call_data):
if result.action == Action.RESPONSE: # 直接回复前端
text = result.response
- self.recode_first_last_text(text, text_index)
- future = self.executor.submit(self.speak_and_play, text, text_index)
- self.tts_queue.put((future, text_index))
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
self.dialogue.put(Message(role="assistant", content=text))
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
text = result.result
@@ -850,111 +888,14 @@ class ConnectionHandler:
content=text,
)
)
- self.chat_with_function_calling(text, tool_call=True)
+ self.chat(text, tool_call=True)
elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
text = result.result
- self.recode_first_last_text(text, text_index)
- future = self.executor.submit(self.speak_and_play, text, text_index)
- self.tts_queue.put((future, text_index))
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
self.dialogue.put(Message(role="assistant", content=text))
else:
pass
- def _tts_priority_thread(self):
- while not self.stop_event.is_set():
- text = None
- try:
- try:
- item = self.tts_queue.get(timeout=1)
- if item is None:
- continue
- future, text_index = item # 解包获取 Future 和 text_index
- except queue.Empty:
- if self.stop_event.is_set():
- break
- continue
- if future is None:
- continue
- text = None
- audio_datas, tts_file = [], None
- try:
- self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
- tts_timeout = int(self.config.get("tts_timeout", 10))
- tts_file, text, _ = future.result(timeout=tts_timeout)
- if text is None or len(text) <= 0:
- self.logger.bind(tag=TAG).error(
- f"TTS出错:{text_index}: tts text is empty"
- )
- elif tts_file is None:
- self.logger.bind(tag=TAG).error(
- f"TTS出错: file is empty: {text_index}: {text}"
- )
- else:
- self.logger.bind(tag=TAG).debug(
- f"TTS生成:文件路径: {tts_file}"
- )
- if os.path.exists(tts_file):
- if self.audio_format == "pcm":
- audio_datas, _ = self.tts.audio_to_pcm_data(tts_file)
- else:
- audio_datas, _ = self.tts.audio_to_opus_data(tts_file)
- # 在这里上报TTS数据
- enqueue_tts_report(self, text, audio_datas)
- else:
- self.logger.bind(tag=TAG).error(
- f"TTS出错:文件不存在{tts_file}"
- )
- except TimeoutError:
- self.logger.bind(tag=TAG).error("TTS超时")
- except Exception as e:
- self.logger.bind(tag=TAG).error(f"TTS出错: {e}")
- if not self.client_abort:
- # 如果没有中途打断就发送语音
- self.audio_play_queue.put((audio_datas, text, text_index))
- if (
- self.tts.delete_audio_file
- and tts_file is not None
- and os.path.exists(tts_file)
- ):
- os.remove(tts_file)
- except Exception as e:
- self.logger.bind(tag=TAG).error(f"TTS任务处理错误: {e}")
- self.clearSpeakStatus()
- asyncio.run_coroutine_threadsafe(
- self.websocket.send(
- json.dumps(
- {
- "type": "tts",
- "state": "stop",
- "session_id": self.session_id,
- }
- )
- ),
- self.loop,
- )
- self.logger.bind(tag=TAG).error(
- f"tts_priority priority_thread: {text} {e}"
- )
-
- def _audio_play_priority_thread(self):
- while not self.stop_event.is_set():
- text = None
- try:
- try:
- audio_datas, text, text_index = self.audio_play_queue.get(timeout=1)
- except queue.Empty:
- if self.stop_event.is_set():
- break
- continue
- future = asyncio.run_coroutine_threadsafe(
- sendAudioMessage(self, audio_datas, text, text_index), self.loop
- )
- future.result()
- except Exception as e:
- self.logger.bind(tag=TAG).error(
- f"audio_play_priority priority_thread: {text} {e}"
- )
-
def _report_worker(self):
"""聊天记录上报工作线程"""
while not self.stop_event.is_set():
@@ -963,17 +904,17 @@ class ConnectionHandler:
item = self.report_queue.get(timeout=1)
if item is None: # 检测毒丸对象
break
-
- type, text, audio_data = item
-
+ type, text, audio_data, report_time = item
try:
- # 执行上报(传入二进制数据)
- report(self, type, text, audio_data)
+ # 检查线程池状态
+ if self.executor is None:
+ continue
+ # 提交任务到线程池
+ self.executor.submit(
+ self._process_report, type, text, audio_data, report_time
+ )
except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
- finally:
- # 标记任务完成
- self.report_queue.task_done()
except queue.Empty:
continue
except Exception as e:
@@ -981,82 +922,79 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
- def speak_and_play(self, text, text_index=0):
- if text is None or len(text) <= 0:
- self.logger.bind(tag=TAG).info(f"无需tts转换,query为空,{text}")
- return None, text, text_index
- tts_file = self.tts.to_tts(text)
- if tts_file is None:
- self.logger.bind(tag=TAG).error(f"tts转换失败,{text}")
- return None, text, text_index
- self.logger.bind(tag=TAG).debug(f"TTS 文件生成完毕: {tts_file}")
- if self.max_output_size > 0:
- add_device_output(self.headers.get("device-id"), len(text))
- return tts_file, text, text_index
+ def _process_report(self, type, text, audio_data, report_time):
+ """处理上报任务"""
+ try:
+ # 执行上报(传入二进制数据)
+ report(self, type, text, audio_data, report_time)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
+ finally:
+ # 标记任务完成
+ self.report_queue.task_done()
def clearSpeakStatus(self):
+ self.client_is_speaking = False
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
- self.asr_server_receive = True
- self.tts_last_text_index = -1
- self.tts_first_text_index = -1
-
- def recode_first_last_text(self, text, text_index=0):
- if self.tts_first_text_index == -1:
- self.logger.bind(tag=TAG).info(f"大模型说出第一句话: {text}")
- self.tts_first_text_index = text_index
- self.tts_last_text_index = text_index
async def close(self, ws=None):
"""资源清理方法"""
+ try:
+ # 取消超时任务
+ if self.timeout_task:
+ self.timeout_task.cancel()
+ self.timeout_task = None
- # 取消超时任务
- if self.timeout_task:
- self.timeout_task.cancel()
- self.timeout_task = None
+ # 清理MCP资源
+ if hasattr(self, "mcp_manager") and self.mcp_manager:
+ await self.mcp_manager.cleanup_all()
- # 清理MCP资源
- if hasattr(self, "mcp_manager") and self.mcp_manager:
- await self.mcp_manager.cleanup_all()
+ # 触发停止事件
+ if self.stop_event:
+ self.stop_event.set()
- # 触发停止事件
- if self.stop_event:
- self.stop_event.set()
+ # 清空任务队列
+ self.clear_queues()
- # 清空任务队列
- self.clear_queues()
+ # 关闭WebSocket连接
+ if ws:
+ await ws.close()
+ elif self.websocket:
+ await self.websocket.close()
- # 关闭WebSocket连接
- if ws:
- await ws.close()
- elif self.websocket:
- await self.websocket.close()
+ # 最后关闭线程池(避免阻塞)
+ if self.executor:
+ self.executor.shutdown(wait=False)
+ self.executor = None
- # 最后关闭线程池(避免阻塞)
- if self.executor:
- self.executor.shutdown(wait=False)
- self.executor = None
-
- self.logger.bind(tag=TAG).info("连接资源已释放")
+ self.logger.bind(tag=TAG).info("连接资源已释放")
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
def clear_queues(self):
"""清空所有任务队列"""
- self.logger.bind(tag=TAG).debug(
- f"开始清理: TTS队列大小={self.tts_queue.qsize()}, 音频队列大小={self.audio_play_queue.qsize()}"
- )
+ if self.tts:
+ self.logger.bind(tag=TAG).debug(
+ f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
+ )
- # 使用非阻塞方式清空队列
- for q in [self.tts_queue, self.audio_play_queue]:
- if not q:
- continue
- while True:
- try:
- q.get_nowait()
- except queue.Empty:
- break
+ # 使用非阻塞方式清空队列
+ for q in [
+ self.tts.tts_text_queue,
+ self.tts.tts_audio_queue,
+ self.report_queue,
+ ]:
+ if not q:
+ continue
+ while True:
+ try:
+ q.get_nowait()
+ except queue.Empty:
+ break
- self.logger.bind(tag=TAG).debug(
- f"清理结束: TTS队列大小={self.tts_queue.qsize()}, 音频队列大小={self.audio_play_queue.qsize()}"
- )
+ self.logger.bind(tag=TAG).debug(
+ f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
+ )
def reset_vad_states(self):
self.client_audio_buffer = bytearray()
@@ -1087,37 +1025,3 @@ class ConnectionHandler:
break
except Exception as e:
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
-
-
-def filter_sensitive_info(config: dict) -> dict:
- """
- 过滤配置中的敏感信息
- Args:
- config: 原始配置字典
- Returns:
- 过滤后的配置字典
- """
- sensitive_keys = [
- "api_key",
- "personal_access_token",
- "access_token",
- "token",
- "secret",
- "access_key_secret",
- "secret_key",
- ]
-
- def _filter_dict(d: dict) -> dict:
- filtered = {}
- for k, v in d.items():
- if any(sensitive in k.lower() for sensitive in sensitive_keys):
- filtered[k] = "***"
- elif isinstance(v, dict):
- filtered[k] = _filter_dict(v)
- elif isinstance(v, list):
- filtered[k] = [_filter_dict(i) if isinstance(i, dict) else i for i in v]
- else:
- filtered[k] = v
- return filtered
-
- return _filter_dict(copy.deepcopy(config))
diff --git a/main/xiaozhi-server/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/abortHandle.py
index fe2715114..ce6f22b6c 100644
--- a/main/xiaozhi-server/core/handle/abortHandle.py
+++ b/main/xiaozhi-server/core/handle/abortHandle.py
@@ -1,6 +1,4 @@
import json
-import queue
-from config.logger import setup_logging
TAG = __name__
diff --git a/main/xiaozhi-server/core/handle/functionHandler.py b/main/xiaozhi-server/core/handle/functionHandler.py
index b09a369c6..e12925535 100644
--- a/main/xiaozhi-server/core/handle/functionHandler.py
+++ b/main/xiaozhi-server/core/handle/functionHandler.py
@@ -1,6 +1,12 @@
from config.logger import setup_logging
import json
-from plugins_func.register import FunctionRegistry, ActionResponse, Action, ToolType
+from plugins_func.register import (
+ FunctionRegistry,
+ ActionResponse,
+ Action,
+ ToolType,
+ DeviceTypeRegistry,
+)
from plugins_func.functions.hass_init import append_devices_to_prompt
TAG = __name__
@@ -10,30 +16,17 @@ class FunctionHandler:
def __init__(self, conn):
self.conn = conn
self.config = conn.config
+ self.device_type_registry = DeviceTypeRegistry()
self.function_registry = FunctionRegistry()
self.register_nessary_functions()
self.register_config_functions()
self.functions_desc = self.function_registry.get_all_function_desc()
- func_names = self.current_support_functions()
- self.modify_plugin_loader_des(func_names)
self.finish_init = True
-
- def modify_plugin_loader_des(self, func_names):
- if "plugin_loader" not in func_names:
- return
- # 可编辑的列表中去掉plugin_loader
- surport_plugins = [func for func in func_names if func != "plugin_loader"]
- func_names = ",".join(surport_plugins)
- for function_desc in self.functions_desc:
- if function_desc["function"]["name"] == "plugin_loader":
- function_desc["function"]["description"] = function_desc["function"][
- "description"
- ].replace("[plugins]", func_names)
- break
-
+
def upload_functions_desc(self):
self.functions_desc = self.function_registry.get_all_function_desc()
+
def current_support_functions(self):
func_names = []
for func in self.functions_desc:
@@ -51,10 +44,8 @@ class FunctionHandler:
def register_nessary_functions(self):
"""注册必要的函数"""
self.function_registry.register_function("handle_exit_intent")
- self.function_registry.register_function("plugin_loader")
self.function_registry.register_function("get_time")
self.function_registry.register_function("get_lunar")
- self.function_registry.register_function("handle_device")
def register_config_functions(self):
"""注册配置中的函数,可以不同客户端使用不同的配置"""
@@ -70,6 +61,16 @@ class FunctionHandler:
return self.function_registry.get_function(name)
def handle_llm_function_call(self, conn, function_call_data):
+ # 多函数调用处理
+ if "function_calls" in function_call_data:
+ responses = []
+ for call in function_call_data["function_calls"]:
+ func = self.get_function(call["name"])
+ if func:
+ # 执行函数并收集响应
+ response = func(conn, **call.get("arguments", {}))
+ responses.append(response)
+ return self._combine_responses(responses) # 合并响应
try:
function_name = function_call_data["name"]
funcItem = self.get_function(function_name)
diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py
index f902a64fa..f5a3b0cd5 100644
--- a/main/xiaozhi-server/core/handle/helloHandle.py
+++ b/main/xiaozhi-server/core/handle/helloHandle.py
@@ -1,23 +1,32 @@
-import json
-from core.handle.sendAudioHandle import send_stt_message
-from core.utils.util import remove_punctuation_and_length
-import shutil
-import asyncio
-import os
-import random
import time
+import json
+import random
+import asyncio
+from core.utils.dialogue import Message
+from core.utils.util import audio_to_data
+from core.handle.sendAudioHandle import sendAudioMessage, send_stt_message
+from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
+from core.providers.tts.dto.dto import ContentType, SentenceType
+from core.handle.mcpHandle import (
+ MCPClient,
+ send_mcp_initialize_message,
+ send_mcp_tools_list_request,
+)
+from core.utils.wakeup_word import WakeupWordsConfig
TAG = __name__
WAKEUP_CONFIG = {
- "dir": "config/assets/",
- "file_name": "wakeup_words",
- "create_time": time.time(),
- "refresh_time": 10,
- "words": ["你好小智", "你好啊小智", "小智你好", "小智"],
- "text": "",
+ "refresh_time": 5,
+ "words": ["你好", "你好啊", "嘿,你好", "嗨"],
}
+# 创建全局的唤醒词配置管理器
+wakeup_words_config = WakeupWordsConfig()
+
+# 用于防止并发调用wakeupWordsResponse的锁
+_wakeup_response_lock = asyncio.Lock()
+
async def handleHelloMessage(conn, msg_json):
"""处理hello消息"""
@@ -26,8 +35,18 @@ async def handleHelloMessage(conn, msg_json):
format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}")
conn.audio_format = format
- conn.asr.set_audio_format(format)
conn.welcome_msg["audio_params"] = audio_params
+ features = msg_json.get("features")
+ if features:
+ conn.logger.bind(tag=TAG).info(f"客户端特性: {features}")
+ conn.features = features
+ if features.get("mcp"):
+ conn.logger.bind(tag=TAG).info("客户端支持MCP")
+ conn.mcp_client = MCPClient()
+ # 发送初始化
+ asyncio.create_task(send_mcp_initialize_message(conn))
+ # 发送mcp消息,获取tools列表
+ asyncio.create_task(send_mcp_tools_list_request(conn))
await conn.websocket.send(json.dumps(conn.welcome_msg))
@@ -36,73 +55,87 @@ async def checkWakeupWords(conn, text):
enable_wakeup_words_response_cache = conn.config[
"enable_wakeup_words_response_cache"
]
- """是否开启唤醒词加速"""
- if not enable_wakeup_words_response_cache:
+
+ if not enable_wakeup_words_response_cache or not conn.tts:
return False
- """检查是否是唤醒词"""
- _, text = remove_punctuation_and_length(text)
- if text in conn.config.get("wakeup_words"):
- await send_stt_message(conn, text)
- conn.tts_first_text_index = 0
- conn.tts_last_text_index = 0
- conn.llm_finish_task = True
- file = getWakeupWordFile(WAKEUP_CONFIG["file_name"])
- if file is None:
+ _, filtered_text = remove_punctuation_and_length(text)
+ if filtered_text not in conn.config.get("wakeup_words"):
+ return False
+
+ conn.just_woken_up = True
+ await send_stt_message(conn, text)
+
+ # 获取当前音色
+ voice = getattr(conn.tts, "voice", "default")
+ if not voice:
+ voice = "default"
+
+ # 获取唤醒词回复配置
+ response = wakeup_words_config.get_wakeup_response(voice)
+ if not response or not response.get("file_path"):
+ response = {
+ "voice": "default",
+ "file_path": "config/assets/wakeup_words.wav",
+ "time": 0,
+ "text": "哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",
+ }
+
+ # 播放唤醒词回复
+ conn.client_abort = False
+ opus_packets, _ = audio_to_data(response.get("file_path"))
+
+ 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")))
+
+ # 检查是否需要更新唤醒词回复
+ if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
+ if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
- return False
- opus_packets, _ = conn.tts.audio_to_opus_data(file)
- text_hello = WAKEUP_CONFIG["text"]
- if not text_hello:
- text_hello = text
- conn.audio_play_queue.put((opus_packets, text_hello, 0))
- if time.time() - WAKEUP_CONFIG["create_time"] > WAKEUP_CONFIG["refresh_time"]:
- asyncio.create_task(wakeupWordsResponse(conn))
- return True
- return False
-
-
-def getWakeupWordFile(file_name):
- for file in os.listdir(WAKEUP_CONFIG["dir"]):
- if file.startswith("my_" + file_name):
- """避免缓存文件是一个空文件"""
- if os.stat(f"config/assets/{file}").st_size > (15 * 1024):
- return f"config/assets/{file}"
-
- """查找config/assets/目录下名称为wakeup_words的文件"""
- for file in os.listdir(WAKEUP_CONFIG["dir"]):
- if file.startswith(file_name):
- return f"config/assets/{file}"
- return None
+ return True
async def wakeupWordsResponse(conn):
- wait_max_time = 5
- while conn.llm is None or not conn.llm.response_no_stream:
- await asyncio.sleep(1)
- wait_max_time -= 1
- if wait_max_time <= 0:
- conn.logger.bind(tag=TAG).error("连接对象没有llm")
+ if not conn.tts or not conn.llm or not conn.llm.response_no_stream:
+ return
+
+ try:
+ # 尝试获取锁,如果获取不到就返回
+ if not await _wakeup_response_lock.acquire():
return
- """唤醒词响应"""
- wakeup_word = random.choice(WAKEUP_CONFIG["words"])
- result = conn.llm.response_no_stream(conn.config["prompt"], wakeup_word)
- if result is None or result == "":
- return
- tts_file = await asyncio.to_thread(conn.tts.to_tts, result)
-
- if tts_file is not None and os.path.exists(tts_file):
- file_type = os.path.splitext(tts_file)[1]
- if file_type:
- file_type = file_type.lstrip(".")
- old_file = getWakeupWordFile("my_" + WAKEUP_CONFIG["file_name"])
- if old_file is not None:
- os.remove(old_file)
- """将文件挪到"wakeup_words.mp3"""
- shutil.move(
- tts_file,
- WAKEUP_CONFIG["dir"] + "my_" + WAKEUP_CONFIG["file_name"] + "." + file_type,
+ # 生成唤醒词回复
+ wakeup_word = random.choice(WAKEUP_CONFIG["words"])
+ question = (
+ "此刻用户正在和你说```"
+ + wakeup_word
+ + "```。\n请你根据以上用户的内容进行20-30字回复。要符合系统设置的角色情感和态度,不要像机器人一样说话。\n"
+ + "请勿对这条内容本身进行任何解释和回应,请勿返回表情符号,仅返回对用户的内容的回复。"
)
- WAKEUP_CONFIG["create_time"] = time.time()
- WAKEUP_CONFIG["text"] = result
+
+ result = conn.llm.response_no_stream(conn.config["prompt"], question)
+ if not result or len(result) == 0:
+ return
+
+ # 生成TTS音频
+ tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
+ if not tts_result:
+ return
+
+ # 获取当前音色
+ voice = getattr(conn.tts, "voice", "default")
+
+ wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
+ file_path = wakeup_words_config.generate_file_path(voice)
+ with open(file_path, "wb") as f:
+ f.write(wav_bytes)
+ # 更新配置
+ wakeup_words_config.update_wakeup_response(voice, file_path, result)
+ finally:
+ # 确保在任何情况下都释放锁
+ if _wakeup_response_lock.locked():
+ _wakeup_response_lock.release()
diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index 1cae8bab4..de4c36c11 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -1,11 +1,13 @@
-from config.logger import setup_logging
import json
+import asyncio
import uuid
from core.handle.sendAudioHandle import send_stt_message
from core.handle.helloHandle import checkWakeupWords
from core.utils.util import remove_punctuation_and_length
+from core.providers.tts.dto.dto import ContentType
from core.utils.dialogue import Message
-from plugins_func.register import Action
+from core.handle.mcpHandle import call_mcp_tool
+from plugins_func.register import Action, ActionResponse
from loguru import logger
TAG = __name__
@@ -13,10 +15,11 @@ TAG = __name__
async def handle_user_intent(conn, text):
# 检查是否有明确的退出命令
- if await check_direct_exit(conn, text):
+ filtered_text = remove_punctuation_and_length(text)[1]
+ if await check_direct_exit(conn, filtered_text):
return True
# 检查是否是唤醒词
- if await checkWakeupWords(conn, text):
+ if await checkWakeupWords(conn, filtered_text):
return True
if conn.intent_type == "function_call":
@@ -81,9 +84,11 @@ async def process_intent_result(conn, intent_result, original_text):
if not funcItem:
conn.func_handler.function_registry.register_function("play_music")
- function_args = None
+ function_args = {}
if "arguments" in intent_data["function_call"]:
function_args = intent_data["function_call"]["arguments"]
+ if function_args is None:
+ function_args = {}
# 确保参数是字符串格式的JSON
if isinstance(function_args, dict):
function_args = json.dumps(function_args)
@@ -95,34 +100,63 @@ async def process_intent_result(conn, intent_result, original_text):
}
await send_stt_message(conn, original_text)
+ conn.client_abort = False
# 使用executor执行函数调用和结果处理
def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text))
- result = conn.func_handler.handle_llm_function_call(
- conn, function_call_data
- )
- logger.bind(tag=TAG).debug(f"检测到Action : {result.action}")
+
+ # 处理Server端MCP工具调用
+ if conn.mcp_manager.is_mcp_tool(function_name):
+ result = conn._handle_mcp_tool_call(function_call_data)
+ elif hasattr(conn, "mcp_client") and conn.mcp_client.has_tool(
+ function_name
+ ):
+ # 如果是小智端MCP工具调用
+ conn.logger.bind(tag=TAG).debug(
+ f"调用小智端MCP工具: {function_name}, 参数: {function_args}"
+ )
+ try:
+ result = asyncio.run_coroutine_threadsafe(
+ call_mcp_tool(
+ conn, conn.mcp_client, function_name, function_args
+ ),
+ conn.loop,
+ ).result()
+ conn.logger.bind(tag=TAG).debug(f"MCP工具调用结果: {result}")
+ result = ActionResponse(
+ action=Action.REQLLM, result=result, response=""
+ )
+ except Exception as e:
+ conn.logger.bind(tag=TAG).error(f"MCP工具调用失败: {e}")
+ result = ActionResponse(
+ action=Action.REQLLM, result="MCP工具调用失败", response=""
+ )
+ else:
+ # 处理系统函数
+ result = conn.func_handler.handle_llm_function_call(
+ conn, function_call_data
+ )
if result:
if result.action == Action.RESPONSE: # 直接回复前端
text = result.response
if text is not None:
- speak_and_play(conn, text)
+ speak_txt(conn, text)
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
text = result.result
conn.dialogue.put(Message(role="tool", content=text))
llm_result = conn.intent.replyResult(text, original_text)
if llm_result is None:
llm_result = text
- speak_and_play(conn, llm_result)
+ speak_txt(conn, llm_result)
elif (
result.action == Action.NOTFOUND
or result.action == Action.ERROR
):
text = result.result
if text is not None:
- speak_and_play(conn, text)
+ speak_txt(conn, text)
elif function_name != "play_music":
# For backward compatibility with original code
# 获取当前最新的文本索引
@@ -130,7 +164,7 @@ async def process_intent_result(conn, intent_result, original_text):
if text is None:
text = result.result
if text is not None:
- speak_and_play(conn, text)
+ speak_txt(conn, text)
# 将函数执行放在线程池中
conn.executor.submit(process_function_call)
@@ -141,12 +175,6 @@ async def process_intent_result(conn, intent_result, original_text):
return False
-def speak_and_play(conn, text):
- text_index = (
- conn.tts_last_text_index + 1 if hasattr(conn, "tts_last_text_index") else 0
- )
- conn.recode_first_last_text(text, text_index)
- future = conn.executor.submit(conn.speak_and_play, text, text_index)
- conn.llm_finish_task = True
- conn.tts_queue.put((future, text_index))
+def speak_txt(conn, text):
+ conn.tts.tts_one_sentence(conn, ContentType.TEXT, content_detail=text)
conn.dialogue.put(Message(role="assistant", content=text))
diff --git a/main/xiaozhi-server/core/handle/iotHandle.py b/main/xiaozhi-server/core/handle/iotHandle.py
index 5b1bb9bb6..bebb44fc5 100644
--- a/main/xiaozhi-server/core/handle/iotHandle.py
+++ b/main/xiaozhi-server/core/handle/iotHandle.py
@@ -1,9 +1,8 @@
import json
import asyncio
-from config.logger import setup_logging
from plugins_func.register import (
- device_type_registry,
- register_function,
+ FunctionItem,
+ register_device_function,
ActionResponse,
Action,
ToolType,
@@ -83,7 +82,11 @@ def create_iot_function(device_name, method_name, method_info):
response = response.replace("{value}", str(param_value))
break
- return ActionResponse(Action.RESPONSE, result, response)
+ return ActionResponse(
+ Action.REQLLM,
+ result=f"{device_name}操作执行成功,请继续处理剩余指令",
+ response=response_success # 保留成功提示
+ )
except Exception as e:
conn.logger.bind(tag=TAG).error(
f"执行{device_name}的{method_name}操作失败: {e}"
@@ -177,7 +180,7 @@ class IotDescriptor:
self.methods.append(method)
-def register_device_type(descriptor):
+def register_device_type(descriptor, device_type_registry):
"""注册设备类型及其功能"""
device_name = descriptor["name"]
type_id = device_type_registry.generate_device_type_id(descriptor)
@@ -213,10 +216,12 @@ def register_device_type(descriptor):
},
}
query_func = create_iot_query_function(device_name, prop_name, prop_info)
- decorated_func = register_function(func_name, func_desc, ToolType.IOT_CTL)(
- query_func
+ decorated_func = register_device_function(
+ func_name, func_desc, ToolType.IOT_CTL
+ )(query_func)
+ functions[func_name] = FunctionItem(
+ func_name, func_desc, decorated_func, ToolType.IOT_CTL
)
- functions[func_name] = decorated_func
# 为每个方法创建控制函数
for method_name, method_info in descriptor["methods"].items():
@@ -267,10 +272,12 @@ def register_device_type(descriptor):
},
}
control_func = create_iot_function(device_name, method_name, method_info)
- decorated_func = register_function(func_name, func_desc, ToolType.IOT_CTL)(
- control_func
+ decorated_func = register_device_function(
+ func_name, func_desc, ToolType.IOT_CTL
+ )(control_func)
+ functions[func_name] = FunctionItem(
+ func_name, func_desc, decorated_func, ToolType.IOT_CTL
)
- functions[func_name] = decorated_func
device_type_registry.register_device_type(type_id, functions)
return type_id
@@ -289,7 +296,6 @@ async def handleIotDescriptors(conn, descriptors):
functions_changed = False
for descriptor in descriptors:
-
# 如果descriptor没有properties和methods,则直接跳过
if "properties" not in descriptor and "methods" not in descriptor:
continue
@@ -319,13 +325,16 @@ async def handleIotDescriptors(conn, descriptors):
if conn.load_function_plugin:
# 注册或获取设备类型
- type_id = register_device_type(descriptor)
+ device_type_registry = conn.func_handler.device_type_registry
+ type_id = register_device_type(descriptor, device_type_registry)
device_functions = device_type_registry.get_device_functions(type_id)
# 在连接级注册设备函数
if hasattr(conn, "func_handler"):
- for func_name in device_functions:
- conn.func_handler.function_registry.register_function(func_name)
+ for func_name, func_item in device_functions.items():
+ conn.func_handler.function_registry.register_function(
+ func_name, func_item
+ )
conn.logger.bind(tag=TAG).info(
f"注册IOT函数到function handler: {func_name}"
)
@@ -334,6 +343,7 @@ async def handleIotDescriptors(conn, descriptors):
# 如果注册了新函数,更新function描述列表
if functions_changed and hasattr(conn, "func_handler"):
conn.func_handler.upload_functions_desc()
+
func_names = conn.func_handler.current_support_functions()
conn.logger.bind(tag=TAG).info(f"设备类型: {type_id}")
conn.logger.bind(tag=TAG).info(
diff --git a/main/xiaozhi-server/core/handle/mcpHandle.py b/main/xiaozhi-server/core/handle/mcpHandle.py
new file mode 100644
index 000000000..3f3216ac2
--- /dev/null
+++ b/main/xiaozhi-server/core/handle/mcpHandle.py
@@ -0,0 +1,387 @@
+import json
+import asyncio
+from concurrent.futures import Future
+from core.utils.util import get_vision_url, sanitize_tool_name
+from core.utils.auth import AuthToken
+
+TAG = __name__
+
+
+class MCPClient:
+ """MCPClient,用于管理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, payload: dict):
+ """Helper to send MCP messages, encapsulating common logic."""
+ if not conn.features.get("mcp"):
+ conn.logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息")
+ return
+
+ message = json.dumps({"type": "mcp", "payload": payload})
+
+ try:
+ await conn.websocket.send(message)
+ conn.logger.bind(tag=TAG).info(f"成功发送MCP消息: {message}")
+ except Exception as e:
+ conn.logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}")
+
+
+async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
+ """处理MCP消息,包括初始化、工具列表和工具调用响应等"""
+ conn.logger.bind(tag=TAG).info(f"处理MCP消息: {payload}")
+
+ if not isinstance(payload, dict):
+ conn.logger.bind(tag=TAG).error("MCP消息缺少payload字段或格式错误")
+ return
+
+ # Handle result
+ if "result" in payload:
+ result = payload["result"]
+ msg_id = int(payload.get("id", 0))
+
+ # Check for tool call response first
+ if msg_id in mcp_client.call_results:
+ conn.logger.bind(tag=TAG).debug(
+ f"收到工具调用响应,ID: {msg_id}, 结果: {result}"
+ )
+ await mcp_client.resolve_call_result(msg_id, result)
+ return
+
+ if msg_id == 1: # mcpInitializeID
+ conn.logger.bind(tag=TAG).debug("收到MCP初始化响应")
+ server_info = result.get("serverInfo")
+ if isinstance(server_info, dict):
+ name = server_info.get("name")
+ version = server_info.get("version")
+ conn.logger.bind(tag=TAG).info(
+ f"客户端MCP服务器信息: name={name}, version={version}"
+ )
+ return
+
+ elif msg_id == 2: # mcpToolsListID
+ conn.logger.bind(tag=TAG).debug("收到MCP工具列表响应")
+ if isinstance(result, dict) and "tools" in result:
+ tools_data = result["tools"]
+ if not isinstance(tools_data, list):
+ conn.logger.bind(tag=TAG).error("工具列表格式错误")
+ return
+
+ conn.logger.bind(tag=TAG).info(
+ f"客户端设备支持的工具数量: {len(tools_data)}"
+ )
+
+ for i, tool in enumerate(tools_data):
+ if not isinstance(tool, dict):
+ continue
+
+ name = tool.get("name", "")
+ description = tool.get("description", "")
+ input_schema = {"type": "object", "properties": {}, "required": []}
+
+ if "inputSchema" in tool and isinstance(tool["inputSchema"], dict):
+ schema = tool["inputSchema"]
+ input_schema["type"] = schema.get("type", "object")
+ input_schema["properties"] = schema.get("properties", {})
+ input_schema["required"] = [
+ s for s in schema.get("required", []) if isinstance(s, str)
+ ]
+
+ new_tool = {
+ "name": name,
+ "description": description,
+ "inputSchema": input_schema,
+ }
+ await mcp_client.add_tool(new_tool)
+ conn.logger.bind(tag=TAG).debug(f"客户端工具 #{i+1}: {name}")
+
+ # 替换所有工具描述中的工具名称
+ for tool_data in mcp_client.tools.values():
+ if "description" in tool_data:
+ description = tool_data["description"]
+ # 遍历所有工具名称进行替换
+ for (
+ sanitized_name,
+ original_name,
+ ) in mcp_client.name_mapping.items():
+ description = description.replace(
+ original_name, sanitized_name
+ )
+ tool_data["description"] = description
+
+ next_cursor = result.get("nextCursor", "")
+ if next_cursor:
+ conn.logger.bind(tag=TAG).info(
+ f"有更多工具,nextCursor: {next_cursor}"
+ )
+ await send_mcp_tools_list_continue_request(conn, next_cursor)
+ else:
+ await mcp_client.set_ready(True)
+ conn.logger.bind(tag=TAG).info("所有工具已获取,MCP客户端准备就绪")
+ return
+
+ # Handle method calls (requests from the client)
+ elif "method" in payload:
+ method = payload["method"]
+ conn.logger.bind(tag=TAG).info(f"收到MCP客户端请求: {method}")
+
+ elif "error" in payload:
+ error_data = payload["error"]
+ error_msg = error_data.get("message", "未知错误")
+ conn.logger.bind(tag=TAG).error(f"收到MCP错误响应: {error_msg}")
+
+ msg_id = int(payload.get("id", 0))
+ if msg_id in mcp_client.call_results:
+ await mcp_client.reject_call_result(
+ msg_id, Exception(f"MCP错误: {error_msg}")
+ )
+
+
+# --- Outgoing MCP Messages ---
+
+
+async def send_mcp_initialize_message(conn):
+ """发送MCP初始化消息"""
+
+ vision_url = get_vision_url(conn.config)
+
+ # 密钥生成token
+ auth = AuthToken(conn.config["server"]["auth_key"])
+ token = auth.generate_token(conn.headers.get("device-id"))
+
+ vision = {
+ "url": vision_url,
+ "token": token,
+ }
+
+ payload = {
+ "jsonrpc": "2.0",
+ "id": 1, # mcpInitializeID
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {
+ "roots": {"listChanged": True},
+ "sampling": {},
+ "vision": vision,
+ },
+ "clientInfo": {
+ "name": "XiaozhiClient",
+ "version": "1.0.0",
+ },
+ },
+ }
+ conn.logger.bind(tag=TAG).info("发送MCP初始化消息")
+ await send_mcp_message(conn, payload)
+
+
+async def send_mcp_tools_list_request(conn):
+ """发送MCP工具列表请求"""
+ payload = {
+ "jsonrpc": "2.0",
+ "id": 2, # mcpToolsListID
+ "method": "tools/list",
+ }
+ conn.logger.bind(tag=TAG).debug("发送MCP工具列表请求")
+ await send_mcp_message(conn, payload)
+
+
+async def send_mcp_tools_list_continue_request(conn, cursor: str):
+ """发送带有cursor的MCP工具列表请求"""
+ payload = {
+ "jsonrpc": "2.0",
+ "id": 2, # mcpToolsListID (same ID for continuation)
+ "method": "tools/list",
+ "params": {"cursor": cursor},
+ }
+ conn.logger.bind(tag=TAG).info(f"发送带cursor的MCP工具列表请求: {cursor}")
+ await send_mcp_message(conn, payload)
+
+
+async def call_mcp_tool(
+ conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30
+):
+ """
+ 调用指定的工具,并等待响应
+ """
+ if not await mcp_client.is_ready():
+ raise RuntimeError("MCP客户端尚未准备就绪")
+
+ if not mcp_client.has_tool(tool_name):
+ raise ValueError(f"工具 {tool_name} 不存在")
+
+ tool_call_id = await mcp_client.get_next_id()
+ result_future = asyncio.Future()
+ await mcp_client.register_call_result_future(tool_call_id, result_future)
+
+ # 处理参数
+ try:
+ if isinstance(args, str):
+ # 确保字符串是有效的JSON
+ if not args.strip():
+ arguments = {}
+ else:
+ try:
+ # 尝试直接解析
+ arguments = json.loads(args)
+ except json.JSONDecodeError:
+ # 如果解析失败,尝试合并多个JSON对象
+ try:
+ # 使用正则表达式匹配所有JSON对象
+ import re
+
+ json_objects = re.findall(r"\{[^{}]*\}", args)
+ if len(json_objects) > 1:
+ # 合并所有JSON对象
+ merged_dict = {}
+ for json_str in json_objects:
+ try:
+ obj = json.loads(json_str)
+ if isinstance(obj, dict):
+ merged_dict.update(obj)
+ except json.JSONDecodeError:
+ continue
+ if merged_dict:
+ arguments = merged_dict
+ else:
+ raise ValueError(f"无法解析任何有效的JSON对象: {args}")
+ else:
+ raise ValueError(f"参数JSON解析失败: {args}")
+ except Exception as e:
+ conn.logger.bind(tag=TAG).error(
+ f"参数JSON解析失败: {str(e)}, 原始参数: {args}"
+ )
+ raise ValueError(f"参数JSON解析失败: {str(e)}")
+ elif isinstance(args, dict):
+ arguments = args
+ else:
+ raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}")
+
+ # 确保参数是字典类型
+ if not isinstance(arguments, dict):
+ raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}")
+
+ except Exception as e:
+ if not isinstance(e, ValueError):
+ raise ValueError(f"参数处理失败: {str(e)}")
+ raise e
+
+ actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
+ payload = {
+ "jsonrpc": "2.0",
+ "id": tool_call_id,
+ "method": "tools/call",
+ "params": {"name": actual_name, "arguments": arguments},
+ }
+
+ conn.logger.bind(tag=TAG).info(
+ f"发送客户端mcp工具调用请求: {actual_name},参数: {args}"
+ )
+ await send_mcp_message(conn, payload)
+
+ try:
+ # Wait for response or timeout
+ raw_result = await asyncio.wait_for(result_future, timeout=timeout)
+ conn.logger.bind(tag=TAG).info(
+ f"客户端mcp工具调用 {actual_name} 成功,原始结果: {raw_result}"
+ )
+
+ if isinstance(raw_result, dict):
+ if raw_result.get("isError") is True:
+ error_msg = raw_result.get(
+ "error", "工具调用返回错误,但未提供具体错误信息"
+ )
+ raise RuntimeError(f"工具调用错误: {error_msg}")
+
+ content = raw_result.get("content")
+ if isinstance(content, list) and len(content) > 0:
+ if isinstance(content[0], dict) and "text" in content[0]:
+ # 直接返回文本内容,不进行JSON解析
+ return content[0]["text"]
+ # 如果结果不是预期的格式,将其转换为字符串
+ return str(raw_result)
+ except asyncio.TimeoutError:
+ await mcp_client.cleanup_call_result(tool_call_id)
+ raise TimeoutError("工具调用请求超时")
+ except Exception as e:
+ await mcp_client.cleanup_call_result(tool_call_id)
+ raise e
diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
index ee6a1d5cd..fd58f49de 100644
--- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
@@ -1,56 +1,40 @@
-import time
-import copy
-from core.utils.util import remove_punctuation_and_length
from core.handle.sendAudioHandle import send_stt_message
from core.handle.intentHandler import handle_user_intent
from core.utils.output_counter import check_device_output_limit
-from core.handle.reportHandle import enqueue_asr_report
+from core.handle.abortHandle import handleAbortMessage
+import time
+import asyncio
+from core.handle.sendAudioHandle import SentenceType
from core.utils.util import audio_to_data
TAG = __name__
async def handleAudioMessage(conn, audio):
- if conn.vad is None:
- return
- if not conn.asr_server_receive:
- conn.logger.bind(tag=TAG).debug(f"前期数据处理中,暂停接收")
- return
- if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
- have_voice = conn.vad.is_vad(conn, audio)
- else:
- have_voice = conn.client_have_voice
-
- # 如果本次没有声音,本段也没声音,就把声音丢弃了
- if have_voice == False and conn.client_have_voice == False:
- await no_voice_close_connect(conn)
- conn.asr_audio.append(audio)
- conn.asr_audio = conn.asr_audio[
- -10:
- ] # 保留最新的10帧音频内容,解决ASR句首丢字问题
- return
- conn.client_no_voice_last_time = 0.0
- conn.asr_audio.append(audio)
- # 如果本段有声音,且已经停止了
- if conn.client_voice_stop:
- conn.client_abort = False
- conn.asr_server_receive = False
- # 音频太短了,无法识别
- if len(conn.asr_audio) < 15:
- conn.asr_server_receive = True
- else:
- text, _ = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
- conn.logger.bind(tag=TAG).info(f"识别文本: {text}")
- text_len, _ = remove_punctuation_and_length(text)
- if text_len > 0:
- # 使用自定义模块进行上报
- enqueue_asr_report(conn, text, copy.deepcopy(conn.asr_audio))
-
- await startToChat(conn, text)
- else:
- conn.asr_server_receive = True
+ # 当前片段是否有人说话
+ have_voice = conn.vad.is_vad(conn, audio)
+ # 如果设备刚刚被唤醒,短暂忽略VAD检测
+ if have_voice and hasattr(conn, "just_woken_up") and conn.just_woken_up:
+ have_voice = False
+ # 设置一个短暂延迟后恢复VAD检测
conn.asr_audio.clear()
- conn.reset_vad_states()
+ if not hasattr(conn, "vad_resume_task") or conn.vad_resume_task.done():
+ conn.vad_resume_task = asyncio.create_task(resume_vad_detection(conn))
+ return
+
+ if have_voice:
+ if conn.client_is_speaking:
+ await handleAbortMessage(conn)
+ # 设备长时间空闲检测,用于say goodbye
+ await no_voice_close_connect(conn, have_voice)
+ # 接收音频
+ await conn.asr.receive_audio(conn, audio, have_voice)
+
+
+async def resume_vad_detection(conn):
+ # 等待2秒后恢复VAD检测
+ await asyncio.sleep(1)
+ conn.just_woken_up = False
async def startToChat(conn, text):
@@ -65,25 +49,25 @@ async def startToChat(conn, text):
):
await max_out_size(conn)
return
+ if conn.client_is_speaking:
+ await handleAbortMessage(conn)
# 首先进行意图分析
intent_handled = await handle_user_intent(conn, text)
if intent_handled:
# 如果意图已被处理,不再进行聊天
- conn.asr_server_receive = True
return
# 意图未被处理,继续常规聊天流程
await send_stt_message(conn, text)
- if conn.intent_type == "function_call":
- # 使用支持function calling的聊天方法
- conn.executor.submit(conn.chat_with_function_calling, text)
- else:
- conn.executor.submit(conn.chat, text)
+ conn.executor.submit(conn.chat, text)
-async def no_voice_close_connect(conn):
+async def no_voice_close_connect(conn, have_voice):
+ if have_voice:
+ conn.client_no_voice_last_time = 0.0
+ return
if conn.client_no_voice_last_time == 0.0:
conn.client_no_voice_last_time = time.time() * 1000
else:
@@ -97,7 +81,6 @@ async def no_voice_close_connect(conn):
):
conn.close_after_chat = True
conn.client_abort = False
- conn.asr_server_receive = False
end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False:
conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语")
@@ -105,19 +88,16 @@ async def no_voice_close_connect(conn):
return
prompt = end_prompt.get("prompt")
if not prompt:
- prompt = "请你以“时间过得真快”未来头,用富有感情、依依不舍的话来结束这场对话吧。!"
+ prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!"
await startToChat(conn, prompt)
async def max_out_size(conn):
text = "不好意思,我现在有点事情要忙,明天这个时候我们再聊,约好了哦!明天不见不散,拜拜!"
await send_stt_message(conn, text)
- conn.tts_first_text_index = 0
- conn.tts_last_text_index = 0
- conn.llm_finish_task = True
file_path = "config/assets/max_output_size.wav"
opus_packets, _ = audio_to_data(file_path)
- conn.audio_play_queue.put((opus_packets, text, 0))
+ conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
conn.close_after_chat = True
@@ -132,14 +112,11 @@ async def check_bind_device(conn):
text = f"请登录控制面板,输入{conn.bind_code},绑定设备。"
await send_stt_message(conn, text)
- conn.tts_first_text_index = 0
- conn.tts_last_text_index = 6
- conn.llm_finish_task = True
# 播放提示音
music_path = "config/assets/bind_code.wav"
opus_packets, _ = audio_to_data(music_path)
- conn.audio_play_queue.put((opus_packets, text, 0))
+ conn.tts.tts_audio_queue.put((SentenceType.FIRST, opus_packets, text))
# 逐个播放数字
for i in range(6): # 确保只播放6位数字
@@ -147,16 +124,14 @@ async def check_bind_device(conn):
digit = conn.bind_code[i]
num_path = f"config/assets/bind_code/{digit}.wav"
num_packets, _ = audio_to_data(num_path)
- conn.audio_play_queue.put((num_packets, None, i + 1))
+ conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None))
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
continue
+ conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else:
text = f"没有找到该设备的版本信息,请正确配置 OTA地址,然后重新编译固件。"
await send_stt_message(conn, text)
- conn.tts_first_text_index = 0
- conn.tts_last_text_index = 0
- conn.llm_finish_task = True
music_path = "config/assets/bind_not_found.wav"
opus_packets, _ = audio_to_data(music_path)
- conn.audio_play_queue.put((opus_packets, text, 0))
+ conn.tts.tts_audio_queue.put((SentenceType.LAST, opus_packets, text))
diff --git a/main/xiaozhi-server/core/handle/reportHandle.py b/main/xiaozhi-server/core/handle/reportHandle.py
index bb1ea066b..7b30f79c0 100644
--- a/main/xiaozhi-server/core/handle/reportHandle.py
+++ b/main/xiaozhi-server/core/handle/reportHandle.py
@@ -9,6 +9,8 @@ TTS上报功能已集成到ConnectionHandler类中。
具体实现请参考core/connection.py中的相关代码。
"""
+import time
+
import opuslib_next
from config.manage_api_client import report as manage_report
@@ -16,7 +18,7 @@ from config.manage_api_client import report as manage_report
TAG = __name__
-def report(conn, type, text, opus_data):
+def report(conn, type, text, opus_data, report_time):
"""执行聊天记录上报操作
Args:
@@ -24,6 +26,7 @@ def report(conn, type, text, opus_data):
type: 上报类型,1为用户,2为智能体
text: 合成文本
opus_data: opus音频数据
+ report_time: 上报时间
"""
try:
if opus_data:
@@ -37,6 +40,7 @@ def report(conn, type, text, opus_data):
chat_type=type,
content=text,
audio=audio_data,
+ report_time=report_time,
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
@@ -104,12 +108,12 @@ def enqueue_tts_report(conn, text, opus_data):
try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
if conn.chat_history_conf == 2:
- conn.report_queue.put((2, text, opus_data))
+ conn.report_queue.put((2, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} "
)
else:
- conn.report_queue.put((2, text, None))
+ conn.report_queue.put((2, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频"
)
@@ -132,14 +136,14 @@ def enqueue_asr_report(conn, text, opus_data):
try:
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
if conn.chat_history_conf == 2:
- conn.report_queue.put((1, text, opus_data))
+ conn.report_queue.put((1, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} "
)
else:
- conn.report_queue.put((1, text, None))
+ conn.report_queue.put((1, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频"
)
except Exception as e:
- conn.logger.bind(tag=TAG).error(f"加入ASR上报队列失败: {text}, {e}")
+ conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}")
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 89f164263..2bf55e65d 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -1,7 +1,9 @@
import json
import asyncio
import time
+from core.providers.tts.dto.dto import SentenceType
from core.utils.util import get_string_no_punctuation_or_emoji, analyze_emotion
+from loguru import logger
TAG = __name__
@@ -30,8 +32,9 @@ emoji_map = {
}
-async def sendAudioMessage(conn, audios, text, text_index=0):
+async def sendAudioMessage(conn, sentenceType, audios, text):
# 发送句子开始消息
+ conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
if text is not None:
emotion = analyze_emotion(text)
emoji = emoji_map.get(emotion, "🙂") # 默认使用笑脸
@@ -45,25 +48,30 @@ async def sendAudioMessage(conn, audios, text, text_index=0):
}
)
)
-
- if text_index == conn.tts_first_text_index:
+ pre_buffer = False
+ if conn.tts.tts_audio_first_sentence and text is not None:
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
+ conn.tts.tts_audio_first_sentence = False
+ pre_buffer = True
+
await send_tts_message(conn, "sentence_start", text)
- is_first_audio = text_index == conn.tts_first_text_index
- await sendAudio(conn, audios, pre_buffer=is_first_audio)
+ await sendAudio(conn, audios, pre_buffer)
await send_tts_message(conn, "sentence_end", text)
# 发送结束消息(如果是最后一个文本)
- if conn.llm_finish_task and text_index == conn.tts_last_text_index:
+ if conn.llm_finish_task and sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None)
+ conn.client_is_speaking = False
if conn.close_after_chat:
await conn.close()
# 播放音频
async def sendAudio(conn, audios, pre_buffer=True):
+ if audios is None or len(audios) == 0:
+ return
# 流控参数优化
frame_duration = 60 # 帧时长(毫秒),匹配 Opus 编码
start_time = time.perf_counter()
@@ -82,7 +90,7 @@ async def sendAudio(conn, audios, pre_buffer=True):
# 播放剩余音频帧
for opus_packet in remaining_audios:
if conn.client_abort:
- return
+ break
# 每分钟重置一次计时器
if time.perf_counter() - last_reset_time > 60:
@@ -125,9 +133,15 @@ async def send_tts_message(conn, state, text=None):
async def send_stt_message(conn, text):
+ end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
+ if end_prompt_str and end_prompt_str == text:
+ await send_tts_message(conn, "start")
+ return
+
"""发送 STT 状态消息"""
stt_text = get_string_no_punctuation_or_emoji(text)
await conn.websocket.send(
json.dumps({"type": "stt", "text": stt_text, "session_id": conn.session_id})
)
+ conn.client_is_speaking = True
await send_tts_message(conn, "start")
diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py
index 79874f1c3..676e33ab1 100644
--- a/main/xiaozhi-server/core/handle/textHandle.py
+++ b/main/xiaozhi-server/core/handle/textHandle.py
@@ -1,7 +1,8 @@
import json
from core.handle.abortHandle import handleAbortMessage
from core.handle.helloHandle import handleHelloMessage
-from core.utils.util import remove_punctuation_and_length
+from core.handle.mcpHandle import handle_mcp_message
+from core.utils.util import remove_punctuation_and_length, filter_sensitive_info
from core.handle.receiveAudioHandle import startToChat, handleAudioMessage
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
from core.handle.iotHandle import handleIotDescriptors, handleIotStatus
@@ -13,17 +14,20 @@ TAG = __name__
async def handleTextMessage(conn, message):
"""处理文本消息"""
- conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}")
try:
msg_json = json.loads(message)
if isinstance(msg_json, int):
+ conn.logger.bind(tag=TAG).info(f"收到文本消息:{message}")
await conn.websocket.send(message)
return
if msg_json["type"] == "hello":
+ conn.logger.bind(tag=TAG).info(f"收到hello消息:{message}")
await handleHelloMessage(conn, msg_json)
elif msg_json["type"] == "abort":
+ conn.logger.bind(tag=TAG).info(f"收到abort消息:{message}")
await handleAbortMessage(conn)
elif msg_json["type"] == "listen":
+ conn.logger.bind(tag=TAG).info(f"收到listen消息:{message}")
if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug(
@@ -38,37 +42,51 @@ async def handleTextMessage(conn, message):
if len(conn.asr_audio) > 0:
await handleAudioMessage(conn, b"")
elif msg_json["state"] == "detect":
- conn.asr_server_receive = False
conn.client_have_voice = False
conn.asr_audio.clear()
if "text" in msg_json:
- text = msg_json["text"]
- _, text = remove_punctuation_and_length(text)
+ original_text = msg_json["text"] # 保留原始文本
+ filtered_len, filtered_text = remove_punctuation_and_length(
+ original_text
+ )
# 识别是否是唤醒词
- is_wakeup_words = text in conn.config.get("wakeup_words")
+ is_wakeup_words = filtered_text in conn.config.get("wakeup_words")
# 是否开启唤醒词回复
enable_greeting = conn.config.get("enable_greeting", True)
if is_wakeup_words and not enable_greeting:
# 如果是唤醒词,且关闭了唤醒词回复,就不用回答
- await send_stt_message(conn, text)
+ await send_stt_message(conn, original_text)
await send_tts_message(conn, "stop", None)
+ conn.client_is_speaking = False
elif is_wakeup_words:
+ conn.just_woken_up = True
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
enqueue_asr_report(conn, "嘿,你好呀", [])
await startToChat(conn, "嘿,你好呀")
else:
# 上报纯文字数据(复用ASR上报功能,但不提供音频数据)
- enqueue_asr_report(conn, text, [])
+ enqueue_asr_report(conn, original_text, [])
# 否则需要LLM对文字内容进行答复
- await startToChat(conn, text)
+ await startToChat(conn, original_text)
elif msg_json["type"] == "iot":
+ conn.logger.bind(tag=TAG).info(f"收到iot消息:{message}")
if "descriptors" in msg_json:
asyncio.create_task(handleIotDescriptors(conn, msg_json["descriptors"]))
if "states" in msg_json:
asyncio.create_task(handleIotStatus(conn, msg_json["states"]))
+ elif msg_json["type"] == "mcp":
+ conn.logger.bind(tag=TAG).info(f"收到mcp消息:{message}")
+ if "payload" in msg_json:
+ asyncio.create_task(
+ handle_mcp_message(conn, conn.mcp_client, msg_json["payload"])
+ )
elif msg_json["type"] == "server":
+ # 记录日志时过滤敏感信息
+ conn.logger.bind(tag=TAG).info(
+ f"收到服务器消息:{filter_sensitive_info(msg_json)}"
+ )
# 如果配置是从API读取的,则需要验证secret
if not conn.read_config_from_api:
return
@@ -95,9 +113,10 @@ async def handleTextMessage(conn, message):
await conn.websocket.send(
json.dumps(
{
- "type": "config_update_response",
+ "type": "server",
"status": "error",
"message": "无法获取服务器实例",
+ "content": {"action": "update_config"},
}
)
)
@@ -107,9 +126,10 @@ async def handleTextMessage(conn, message):
await conn.websocket.send(
json.dumps(
{
- "type": "config_update_response",
+ "type": "server",
"status": "error",
"message": "更新服务器配置失败",
+ "content": {"action": "update_config"},
}
)
)
@@ -119,9 +139,10 @@ async def handleTextMessage(conn, message):
await conn.websocket.send(
json.dumps(
{
- "type": "config_update_response",
+ "type": "server",
"status": "success",
"message": "配置更新成功",
+ "content": {"action": "update_config"},
}
)
)
@@ -130,14 +151,17 @@ async def handleTextMessage(conn, message):
await conn.websocket.send(
json.dumps(
{
- "type": "config_update_response",
+ "type": "server",
"status": "error",
"message": f"更新配置失败: {str(e)}",
+ "content": {"action": "update_config"},
}
)
)
# 重启服务器
elif msg_json["action"] == "restart":
await conn.handle_restart(msg_json)
+ else:
+ conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
except json.JSONDecodeError:
await conn.websocket.send(message)
diff --git a/main/xiaozhi-server/core/http_server.py b/main/xiaozhi-server/core/http_server.py
new file mode 100644
index 000000000..0ed831e87
--- /dev/null
+++ b/main/xiaozhi-server/core/http_server.py
@@ -0,0 +1,71 @@
+import asyncio
+from aiohttp import web
+from config.logger import setup_logging
+from core.api.ota_handler import OTAHandler
+from core.api.vision_handler import VisionHandler
+
+TAG = __name__
+
+
+class SimpleHttpServer:
+ def __init__(self, config: dict):
+ self.config = config
+ self.logger = setup_logging()
+ self.ota_handler = OTAHandler(config)
+ self.vision_handler = VisionHandler(config)
+
+ def _get_websocket_url(self, local_ip: str, port: int) -> str:
+ """获取websocket地址
+
+ Args:
+ local_ip: 本地IP地址
+ port: 端口号
+
+ Returns:
+ str: websocket地址
+ """
+ server_config = self.config["server"]
+ websocket_config = server_config.get("websocket")
+
+ if websocket_config and "你" not in websocket_config:
+ return websocket_config
+ else:
+ return f"ws://{local_ip}:{port}/xiaozhi/v1/"
+
+ async def start(self):
+ server_config = self.config["server"]
+ host = server_config.get("ip", "0.0.0.0")
+ port = int(server_config.get("http_port", 8003))
+
+ if port:
+ app = web.Application()
+
+ read_config_from_api = server_config.get("read_config_from_api", False)
+
+ if not read_config_from_api:
+ # 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口
+ app.add_routes(
+ [
+ web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
+ web.post("/xiaozhi/ota/", self.ota_handler.handle_post),
+ web.options("/xiaozhi/ota/", self.ota_handler.handle_post),
+ ]
+ )
+ # 添加路由
+ app.add_routes(
+ [
+ web.get("/mcp/vision/explain", self.vision_handler.handle_get),
+ web.post("/mcp/vision/explain", self.vision_handler.handle_post),
+ web.options("/mcp/vision/explain", self.vision_handler.handle_post),
+ ]
+ )
+
+ # 运行服务
+ runner = web.AppRunner(app)
+ await runner.setup()
+ site = web.TCPSite(runner, host, port)
+ await site.start()
+
+ # 保持服务运行
+ while True:
+ await asyncio.sleep(3600) # 每隔 1 小时检查一次
diff --git a/main/xiaozhi-server/core/mcp/MCPClient.py b/main/xiaozhi-server/core/mcp/MCPClient.py
index 2ae34c292..5b7bab557 100644
--- a/main/xiaozhi-server/core/mcp/MCPClient.py
+++ b/main/xiaozhi-server/core/mcp/MCPClient.py
@@ -9,6 +9,7 @@ from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from mcp.client.sse import sse_client
from config.logger import setup_logging
+from core.utils.util import sanitize_tool_name
TAG = __name__
@@ -23,7 +24,9 @@ class MCPClient:
self._shutdown_evt = asyncio.Event()
self.session: Optional[ClientSession] = None
- self.tools: List = []
+ self.tools: List = [] # original tool objects
+ self.tools_dict: Dict[str, Any] = {}
+ self.name_mapping: Dict[str, str] = {}
async def initialize(self):
if self._worker_task:
@@ -32,7 +35,7 @@ class MCPClient:
await self._ready_evt.wait()
self.logger.bind(tag=TAG).info(
- f"Connected, tools = {[t.name for t in self.tools]}"
+ f"Connected, tools = {[name for name in self.name_mapping.values()]}"
)
async def cleanup(self):
@@ -48,27 +51,28 @@ class MCPClient:
self._worker_task = None
def has_tool(self, name: str) -> bool:
- return any(t.name == name for t in self.tools)
+ return name in self.tools_dict
def get_available_tools(self):
return [
{
"type": "function",
"function": {
- "name": t.name,
- "description": t.description,
- "parameters": t.inputSchema,
+ "name": name,
+ "description": tool.description,
+ "parameters": tool.inputSchema,
},
}
- for t in self.tools
+ for name, tool in self.tools_dict.items()
]
async def call_tool(self, name: str, args: dict):
if not self.session:
raise RuntimeError("MCPClient not initialized")
+ real_name = self.name_mapping.get(name, name)
loop = self._worker_task.get_loop()
- coro = self.session.call_tool(name, args)
+ coro = self.session.call_tool(real_name, args)
if loop is asyncio.get_running_loop():
return await coro
@@ -76,6 +80,27 @@ class MCPClient:
fut: concurrent.futures.Future = asyncio.run_coroutine_threadsafe(coro, loop)
return await asyncio.wrap_future(fut)
+ def is_connected(self) -> bool:
+ """检查MCP客户端是否连接正常
+
+ Returns:
+ bool: 如果客户端已连接并正常工作,返回True,否则返回False
+ """
+ # 检查工作任务是否存在
+ if self._worker_task is None:
+ return False
+
+ # 检查工作任务是否已经完成或取消
+ if self._worker_task.done():
+ return False
+
+ # 检查会话是否存在
+ if self.session is None:
+ return False
+
+ # 所有检查都通过,连接正常
+ return True
+
async def _worker(self):
async with AsyncExitStack() as stack:
try:
@@ -92,11 +117,21 @@ class MCPClient:
args=self.config.get("args", []),
env=env,
)
- stdio_r, stdio_w = await stack.enter_async_context(stdio_client(params))
+ stdio_r, stdio_w = await stack.enter_async_context(
+ stdio_client(params)
+ )
read_stream, write_stream = stdio_r, stdio_w
# 建立SSEClient
elif "url" in self.config:
- sse_r, sse_w = await stack.enter_async_context(sse_client(self.config["url"]))
+ if "API_ACCESS_TOKEN" in self.config:
+ headers = {
+ "Authorization": f"Bearer {self.config['API_ACCESS_TOKEN']}"
+ }
+ else:
+ headers = {}
+ sse_r, sse_w = await stack.enter_async_context(
+ sse_client(self.config["url"], headers=headers)
+ )
read_stream, write_stream = sse_r, sse_w
else:
@@ -113,6 +148,10 @@ class MCPClient:
# 获取工具
self.tools = (await self.session.list_tools()).tools
+ for t in self.tools:
+ sanitized = sanitize_tool_name(t.name)
+ self.tools_dict[sanitized] = t
+ self.name_mapping[sanitized] = t.name
self._ready_evt.set()
diff --git a/main/xiaozhi-server/core/mcp/manager.py b/main/xiaozhi-server/core/mcp/manager.py
index dc2f9de92..1c677e0e3 100644
--- a/main/xiaozhi-server/core/mcp/manager.py
+++ b/main/xiaozhi-server/core/mcp/manager.py
@@ -100,7 +100,7 @@ class MCPManager:
return False
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
- """执行工具调用
+ """执行工具调用,失败时会尝试重新连接
Args:
tool_name: 工具名称
arguments: 工具参数
@@ -112,11 +112,64 @@ class MCPManager:
self.conn.logger.bind(tag=TAG).info(
f"Executing tool {tool_name} with arguments: {arguments}"
)
- for client in self.client.values():
+
+ max_retries = 3 # 最大重试次数
+ retry_interval = 2 # 重试间隔(秒)
+
+ # 找到对应的客户端
+ client_name = None
+ target_client = None
+ for name, client in self.client.items():
if client.has_tool(tool_name):
- return await client.call_tool(tool_name, arguments)
-
- raise ValueError(f"Tool {tool_name} not found in any MCP server")
+ client_name = name
+ target_client = client
+ break
+
+ if not target_client:
+ raise ValueError(f"Tool {tool_name} not found in any MCP server")
+
+ # 带重试机制的工具调用
+ for attempt in range(max_retries):
+ try:
+ return await target_client.call_tool(tool_name, arguments)
+ except Exception as e:
+ # 最后一次尝试失败时直接抛出异常
+ if attempt == max_retries - 1:
+ raise
+
+ self.conn.logger.bind(tag=TAG).warning(
+ f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}"
+ )
+
+ # 尝试重新连接
+ self.conn.logger.bind(tag=TAG).info(
+ f"重试前尝试重新连接 MCP 客户端 {client_name}"
+ )
+ try:
+ # 关闭旧的连接
+ await target_client.cleanup()
+
+ # 重新初始化客户端
+ config = self.load_config()
+ if client_name in config:
+ client = MCPClient(config[client_name])
+ await client.initialize()
+ self.client[client_name] = client
+ target_client = client
+ self.conn.logger.bind(tag=TAG).info(
+ f"成功重新连接 MCP 客户端: {client_name}"
+ )
+ else:
+ self.conn.logger.bind(tag=TAG).error(
+ f"Cannot reconnect MCP client {client_name}: config not found"
+ )
+ except Exception as reconnect_error:
+ self.conn.logger.bind(tag=TAG).error(
+ f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
+ )
+
+ # 等待一段时间再重试
+ await asyncio.sleep(retry_interval)
async def cleanup_all(self) -> None:
"""依次关闭所有 MCPClient,不让异常阻断整体流程。"""
diff --git a/main/xiaozhi-server/core/providers/asr/aliyun.py b/main/xiaozhi-server/core/providers/asr/aliyun.py
index 6606168c9..36f417457 100644
--- a/main/xiaozhi-server/core/providers/asr/aliyun.py
+++ b/main/xiaozhi-server/core/providers/asr/aliyun.py
@@ -2,9 +2,6 @@ import http.client
import json
import asyncio
from typing import Optional, Tuple, List
-import opuslib_next
-import wave
-import io
import os
import uuid
import hmac
@@ -16,6 +13,7 @@ import time
from datetime import datetime
from config.logger import setup_logging
from core.providers.asr.base import ASRProviderBase
+from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
@@ -92,6 +90,7 @@ class AccessToken:
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
+ self.interface_type = InterfaceType.NON_STREAM
"""阿里云ASR初始化"""
# 新增空值判断逻辑
self.access_key_id = config.get("access_key_id")
@@ -155,12 +154,6 @@ class ASRProvider(ASRProviderBase):
# f"剩余 {remaining:.2f}秒")
return time.time() > self.expire_time
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
-
def _construct_request_url(self) -> str:
"""构造请求URL,包含参数"""
request = f"{self.base_url}?appkey={self.app_key}"
@@ -171,21 +164,6 @@ class ASRProvider(ASRProviderBase):
request += "&enable_voice_detection=false"
return request
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1) # 单声道
- wf.setsampwidth(2) # 16-bit
- wf.setframerate(self.sample_rate)
- wf.writeframes(b"".join(pcm_data))
-
- logger.bind(tag=TAG).debug(f"音频文件已保存至: {file_path}")
- return file_path
-
async def _send_request(self, pcm_data: bytes) -> Optional[str]:
"""发送请求到阿里云ASR服务"""
try:
@@ -235,7 +213,7 @@ class ASRProvider(ASRProviderBase):
return None
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
if self._is_token_expired():
@@ -245,7 +223,7 @@ class ASRProvider(ASRProviderBase):
file_path = None
try:
# 解码Opus为PCM
- if self.audio_format == "pcm":
+ if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
diff --git a/main/xiaozhi-server/core/providers/asr/baidu.py b/main/xiaozhi-server/core/providers/asr/baidu.py
index fe73fd457..aa8ea9015 100644
--- a/main/xiaozhi-server/core/providers/asr/baidu.py
+++ b/main/xiaozhi-server/core/providers/asr/baidu.py
@@ -1,18 +1,10 @@
-import base64
-import hashlib
-import hmac
-import json
import time
-from datetime import datetime, timezone
import os
-import uuid
from typing import Optional, Tuple, List
-import wave
-import opuslib_next
-
from aip import AipSpeech
from core.providers.asr.base import ASRProviderBase
from config.logger import setup_logging
+from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
@@ -21,6 +13,7 @@ logger = setup_logging()
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool = True):
super().__init__()
+ self.interface_type = InterfaceType.NON_STREAM
self.app_id = config.get("app_id")
self.api_key = config.get("api_key")
self.secret_key = config.get("secret_key")
@@ -36,22 +29,8 @@ class ASRProvider(ASRProviderBase):
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1)
- wf.setsampwidth(2) # 2 bytes = 16-bit
- wf.setframerate(16000)
- wf.writeframes(b"".join(pcm_data))
-
- return file_path
-
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
if not opus_data:
@@ -66,7 +45,7 @@ class ASRProvider(ASRProviderBase):
return None, file_path
# 将Opus音频数据解码为PCM
- if self.audio_format == "pcm":
+ if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py
index 227a906d8..71098a200 100644
--- a/main/xiaozhi-server/core/providers/asr/base.py
+++ b/main/xiaozhi-server/core/providers/asr/base.py
@@ -1,7 +1,19 @@
-from abc import ABC, abstractmethod
-from typing import Optional, Tuple, List
+import os
+import wave
+import copy
+import uuid
+import queue
+import asyncio
+import traceback
+import threading
import opuslib_next
+from abc import ABC, abstractmethod
from config.logger import setup_logging
+from typing import Optional, Tuple, List
+from core.handle.receiveAudioHandle import startToChat
+from core.handle.reportHandle import enqueue_asr_report
+from core.utils.util import remove_punctuation_and_length
+from core.handle.receiveAudioHandle import handleAudioMessage
TAG = __name__
logger = setup_logging()
@@ -9,36 +21,119 @@ logger = setup_logging()
class ASRProviderBase(ABC):
def __init__(self):
- self.audio_format = "opus"
+ pass
+
+ # 打开音频通道
+ # 这里默认是非流式的处理方式
+ # 流式处理方式请在子类中重写
+ async def open_audio_channels(self, conn):
+ # tts 消化线程
+ conn.asr_priority_thread = threading.Thread(
+ target=self.asr_text_priority_thread, args=(conn,), daemon=True
+ )
+ conn.asr_priority_thread.start()
+
+ # 有序处理ASR音频
+ def asr_text_priority_thread(self, conn):
+ while not conn.stop_event.is_set():
+ try:
+ message = conn.asr_audio_queue.get(timeout=1)
+ future = asyncio.run_coroutine_threadsafe(
+ handleAudioMessage(conn, message),
+ conn.loop,
+ )
+ future.result()
+ except queue.Empty:
+ continue
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ )
+ continue
+
+ # 接收音频
+ # 这里默认是非流式的处理方式
+ # 流式处理方式请在子类中重写
+ async def receive_audio(self, conn, audio, audio_have_voice):
+ if conn.client_listen_mode == "auto" or conn.client_listen_mode == "realtime":
+ have_voice = audio_have_voice
+ else:
+ have_voice = conn.client_have_voice
+ # 如果本次没有声音,本段也没声音,就把声音丢弃了
+ conn.asr_audio.append(audio)
+ if have_voice == False and conn.client_have_voice == False:
+ conn.asr_audio = conn.asr_audio[-10:]
+ return
+
+ # 如果本段有声音,且已经停止了
+ if conn.client_voice_stop:
+ asr_audio_task = copy.deepcopy(conn.asr_audio)
+ conn.asr_audio.clear()
+
+ # 音频太短了,无法识别
+ conn.reset_vad_states()
+ if len(asr_audio_task) > 15:
+ await self.handle_voice_stop(conn, asr_audio_task)
+
+ # 处理语音停止
+ async def handle_voice_stop(self, conn, asr_audio_task):
+ raw_text, _ = await self.speech_to_text(
+ asr_audio_task, conn.session_id, conn.audio_format
+ ) # 确保ASR模块返回原始文本
+ conn.logger.bind(tag=TAG).info(f"识别文本: {raw_text}")
+ text_len, _ = remove_punctuation_and_length(raw_text)
+ self.stop_ws_connection()
+ if text_len > 0:
+ # 使用自定义模块进行上报
+ await startToChat(conn, raw_text)
+ enqueue_asr_report(conn, raw_text, asr_audio_task)
+
+ def stop_ws_connection(self):
+ pass
- @abstractmethod
def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
"""PCM数据保存为WAV文件"""
- pass
+ module_name = __name__.split(".")[-1]
+ file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
+ file_path = os.path.join(self.output_dir, file_name)
+
+ with wave.open(file_path, "wb") as wf:
+ wf.setnchannels(1)
+ wf.setsampwidth(2) # 2 bytes = 16-bit
+ wf.setframerate(16000)
+ wf.writeframes(b"".join(pcm_data))
+
+ return file_path
@abstractmethod
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
pass
- def set_audio_format(self, format: str) -> None:
- """设置音频格式"""
- self.audio_format = format
-
@staticmethod
def decode_opus(opus_data: List[bytes]) -> bytes:
"""将Opus音频数据解码为PCM数据"""
+ try:
+ decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
+ pcm_data = []
+ buffer_size = 960 # 每次处理960个采样点
- decoder = opuslib_next.Decoder(16000, 1) # 16kHz, 单声道
- pcm_data = []
+ for opus_packet in opus_data:
+ try:
+ # 使用较小的缓冲区大小进行处理
+ pcm_frame = decoder.decode(opus_packet, buffer_size)
+ if pcm_frame:
+ pcm_data.append(pcm_frame)
+ except opuslib_next.OpusError as e:
+ logger.bind(tag=TAG).warning(f"Opus解码错误,跳过当前数据包: {e}")
+ continue
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"音频处理错误: {e}", exc_info=True)
+ continue
- for opus_packet in opus_data:
- try:
- pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
- pcm_data.append(pcm_frame)
- except opuslib_next.OpusError as e:
- logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
-
- return pcm_data
+ return pcm_data
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}", exc_info=True)
+ return []
diff --git a/main/xiaozhi-server/core/providers/asr/doubao.py b/main/xiaozhi-server/core/providers/asr/doubao.py
index 403c181f1..f6cd79c62 100644
--- a/main/xiaozhi-server/core/providers/asr/doubao.py
+++ b/main/xiaozhi-server/core/providers/asr/doubao.py
@@ -1,17 +1,14 @@
import time
-import io
-import wave
import os
-from typing import Optional, Tuple, List
import uuid
-import websockets
import json
import gzip
-
-import opuslib_next
-from core.providers.asr.base import ASRProviderBase
-
+import websockets
from config.logger import setup_logging
+from typing import Optional, Tuple, List
+from core.providers.asr.base import ASRProviderBase
+from core.providers.asr.dto.dto import InterfaceType
+
TAG = __name__
logger = setup_logging()
@@ -86,6 +83,7 @@ def parse_response(res):
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
+ self.interface_type = InterfaceType.NON_STREAM
self.appid = config.get("appid")
self.cluster = config.get("cluster")
self.access_token = config.get("access_token")
@@ -102,20 +100,6 @@ class ASRProvider(ASRProviderBase):
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1)
- wf.setsampwidth(2) # 2 bytes = 16-bit
- wf.setframerate(16000)
- wf.writeframes(b"".join(pcm_data))
-
- return file_path
-
@staticmethod
def _generate_header(
message_type=CLIENT_FULL_REQUEST, message_type_specific_flags=NO_SEQUENCE
@@ -184,6 +168,7 @@ class ASRProvider(ASRProviderBase):
if (
"payload_msg" in result
and result["payload_msg"]["code"] != self.success_code
+ and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误
):
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
@@ -219,6 +204,9 @@ class ASRProvider(ASRProviderBase):
if len(result["payload_msg"]["result"]) > 0:
return result["payload_msg"]["result"][0]["text"]
return None
+ elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
+ # 无有效语音,返回空字符串
+ return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
@@ -244,14 +232,14 @@ class ASRProvider(ASRProviderBase):
yield data[offset:data_len], True
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
file_path = None
try:
# 合并所有opus数据包
- if self.audio_format == "pcm":
+ if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
diff --git a/main/xiaozhi-server/core/providers/asr/doubao_stream.py b/main/xiaozhi-server/core/providers/asr/doubao_stream.py
new file mode 100644
index 000000000..31704b969
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/asr/doubao_stream.py
@@ -0,0 +1,351 @@
+import json
+import gzip
+import uuid
+import asyncio
+import websockets
+import opuslib_next
+from core.providers.asr.base import ASRProviderBase
+from config.logger import setup_logging
+from core.providers.asr.dto.dto import InterfaceType
+
+TAG = __name__
+logger = setup_logging()
+
+
+class ASRProvider(ASRProviderBase):
+ def __init__(self, config, delete_audio_file):
+ super().__init__()
+ self.interface_type = InterfaceType.STREAM
+ self.config = config
+ self.text = ""
+ self.max_retries = 3
+ self.retry_delay = 2
+ self.decoder = opuslib_next.Decoder(16000, 1)
+ self.asr_ws = None
+ self.forward_task = None
+ self.is_processing = False # 添加处理状态标志
+
+ # 配置参数
+ self.appid = str(config.get("appid"))
+ self.cluster = config.get("cluster")
+ self.access_token = config.get("access_token")
+ self.boosting_table_name = config.get("boosting_table_name", "")
+ self.correct_table_name = config.get("correct_table_name", "")
+ self.output_dir = config.get("output_dir", "tmp/")
+ self.delete_audio_file = delete_audio_file
+
+ # 火山引擎ASR配置
+ self.ws_url = "wss://openspeech.bytedance.com/api/v3/sauc/bigmodel"
+ self.uid = config.get("uid", "streaming_asr_service")
+ self.workflow = config.get(
+ "workflow", "audio_in,resample,partition,vad,fe,decode,itn,nlu_punctuate"
+ )
+ self.result_type = config.get("result_type", "single")
+ self.format = config.get("format", "pcm")
+ self.codec = config.get("codec", "pcm")
+ self.rate = config.get("sample_rate", 16000)
+ self.language = config.get("language", "zh-CN")
+ self.bits = config.get("bits", 16)
+ self.channel = config.get("channel", 1)
+ self.auth_method = config.get("auth_method", "token")
+ self.secret = config.get("secret", "access_secret")
+
+ async def open_audio_channels(self, conn):
+ await super().open_audio_channels(conn)
+
+ async def receive_audio(self, conn, audio, audio_have_voice):
+ conn.asr_audio.append(audio)
+ conn.asr_audio = conn.asr_audio[-10:]
+
+ # 如果本次有声音,且之前没有建立连接
+ if audio_have_voice and self.asr_ws is None and not self.is_processing:
+ try:
+ self.is_processing = True
+ # 建立新的WebSocket连接
+ headers = self.token_auth() if self.auth_method == "token" else None
+ logger.bind(tag=TAG).info(f"正在连接ASR服务,headers: {headers}")
+
+ self.asr_ws = await websockets.connect(
+ self.ws_url,
+ additional_headers=headers,
+ max_size=1000000000,
+ ping_interval=None,
+ ping_timeout=None,
+ close_timeout=10,
+ )
+
+ # 发送初始化请求
+ request_params = self.construct_request(str(uuid.uuid4()))
+ try:
+ payload_bytes = str.encode(json.dumps(request_params))
+ payload_bytes = gzip.compress(payload_bytes)
+ full_client_request = self.generate_header()
+ full_client_request.extend((len(payload_bytes)).to_bytes(4, "big"))
+ full_client_request.extend(payload_bytes)
+
+ logger.bind(tag=TAG).info(f"发送初始化请求: {request_params}")
+ await self.asr_ws.send(full_client_request)
+
+ # 等待初始化响应
+ init_res = await self.asr_ws.recv()
+ result = self.parse_response(init_res)
+ logger.bind(tag=TAG).info(f"收到初始化响应: {result}")
+
+ # 检查初始化响应
+ if "code" in result and result["code"] != 1000:
+ error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}"
+ logger.bind(tag=TAG).error(error_msg)
+ raise Exception(error_msg)
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"发送初始化请求失败: {str(e)}")
+ if hasattr(e, "__cause__") and e.__cause__:
+ logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ raise e
+
+ # 启动接收ASR结果的异步任务
+ self.forward_task = asyncio.create_task(self._forward_asr_results(conn))
+
+ # 发送缓存的音频数据
+ if conn.asr_audio and len(conn.asr_audio) > 0:
+ for cached_audio in conn.asr_audio[-10:]:
+ try:
+ pcm_frame = self.decoder.decode(cached_audio, 960)
+ payload = gzip.compress(pcm_frame)
+ audio_request = bytearray(
+ self.generate_audio_default_header()
+ )
+ audio_request.extend(len(payload).to_bytes(4, "big"))
+ audio_request.extend(payload)
+ await self.asr_ws.send(audio_request)
+ except Exception as e:
+ logger.bind(tag=TAG).info(
+ f"发送缓存音频数据时发生错误: {e}"
+ )
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
+ if hasattr(e, "__cause__") and e.__cause__:
+ logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ if self.asr_ws:
+ await self.asr_ws.close()
+ self.asr_ws = None
+ self.is_processing = False
+ return
+
+ # 发送当前音频数据
+ if self.asr_ws and self.is_processing:
+ try:
+ pcm_frame = self.decoder.decode(audio, 960)
+ payload = gzip.compress(pcm_frame)
+ audio_request = bytearray(self.generate_audio_default_header())
+ audio_request.extend(len(payload).to_bytes(4, "big"))
+ audio_request.extend(payload)
+ await self.asr_ws.send(audio_request)
+ except Exception as e:
+ logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}")
+
+ async def _forward_asr_results(self, conn):
+ try:
+ while self.asr_ws and not conn.stop_event.is_set():
+ try:
+ response = await self.asr_ws.recv()
+ result = self.parse_response(response)
+ logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
+
+ if "payload_msg" in result:
+ payload = result["payload_msg"]
+ # 检查是否是错误码1013(无有效语音)
+ if "code" in payload and payload["code"] == 1013:
+ # 静默处理,不记录错误日志
+ continue
+
+ if "result" in payload:
+ utterances = payload["result"].get("utterances", [])
+ # 检查duration和空文本的情况
+ if (
+ payload.get("audio_info", {}).get("duration", 0) > 2000
+ and not utterances
+ and not payload["result"].get("text")
+ ):
+ logger.bind(tag=TAG).error(f"识别文本:空")
+ self.text = ""
+ conn.reset_vad_states()
+ await self.handle_voice_stop(conn, None)
+ break
+
+ for utterance in utterances:
+ if utterance.get("definite", False):
+ self.text = utterance["text"]
+ logger.bind(tag=TAG).info(
+ f"识别到文本: {self.text}"
+ )
+ conn.reset_vad_states()
+ await self.handle_voice_stop(conn, None)
+ break
+ elif "error" in payload:
+ error_msg = payload.get("error", "未知错误")
+ logger.bind(tag=TAG).error(f"ASR服务返回错误: {error_msg}")
+ break
+
+ except websockets.ConnectionClosed:
+ logger.bind(tag=TAG).info("ASR服务连接已关闭")
+ self.is_processing = False
+ break
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
+ if hasattr(e, "__cause__") and e.__cause__:
+ logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ self.is_processing = False
+ break
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
+ if hasattr(e, "__cause__") and e.__cause__:
+ logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ finally:
+ if self.asr_ws:
+ await self.asr_ws.close()
+ self.asr_ws = None
+ self.is_processing = False
+
+ def stop_ws_connection(self):
+ if self.asr_ws:
+ asyncio.create_task(self.asr_ws.close())
+ self.asr_ws = None
+ self.is_processing = False
+
+ def construct_request(self, reqid):
+ req = {
+ "app": {
+ "appid": self.appid,
+ "cluster": self.cluster,
+ "token": self.access_token,
+ },
+ "user": {"uid": self.uid},
+ "request": {
+ "reqid": reqid,
+ "workflow": self.workflow,
+ "show_utterances": True,
+ "result_type": self.result_type,
+ "sequence": 1,
+ "boosting_table_name": self.boosting_table_name,
+ "correct_table_name": self.correct_table_name,
+ "end_window_size": 200,
+ },
+ "audio": {
+ "format": self.format,
+ "codec": self.codec,
+ "rate": self.rate,
+ "language": self.language,
+ "bits": self.bits,
+ "channel": self.channel,
+ "sample_rate": self.rate,
+ },
+ }
+ logger.bind(tag=TAG).debug(
+ f"构造请求参数: {json.dumps(req, ensure_ascii=False)}"
+ )
+ return req
+
+ def token_auth(self):
+ return {
+ "X-Api-App-Key": self.appid,
+ "X-Api-Access-Key": self.access_token,
+ "X-Api-Resource-Id": "volc.bigasr.sauc.duration",
+ "X-Api-Connect-Id": str(uuid.uuid4()),
+ }
+
+ def generate_header(
+ self,
+ version=0x01,
+ message_type=0x01,
+ message_type_specific_flags=0x00,
+ serial_method=0x01,
+ compression_type=0x01,
+ reserved_data=0x00,
+ extension_header: bytes = b"",
+ ):
+ header = bytearray()
+ header_size = int(len(extension_header) / 4) + 1
+ header.append((version << 4) | header_size)
+ header.append((message_type << 4) | message_type_specific_flags)
+ header.append((serial_method << 4) | compression_type)
+ header.append(reserved_data)
+ header.extend(extension_header)
+ return header
+
+ def generate_audio_default_header(self):
+ return self.generate_header(
+ version=0x01,
+ message_type=0x02,
+ message_type_specific_flags=0x00,
+ serial_method=0x01,
+ compression_type=0x01,
+ )
+
+ def generate_last_audio_default_header(self):
+ return self.generate_header(
+ version=0x01,
+ message_type=0x02,
+ message_type_specific_flags=0x02,
+ serial_method=0x01,
+ compression_type=0x01,
+ )
+
+ def parse_response(self, res: bytes) -> dict:
+ try:
+ # 检查响应长度
+ if len(res) < 4:
+ logger.bind(tag=TAG).error(f"响应数据长度不足: {len(res)}")
+ return {"error": "响应数据长度不足"}
+
+ # 获取消息头
+ header = res[:4]
+ message_type = header[1] >> 4
+
+ # 如果是错误响应
+ if message_type == 0x0F: # SERVER_ERROR_RESPONSE
+ code = int.from_bytes(res[4:8], "big", signed=False)
+ msg_length = int.from_bytes(res[8:12], "big", signed=False)
+ error_msg = json.loads(res[12:].decode("utf-8"))
+ return {
+ "code": code,
+ "msg_length": msg_length,
+ "payload_msg": error_msg,
+ }
+
+ # 获取JSON数据(跳过12字节头部)
+ try:
+ json_data = res[12:].decode("utf-8")
+ result = json.loads(json_data)
+ logger.bind(tag=TAG).debug(f"成功解析JSON响应: {result}")
+ return {"payload_msg": result}
+ except (UnicodeDecodeError, json.JSONDecodeError) as e:
+ logger.bind(tag=TAG).error(f"JSON解析失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"原始数据: {res}")
+ raise
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"解析响应失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}")
+ raise
+
+ async def speech_to_text(self, opus_data, session_id, audio_format):
+ result = self.text
+ self.text = "" # 清空text
+ return result, None
+
+ async def close(self):
+ """资源清理方法"""
+ if self.asr_ws:
+ await self.asr_ws.close()
+ self.asr_ws = None
+ if self.forward_task:
+ self.forward_task.cancel()
+ try:
+ await self.forward_task
+ except asyncio.CancelledError:
+ pass
+ self.forward_task = None
+ self.is_processing = False
diff --git a/main/xiaozhi-server/core/providers/asr/dto/dto.py b/main/xiaozhi-server/core/providers/asr/dto/dto.py
new file mode 100644
index 000000000..85b2d7b21
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/asr/dto/dto.py
@@ -0,0 +1,9 @@
+from enum import Enum
+from typing import Union, Optional
+
+
+class InterfaceType(Enum):
+ # 接口类型
+ STREAM = "STREAM" # 流式接口
+ NON_STREAM = "NON_STREAM" # 非流式接口
+ LOCAL = "LOCAL" # 本地服务
diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py
index ec3df17f1..217f17ff7 100644
--- a/main/xiaozhi-server/core/providers/asr/fun_local.py
+++ b/main/xiaozhi-server/core/providers/asr/fun_local.py
@@ -1,18 +1,22 @@
import time
-import wave
import os
import sys
import io
+import psutil
from config.logger import setup_logging
from typing import Optional, Tuple, List
-import uuid
from core.providers.asr.base import ASRProviderBase
from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess
+import shutil
+from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
+MAX_RETRIES = 2
+RETRY_DELAY = 1 # 重试延迟(秒)
+
# 捕获标准输出
class CaptureOutput:
@@ -34,6 +38,14 @@ class CaptureOutput:
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
+
+ # 内存检测,要求大于2G
+ min_mem_bytes = 2 * 1024 * 1024 * 1024
+ total_mem = psutil.virtual_memory().total
+ if total_mem < min_mem_bytes:
+ logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR")
+
+ self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir") # 修正配置键名
self.delete_audio_file = delete_audio_file
@@ -49,65 +61,74 @@ class ASRProvider(ASRProviderBase):
# device="cuda:0", # 启用GPU加速
)
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1)
- wf.setsampwidth(2) # 2 bytes = 16-bit
- wf.setframerate(16000)
- wf.writeframes(b"".join(pcm_data))
-
- return file_path
-
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""语音转文本主处理逻辑"""
file_path = None
- try:
- # 合并所有opus数据包
- if self.audio_format == "pcm":
- pcm_data = opus_data
- else:
- pcm_data = self.decode_opus(opus_data)
+ retry_count = 0
- combined_pcm_data = b"".join(pcm_data)
+ while retry_count < MAX_RETRIES:
+ try:
+ # 合并所有opus数据包
+ if audio_format == "pcm":
+ pcm_data = opus_data
+ else:
+ pcm_data = self.decode_opus(opus_data)
- # 判断是否保存为WAV文件
- if self.delete_audio_file:
- pass
- else:
- file_path = self.save_audio_to_file(pcm_data, session_id)
+ combined_pcm_data = b"".join(pcm_data)
- # 语音识别
- start_time = time.time()
- result = self.model.generate(
- input=combined_pcm_data,
- cache={},
- language="auto",
- use_itn=True,
- batch_size_s=60,
- )
- text = rich_transcription_postprocess(result[0]["text"])
- logger.bind(tag=TAG).debug(
- f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
- )
+ # 检查磁盘空间
+ if not self.delete_audio_file:
+ free_space = shutil.disk_usage(self.output_dir).free
+ if free_space < len(combined_pcm_data) * 2: # 预留2倍空间
+ raise OSError("磁盘空间不足")
- return text, file_path
+ # 判断是否保存为WAV文件
+ if self.delete_audio_file:
+ pass
+ else:
+ file_path = self.save_audio_to_file(pcm_data, session_id)
- except Exception as e:
- logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
- return "", file_path
+ # 语音识别
+ start_time = time.time()
+ result = self.model.generate(
+ input=combined_pcm_data,
+ cache={},
+ language="auto",
+ use_itn=True,
+ batch_size_s=60,
+ )
+ text = rich_transcription_postprocess(result[0]["text"])
+ logger.bind(tag=TAG).debug(
+ f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
+ )
- # finally:
- # # 文件清理逻辑
- # if self.delete_audio_file and file_path and os.path.exists(file_path):
- # try:
- # os.remove(file_path)
- # logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
- # except Exception as e:
- # logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
+ return text, file_path
+
+ except OSError as e:
+ retry_count += 1
+ if retry_count >= MAX_RETRIES:
+ logger.bind(tag=TAG).error(
+ f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
+ )
+ return "", file_path
+ logger.bind(tag=TAG).warning(
+ f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
+ )
+ time.sleep(RETRY_DELAY)
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
+ return "", file_path
+
+ finally:
+ # 文件清理逻辑
+ if self.delete_audio_file and file_path and os.path.exists(file_path):
+ try:
+ os.remove(file_path)
+ logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"文件删除失败: {file_path} | 错误: {e}"
+ )
diff --git a/main/xiaozhi-server/core/providers/asr/fun_server.py b/main/xiaozhi-server/core/providers/asr/fun_server.py
index 97c9fdc9f..7eb9e7848 100644
--- a/main/xiaozhi-server/core/providers/asr/fun_server.py
+++ b/main/xiaozhi-server/core/providers/asr/fun_server.py
@@ -1,11 +1,8 @@
from typing import Optional, Tuple, List
-import opuslib_next
from core.providers.asr.base import ASRProviderBase
-import os
+from core.providers.asr.dto.dto import InterfaceType
import ssl
import json
-import uuid
-import wave
import websockets
from config.logger import setup_logging
import asyncio
@@ -23,6 +20,7 @@ class ASRProvider(ASRProviderBase):
:param delete_audio_file: Boolean to indicate whether to delete audio files after processing.
"""
super().__init__()
+ self.interface_type = InterfaceType.NON_STREAM
self.host = config.get("host", "localhost")
self.port = config.get("port", 10095)
self.api_key = config.get("api_key", "none")
@@ -43,20 +41,6 @@ class ASRProvider(ASRProviderBase):
self.ssl_context.check_hostname = False
self.ssl_context.verify_mode = ssl.CERT_NONE
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1)
- wf.setsampwidth(2) # 2 bytes = 16-bit
- wf.setframerate(16000)
- wf.writeframes(b"".join(pcm_data))
-
- return file_path
-
async def _receive_responses(self, ws) -> None:
"""
Asynchronous generator to receive messages from the WebSocket.
@@ -116,7 +100,7 @@ class ASRProvider(ASRProviderBase):
logger.bind(tag=TAG).debug(f"Sent end message: {end_message}")
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""
Convert speech data to text using FunASR.
@@ -125,7 +109,7 @@ class ASRProvider(ASRProviderBase):
:return: Tuple containing recognized text and optional timestamp.
"""
file_path = None
- if self.audio_format == "pcm":
+ if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
diff --git a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
index 667e1606d..9e5ade806 100644
--- a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
+++ b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
@@ -5,8 +5,7 @@ import sys
import io
from config.logger import setup_logging
from typing import Optional, Tuple, List
-import uuid
-import opuslib_next
+from core.providers.asr.dto.dto import InterfaceType
from core.providers.asr.base import ASRProviderBase
import numpy as np
@@ -38,6 +37,7 @@ class CaptureOutput:
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
+ self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
@@ -84,20 +84,6 @@ class ASRProvider(ASRProviderBase):
use_itn=True,
)
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1)
- wf.setsampwidth(2) # 2 bytes = 16-bit
- wf.setframerate(16000)
- wf.writeframes(b"".join(pcm_data))
-
- return file_path
-
def read_wave(self, wave_filename: str) -> Tuple[np.ndarray, int]:
"""
Args:
@@ -123,14 +109,14 @@ class ASRProvider(ASRProviderBase):
return samples_float32, f.getframerate()
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""语音转文本主处理逻辑"""
file_path = None
try:
# 保存音频文件
start_time = time.time()
- if self.audio_format == "pcm":
+ if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
diff --git a/main/xiaozhi-server/core/providers/asr/tencent.py b/main/xiaozhi-server/core/providers/asr/tencent.py
index 5ab1befb5..1fd1c6f42 100644
--- a/main/xiaozhi-server/core/providers/asr/tencent.py
+++ b/main/xiaozhi-server/core/providers/asr/tencent.py
@@ -5,11 +5,8 @@ import json
import time
from datetime import datetime, timezone
import os
-import uuid
from typing import Optional, Tuple, List
-import wave
-import opuslib_next
-
+from core.providers.asr.dto.dto import InterfaceType
import requests
from core.providers.asr.base import ASRProviderBase
from config.logger import setup_logging
@@ -25,6 +22,7 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool = True):
super().__init__()
+ self.interface_type = InterfaceType.NON_STREAM
self.secret_id = config.get("secret_id")
self.secret_key = config.get("secret_key")
self.output_dir = config.get("output_dir")
@@ -33,22 +31,8 @@ class ASRProvider(ASRProviderBase):
# 确保输出目录存在
os.makedirs(self.output_dir, exist_ok=True)
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
-
- with wave.open(file_path, "wb") as wf:
- wf.setnchannels(1)
- wf.setsampwidth(2) # 2 bytes = 16-bit
- wf.setframerate(16000)
- wf.writeframes(b"".join(pcm_data))
-
- return file_path
-
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本"""
if not opus_data:
@@ -63,7 +47,7 @@ class ASRProvider(ASRProviderBase):
return None, file_path
# 将Opus音频数据解码为PCM
- if self.audio_format == "pcm":
+ if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
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 2a3e023f0..d13c4df4a 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
@@ -53,6 +53,8 @@ class IntentProvider(IntentProviderBase):
prompt = (
"你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
+ "- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n"
+ "- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n"
f"{functions_desc}\n"
"处理步骤:\n"
"1. 分析用户输入,确定用户意图\n"
@@ -70,6 +72,18 @@ class IntentProvider(IntentProviderBase):
'返回: {"function_call": {"name": "get_time"}}\n'
"```\n"
"```\n"
+ "用户: 当前电池电量是多少?\n"
+ '返回: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "当前电池电量为{value}%", "response_failure": "无法获取Battery的当前电量百分比"}}}\n'
+ "```\n"
+ "```\n"
+ "用户: 当前屏幕亮度是多少?\n"
+ '返回: {"function_call": {"name": "self_screen_get_brightness"}}\n'
+ "```\n"
+ "```\n"
+ "用户: 设置屏幕亮度为50%\n"
+ '返回: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
+ "```\n"
+ "```\n"
"用户: 我想结束对话\n"
'返回: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
"```\n"
@@ -81,6 +95,10 @@ class IntentProvider(IntentProviderBase):
"1. 只返回JSON格式,不要包含任何其他文字\n"
'2. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
"3. 确保返回的JSON格式正确,包含所有必要的字段\n"
+ "特殊说明:\n"
+ "- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n"
+ "- 请返回多个function_call组成的JSON数组\n"
+ "- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}"
)
return prompt
@@ -116,6 +134,8 @@ class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
if not self.llm:
raise ValueError("LLM provider not set")
+ if conn.func_handler is None:
+ return '{"function_call": {"name": "continue_chat"}}'
# 记录整体开始时间
total_start_time = time.time()
@@ -142,15 +162,25 @@ class IntentProvider(IntentProviderBase):
self.clean_cache()
if self.promot == "":
- if hasattr(conn, "func_handler"):
- functions = conn.func_handler.get_functions()
- self.promot = self.get_intent_system_prompt(functions)
+ functions = conn.func_handler.get_functions()
+ if hasattr(conn, "mcp_client"):
+ mcp_tools = conn.mcp_client.get_available_tools()
+ if mcp_tools is not None and len(mcp_tools) > 0:
+ if functions is None:
+ functions = []
+ functions.extend(mcp_tools)
+
+ self.promot = self.get_intent_system_prompt(functions)
music_config = initialize_music_handler(conn)
music_file_names = music_config["music_file_names"]
prompt_music = f"{self.promot}\n{music_file_names}\n"
- devices = conn.config["plugins"]["home_assistant"].get("devices", [])
+ 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:
hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
for device in devices:
@@ -222,7 +252,8 @@ class IntentProvider(IntentProviderBase):
if function_name == "continue_chat":
# 保留非工具相关的消息
clean_history = [
- msg for msg in conn.dialogue.dialogue
+ msg
+ for msg in conn.dialogue.dialogue
if msg.role not in ["tool", "function"]
]
conn.dialogue.dialogue = clean_history
diff --git a/main/xiaozhi-server/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py
index 97d0d8e72..777861403 100644
--- a/main/xiaozhi-server/core/providers/llm/base.py
+++ b/main/xiaozhi-server/core/providers/llm/base.py
@@ -10,7 +10,7 @@ class LLMProviderBase(ABC):
"""LLM response generator"""
pass
- def response_no_stream(self, system_prompt, user_prompt):
+ def response_no_stream(self, system_prompt, user_prompt, **kwargs):
try:
# 构造对话格式
dialogue = [
@@ -18,7 +18,7 @@ class LLMProviderBase(ABC):
{"role": "user", "content": user_prompt}
]
result = ""
- for part in self.response("", dialogue):
+ for part in self.response("", dialogue, **kwargs):
result += part
return result
@@ -30,7 +30,7 @@ class LLMProviderBase(ABC):
"""
Default implementation for function calling (streaming)
This should be overridden by providers that support function calls
-
+
Returns: generator that yields either text tokens or a special function call token
"""
# For providers that don't support functions, just return regular response
diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py
index 60a046670..31a7d4ac3 100644
--- a/main/xiaozhi-server/core/providers/llm/coze/coze.py
+++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py
@@ -23,9 +23,11 @@ class LLMProvider(LLMProviderBase):
self.bot_id = str(config.get("bot_id"))
self.user_id = str(config.get("user_id"))
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
- check_model_key("CozeLLM", self.personal_access_token)
+ model_key_msg = check_model_key("CozeLLM", self.personal_access_token)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
coze_api_token = self.personal_access_token
coze_api_base = COZE_CN_BASE_URL
diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py
index 52ca9853e..4ec04ec76 100644
--- a/main/xiaozhi-server/core/providers/llm/dify/dify.py
+++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py
@@ -15,9 +15,11 @@ class LLMProvider(LLMProviderBase):
self.mode = config.get("mode", "chat-messages")
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip("/")
self.session_conversation_map = {} # 存储session_id和conversation_id的映射
- check_model_key("DifyLLM", self.api_key)
+ model_key_msg = check_model_key("DifyLLM", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
try:
# 取最后一条用户消息
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
diff --git a/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py b/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py
index b2e9d6b7b..4f3f4259c 100644
--- a/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py
+++ b/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py
@@ -14,9 +14,11 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url")
self.detail = config.get("detail", False)
self.variables = config.get("variables", {})
- check_model_key("FastGPTLLM", self.api_key)
+ model_key_msg = check_model_key("FastGPTLLM", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
try:
# 取最后一条用户消息
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
diff --git a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
index d1cf238e6..608e83878 100644
--- a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
+++ b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
@@ -73,8 +73,9 @@ class LLMProvider(LLMProviderBase):
http_proxy = cfg.get("http_proxy")
https_proxy = cfg.get("https_proxy")
- if not check_model_key("LLM", self.api_key):
- raise ValueError("无效的Gemini API Key,请检查是否配置正确")
+ model_key_msg = check_model_key("LLM", self.api_key)
+ if model_key_msg:
+ log.bind(tag=TAG).error(model_key_msg)
if http_proxy or https_proxy:
log.bind(tag=TAG).info(
@@ -112,7 +113,7 @@ class LLMProvider(LLMProviderBase):
]
# Gemini文档提到,无需维护session-id,直接用dialogue拼接而成
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
yield from self._generate(dialogue, None)
def response_with_functions(self, session_id, dialogue, functions=None):
diff --git a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
index c436fc9e0..f203e5f7d 100644
--- a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
+++ b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
@@ -14,7 +14,7 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url
self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
try:
# home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
index aad6354f9..c973cacd8 100644
--- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
+++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
@@ -18,13 +18,13 @@ class LLMProvider(LLMProviderBase):
self.client = OpenAI(
base_url=self.base_url,
- api_key="ollama" # Ollama doesn't need an API key but OpenAI client requires one
+ api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
)
# 检查是否是qwen3模型
self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3")
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
try:
# 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
if self.is_qwen3:
@@ -35,7 +35,9 @@ class LLMProvider(LLMProviderBase):
for i in range(len(dialogue_copy) - 1, -1, -1):
if dialogue_copy[i]["role"] == "user":
# 在用户消息前添加/no_think指令
- dialogue_copy[i]["content"] = "/no_think " + dialogue_copy[i]["content"]
+ dialogue_copy[i]["content"] = (
+ "/no_think " + dialogue_copy[i]["content"]
+ )
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
break
@@ -43,9 +45,7 @@ class LLMProvider(LLMProviderBase):
dialogue = dialogue_copy
responses = self.client.chat.completions.create(
- model=self.model_name,
- messages=dialogue,
- stream=True
+ model=self.model_name, messages=dialogue, stream=True
)
is_active = True
# 用于处理跨chunk的标签
@@ -53,29 +53,33 @@ class LLMProvider(LLMProviderBase):
for chunk in responses:
try:
- delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None
- content = delta.content if hasattr(delta, 'content') else ''
+ delta = (
+ chunk.choices[0].delta
+ if getattr(chunk, "choices", None)
+ else None
+ )
+ content = delta.content if hasattr(delta, "content") else ""
if content:
# 将内容添加到缓冲区
buffer += content
# 处理缓冲区中的标签
- while '' in buffer and '' in buffer:
+ while "" in buffer and "" in buffer:
# 找到完整的标签并移除
- pre = buffer.split('', 1)[0]
- post = buffer.split('', 1)[1]
+ pre = buffer.split("", 1)[0]
+ post = buffer.split("", 1)[1]
buffer = pre + post
# 处理只有开始标签的情况
- if '' in buffer:
+ if "" in buffer:
is_active = False
- buffer = buffer.split('', 1)[0]
+ buffer = buffer.split("", 1)[0]
# 处理只有结束标签的情况
- if '' in buffer:
+ if "" in buffer:
is_active = True
- buffer = buffer.split('', 1)[1]
+ buffer = buffer.split("", 1)[1]
# 如果当前处于活动状态且缓冲区有内容,则输出
if is_active and buffer:
@@ -100,7 +104,9 @@ class LLMProvider(LLMProviderBase):
for i in range(len(dialogue_copy) - 1, -1, -1):
if dialogue_copy[i]["role"] == "user":
# 在用户消息前添加/no_think指令
- dialogue_copy[i]["content"] = "/no_think " + dialogue_copy[i]["content"]
+ dialogue_copy[i]["content"] = (
+ "/no_think " + dialogue_copy[i]["content"]
+ )
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
break
@@ -119,9 +125,15 @@ class LLMProvider(LLMProviderBase):
for chunk in stream:
try:
- delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None
- content = delta.content if hasattr(delta, 'content') else None
- tool_calls = delta.tool_calls if hasattr(delta, 'tool_calls') else None
+ delta = (
+ chunk.choices[0].delta
+ if getattr(chunk, "choices", None)
+ else None
+ )
+ content = delta.content if hasattr(delta, "content") else None
+ tool_calls = (
+ delta.tool_calls if hasattr(delta, "tool_calls") else None
+ )
# 如果是工具调用,直接传递
if tool_calls:
@@ -134,21 +146,21 @@ class LLMProvider(LLMProviderBase):
buffer += content
# 处理缓冲区中的标签
- while '' in buffer and '' in buffer:
+ while "" in buffer and "" in buffer:
# 找到完整的标签并移除
- pre = buffer.split('', 1)[0]
- post = buffer.split('', 1)[1]
+ pre = buffer.split("", 1)[0]
+ post = buffer.split("", 1)[1]
buffer = pre + post
# 处理只有开始标签的情况
- if '' in buffer:
+ if "" in buffer:
is_active = False
- buffer = buffer.split('', 1)[0]
+ buffer = buffer.split("", 1)[0]
# 处理只有结束标签的情况
- if '' in buffer:
+ if "" in buffer:
is_active = True
- buffer = buffer.split('', 1)[1]
+ buffer = buffer.split("", 1)[1]
# 如果当前处于活动状态且缓冲区有内容,则输出
if is_active and buffer:
diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py
index a20067af0..a5ee29b66 100644
--- a/main/xiaozhi-server/core/providers/llm/openai/openai.py
+++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py
@@ -16,26 +16,46 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url")
else:
self.base_url = config.get("url")
- max_tokens = config.get("max_tokens")
- if max_tokens is None or max_tokens == "":
- max_tokens = 500
- try:
- max_tokens = int(max_tokens)
- except (ValueError, TypeError):
- max_tokens = 500
- self.max_tokens = max_tokens
+ param_defaults = {
+ "max_tokens": (500, int),
+ "temperature": (0.7, lambda x: round(float(x), 1)),
+ "top_p": (1.0, lambda x: round(float(x), 1)),
+ "frequency_penalty": (0, lambda x: round(float(x), 1)),
+ }
- check_model_key("LLM", self.api_key)
+ for param, (default, converter) in param_defaults.items():
+ value = config.get(param)
+ try:
+ setattr(
+ self,
+ param,
+ converter(value) if value not in (None, "") else default,
+ )
+ except (ValueError, TypeError):
+ setattr(self, param, default)
+
+ logger.debug(
+ f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
+ )
+
+ model_key_msg = check_model_key("LLM", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
try:
responses = self.client.chat.completions.create(
model=self.model_name,
messages=dialogue,
stream=True,
- max_tokens=self.max_tokens,
+ max_tokens=kwargs.get("max_tokens", self.max_tokens),
+ temperature=kwargs.get("temperature", self.temperature),
+ top_p=kwargs.get("top_p", self.top_p),
+ frequency_penalty=kwargs.get(
+ "frequency_penalty", self.frequency_penalty
+ ),
)
is_active = True
@@ -73,12 +93,14 @@ class LLMProvider(LLMProviderBase):
for chunk in stream:
# 检查是否存在有效的choice且content不为空
if getattr(chunk, "choices", None):
- yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls
+ yield chunk.choices[0].delta.content, chunk.choices[
+ 0
+ ].delta.tool_calls
# 存在 CompletionUsage 消息时,生成 Token 消耗 log
- elif isinstance(getattr(chunk, 'usage', None), CompletionUsage):
- usage_info = getattr(chunk, 'usage', None)
+ elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
+ usage_info = getattr(chunk, "usage", None)
logger.bind(tag=TAG).info(
- f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
+ f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
)
diff --git a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py
index b90b0418d..a4e9a5e6c 100644
--- a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py
+++ b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py
@@ -15,39 +15,45 @@ class LLMProvider(LLMProviderBase):
# 如果没有v1,增加v1
if not self.base_url.endswith("/v1"):
self.base_url = f"{self.base_url}/v1"
-
- logger.bind(tag=TAG).info(f"Initializing Xinference LLM provider with model: {self.model_name}, base_url: {self.base_url}")
+
+ logger.bind(tag=TAG).info(
+ f"Initializing Xinference LLM provider with model: {self.model_name}, base_url: {self.base_url}"
+ )
try:
self.client = OpenAI(
base_url=self.base_url,
- api_key="xinference" # Xinference has a similar setup to Ollama where it doesn't need an actual key
+ api_key="xinference", # Xinference has a similar setup to Ollama where it doesn't need an actual key
)
logger.bind(tag=TAG).info("Xinference client initialized successfully")
except Exception as e:
logger.bind(tag=TAG).error(f"Error initializing Xinference client: {e}")
raise
- def response(self, session_id, dialogue):
+ def response(self, session_id, dialogue, **kwargs):
try:
- logger.bind(tag=TAG).debug(f"Sending request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}")
- responses = self.client.chat.completions.create(
- model=self.model_name,
- messages=dialogue,
- stream=True
+ logger.bind(tag=TAG).debug(
+ f"Sending request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}"
)
- is_active=True
+ responses = self.client.chat.completions.create(
+ model=self.model_name, messages=dialogue, stream=True
+ )
+ is_active = True
for chunk in responses:
try:
- delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None
- content = delta.content if hasattr(delta, 'content') else ''
+ delta = (
+ chunk.choices[0].delta
+ if getattr(chunk, "choices", None)
+ else None
+ )
+ content = delta.content if hasattr(delta, "content") else ""
if content:
- if '' in content:
+ if "" in content:
is_active = False
- content = content.split('')[0]
- if '' in content:
+ content = content.split("")[0]
+ if "" in content:
is_active = True
- content = content.split('')[-1]
+ content = content.split("")[-1]
if is_active:
yield content
except Exception as e:
@@ -59,10 +65,14 @@ class LLMProvider(LLMProviderBase):
def response_with_functions(self, session_id, dialogue, functions=None):
try:
- logger.bind(tag=TAG).debug(f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}")
+ logger.bind(tag=TAG).debug(
+ f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}"
+ )
if functions:
- logger.bind(tag=TAG).debug(f"Function calls enabled with: {[f.get('function', {}).get('name') for f in functions]}")
-
+ logger.bind(tag=TAG).debug(
+ f"Function calls enabled with: {[f.get('function', {}).get('name') for f in functions]}"
+ )
+
stream = self.client.chat.completions.create(
model=self.model_name,
messages=dialogue,
@@ -74,7 +84,7 @@ class LLMProvider(LLMProviderBase):
delta = chunk.choices[0].delta
content = delta.content
tool_calls = delta.tool_calls
-
+
if content:
yield content, tool_calls
elif tool_calls:
@@ -82,4 +92,7 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Xinference function call: {e}")
- yield {"type": "content", "content": f"【Xinference服务响应异常: {str(e)}】"}
+ yield {
+ "type": "content",
+ "content": f"【Xinference服务响应异常: {str(e)}】",
+ }
diff --git a/main/xiaozhi-server/core/providers/memory/base.py b/main/xiaozhi-server/core/providers/memory/base.py
index 19dcabb85..2ced898dd 100644
--- a/main/xiaozhi-server/core/providers/memory/base.py
+++ b/main/xiaozhi-server/core/providers/memory/base.py
@@ -9,7 +9,9 @@ class MemoryProviderBase(ABC):
def __init__(self, config):
self.config = config
self.role_id = None
- self.llm = None
+
+ def set_llm(self, llm):
+ self.llm = llm
@abstractmethod
async def save_memory(self, msgs):
diff --git a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py
index 6ef3bc8c1..d61d73f3e 100644
--- a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py
+++ b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py
@@ -12,12 +12,14 @@ class MemoryProvider(MemoryProviderBase):
super().__init__(config)
self.api_key = config.get("api_key", "")
self.api_version = config.get("api_version", "v1.1")
- have_key = check_model_key("Mem0ai", self.api_key)
- if not have_key:
+ model_key_msg = check_model_key("Mem0ai", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
self.use_mem0 = False
return
else:
self.use_mem0 = True
+
try:
self.client = MemoryClient(api_key=self.api_key)
logger.bind(tag=TAG).info("成功连接到 Mem0ai 服务")
diff --git a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py
index a916e6c9d..236f3e7f3 100644
--- a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py
+++ b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py
@@ -5,6 +5,7 @@ import os
import yaml
from config.config_loader import get_project_dir
from config.manage_api_client import save_mem_local_short
+from core.utils.util import check_model_key
short_term_memory_prompt = """
@@ -107,7 +108,7 @@ TAG = __name__
class MemoryProvider(MemoryProviderBase):
def __init__(self, config, summary_memory):
super().__init__(config)
- self.short_momery = ""
+ self.short_memory = ""
self.save_to_file = True
self.memory_path = get_project_dir() + "data/.memory.yaml"
self.load_memory(summary_memory)
@@ -122,7 +123,7 @@ class MemoryProvider(MemoryProviderBase):
def load_memory(self, summary_memory):
# api获取到总结记忆后直接返回
if summary_memory or not self.save_to_file:
- self.short_momery = summary_memory
+ self.short_memory = summary_memory
return
all_memory = {}
@@ -130,18 +131,25 @@ class MemoryProvider(MemoryProviderBase):
with open(self.memory_path, "r", encoding="utf-8") as f:
all_memory = yaml.safe_load(f) or {}
if self.role_id in all_memory:
- self.short_momery = all_memory[self.role_id]
+ self.short_memory = all_memory[self.role_id]
def save_memory_to_file(self):
all_memory = {}
if os.path.exists(self.memory_path):
with open(self.memory_path, "r", encoding="utf-8") as f:
all_memory = yaml.safe_load(f) or {}
- all_memory[self.role_id] = self.short_momery
+ all_memory[self.role_id] = self.short_memory
with open(self.memory_path, "w", encoding="utf-8") as f:
yaml.dump(all_memory, f, allow_unicode=True)
async def save_memory(self, msgs):
+ # 打印使用的模型信息
+ model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
+ logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
+ api_key = getattr(self.llm, "api_key", None)
+ memory_key_msg = check_model_key("记忆总结专用LLM", api_key)
+ if memory_key_msg:
+ logger.bind(tag=TAG).error(memory_key_msg)
if self.llm is None:
logger.bind(tag=TAG).error("LLM is not set for memory provider")
return None
@@ -155,31 +163,39 @@ class MemoryProvider(MemoryProviderBase):
msgStr += f"User: {msg.content}\n"
elif msg.role == "assistant":
msgStr += f"Assistant: {msg.content}\n"
- if self.short_momery and len(self.short_momery) > 0:
+ if self.short_memory and len(self.short_memory) > 0:
msgStr += "历史记忆:\n"
- msgStr += self.short_momery
+ msgStr += self.short_memory
# 当前时间
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
msgStr += f"当前时间:{time_str}"
if self.save_to_file:
- result = self.llm.response_no_stream(short_term_memory_prompt, msgStr)
+ result = self.llm.response_no_stream(
+ short_term_memory_prompt,
+ msgStr,
+ max_tokens=2000,
+ temperature=0.2,
+ )
json_str = extract_json_data(result)
try:
json.loads(json_str) # 检查json格式是否正确
- self.short_momery = json_str
+ self.short_memory = json_str
self.save_memory_to_file()
except Exception as e:
print("Error:", e)
else:
result = self.llm.response_no_stream(
- short_term_memory_prompt_only_content, msgStr
+ short_term_memory_prompt_only_content,
+ msgStr,
+ max_tokens=2000,
+ temperature=0.2,
)
save_mem_local_short(self.role_id, result)
logger.bind(tag=TAG).info(f"Save memory successful - Role: {self.role_id}")
- return self.short_momery
+ return self.short_memory
async def query_memory(self, query: str) -> str:
- return self.short_momery
+ return self.short_memory
diff --git a/main/xiaozhi-server/core/providers/tts/aliyun.py b/main/xiaozhi-server/core/providers/tts/aliyun.py
index 61ab43643..c9b3d1307 100644
--- a/main/xiaozhi-server/core/providers/tts/aliyun.py
+++ b/main/xiaozhi-server/core/providers/tts/aliyun.py
@@ -1,4 +1,3 @@
-import os
import uuid
import json
import hmac
@@ -8,61 +7,74 @@ import requests
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
-import http.client
-import urllib.parse
import time
import uuid
from urllib import parse
+
+
class AccessToken:
@staticmethod
def _encode_text(text):
encoded_text = parse.quote_plus(text)
- return encoded_text.replace('+', '%20').replace('*', '%2A').replace('%7E', '~')
-
+ return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
+
@staticmethod
def _encode_dict(dic):
keys = dic.keys()
dic_sorted = [(key, dic[key]) for key in sorted(keys)]
encoded_text = parse.urlencode(dic_sorted)
- return encoded_text.replace('+', '%20').replace('*', '%2A').replace('%7E', '~')
-
+ return encoded_text.replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
+
@staticmethod
def create_token(access_key_id, access_key_secret):
- parameters = {'AccessKeyId': access_key_id,
- 'Action': 'CreateToken',
- 'Format': 'JSON',
- 'RegionId': 'cn-shanghai',
- 'SignatureMethod': 'HMAC-SHA1',
- 'SignatureNonce': str(uuid.uuid1()),
- 'SignatureVersion': '1.0',
- 'Timestamp': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
- 'Version': '2019-02-28'}
+ parameters = {
+ "AccessKeyId": access_key_id,
+ "Action": "CreateToken",
+ "Format": "JSON",
+ "RegionId": "cn-shanghai",
+ "SignatureMethod": "HMAC-SHA1",
+ "SignatureNonce": str(uuid.uuid1()),
+ "SignatureVersion": "1.0",
+ "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "Version": "2019-02-28",
+ }
# 构造规范化的请求字符串
query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string)
# 构造待签名字符串
- string_to_sign = 'GET' + '&' + AccessToken._encode_text('/') + '&' + AccessToken._encode_text(query_string)
+ string_to_sign = (
+ "GET"
+ + "&"
+ + AccessToken._encode_text("/")
+ + "&"
+ + AccessToken._encode_text(query_string)
+ )
# print('待签名的字符串: %s' % string_to_sign)
# 计算签名
- secreted_string = hmac.new(bytes(access_key_secret + '&', encoding='utf-8'),
- bytes(string_to_sign, encoding='utf-8'),
- hashlib.sha1).digest()
+ secreted_string = hmac.new(
+ bytes(access_key_secret + "&", encoding="utf-8"),
+ bytes(string_to_sign, encoding="utf-8"),
+ hashlib.sha1,
+ ).digest()
signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature)
# 进行URL编码
signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature)
# 调用服务
- full_url = 'http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s' % (signature, query_string)
+ full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
+ signature,
+ query_string,
+ )
# print('url: %s' % full_url)
# 提交HTTP GET请求
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
- key = 'Token'
+ key = "Token"
if key in root_obj:
- token = root_obj[key]['Id']
- expire_time = root_obj[key]['ExpireTime']
+ token = root_obj[key]["Id"]
+ expire_time = root_obj[key]["ExpireTime"]
return token, expire_time
# print(response.text)
return None, None
@@ -70,26 +82,36 @@ class AccessToken:
class TTSProvider(TTSProviderBase):
-
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
-
+
# 新增空值判断逻辑
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.format = config.get("format", "wav")
- self.sample_rate = config.get("sample_rate", 16000)
- self.voice = config.get("voice", "xiaoyun")
- self.volume = config.get("volume", 50)
- self.speech_rate = config.get("speech_rate", 0)
- self.pitch_rate = config.get("pitch_rate", 0)
+ self.audio_file_type = config.get("format", "wav")
+ sample_rate = config.get("sample_rate", "16000")
+ self.sample_rate = int(sample_rate) if sample_rate else 16000
+
+ if config.get("private_voice"):
+ self.voice = config.get("private_voice")
+ else:
+ self.voice = config.get("voice", "xiaoyun")
+
+ volume = config.get("volume", "50")
+ self.volume = int(volume) if volume else 50
+
+ speech_rate = config.get("speech_rate", "0")
+ self.speech_rate = int(speech_rate) if speech_rate else 0
+
+ pitch_rate = config.get("pitch_rate", "0")
+ self.pitch_rate = int(pitch_rate) if pitch_rate else 0
+
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
self.api_url = f"https://{self.host}/stream/v1/tts"
- self.header = {
- "Content-Type": "application/json"
- }
+ self.header = {"Content-Type": "application/json"}
if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token
@@ -99,35 +121,30 @@ class TTSProvider(TTSProviderBase):
self.token = config.get("token")
self.expire_time = None
-
def _refresh_token(self):
"""刷新Token并记录过期时间"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
- self.access_key_id,
- self.access_key_secret
+ self.access_key_id, self.access_key_secret
)
if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间")
try:
- #统一转换为字符串处理
+ # 统一转换为字符串处理
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
expire_time = datetime.fromtimestamp(int(expire_str))
else:
- expire_time = datetime.strptime(
- expire_str,
- "%Y-%m-%dT%H:%M:%SZ"
- )
+ expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e
-
+
else:
self.expire_time = None
-
+
if not self.token:
raise ValueError("无法获取有效的访问Token")
@@ -142,8 +159,6 @@ class TTSProvider(TTSProviderBase):
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒")
return time.time() > self.expire_time
- def generate_filename(self, extension=".wav"):
- return os.path.join(self.output_file, f"tts-{__name__}{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
async def text_to_speak(self, text, output_file):
if self._is_token_expired():
@@ -158,21 +173,30 @@ class TTSProvider(TTSProviderBase):
"voice": self.voice,
"volume": self.volume,
"speech_rate": self.speech_rate,
- "pitch_rate": self.pitch_rate
+ "pitch_rate": self.pitch_rate,
}
# print(self.api_url, json.dumps(request_json, ensure_ascii=False))
try:
- resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
+ resp = requests.post(
+ self.api_url, json.dumps(request_json), headers=self.header
+ )
if resp.status_code == 401: # Token过期特殊处理
self._refresh_token()
- resp = requests.post(self.api_url, json.dumps(request_json), headers=self.header)
+ resp = requests.post(
+ self.api_url, json.dumps(request_json), headers=self.header
+ )
# 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
- if resp.headers['Content-Type'].startswith('audio/'):
- with open(output_file, 'wb') as f:
- f.write(resp.content)
- return output_file
+ if resp.headers["Content-Type"].startswith("audio/"):
+ if output_file:
+ with open(output_file, "wb") as f:
+ f.write(resp.content)
+ return output_file
+ else:
+ return resp.content
else:
- raise Exception(f"{__name__} status_code: {resp.status_code} response: {resp.content}")
+ raise Exception(
+ f"{__name__} status_code: {resp.status_code} response: {resp.content}"
+ )
except Exception as e:
raise Exception(f"{__name__} error: {e}")
diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py
index f2632c02a..1a9d069c2 100644
--- a/main/xiaozhi-server/core/providers/tts/base.py
+++ b/main/xiaozhi-server/core/providers/tts/base.py
@@ -1,9 +1,27 @@
-import asyncio
-from config.logger import setup_logging
import os
+import re
+import queue
+import uuid
+import asyncio
+import threading
+from core.utils import p3
+from datetime import datetime
+from core.utils import textUtils
from abc import ABC, abstractmethod
+from config.logger import setup_logging
+from core.utils.util import audio_to_data, audio_bytes_to_data
from core.utils.tts import MarkdownCleaner
-from core.utils.util import audio_to_data
+from core.utils.output_counter import add_device_output
+from core.handle.reportHandle import enqueue_tts_report
+from core.handle.sendAudioHandle import sendAudioMessage
+from core.providers.tts.dto.dto import (
+ TTSMessageDTO,
+ SentenceType,
+ ContentType,
+ InterfaceType,
+)
+
+import traceback
TAG = __name__
logger = setup_logging()
@@ -11,43 +29,112 @@ logger = setup_logging()
class TTSProviderBase(ABC):
def __init__(self, config, delete_audio_file):
+ self.interface_type = InterfaceType.NON_STREAM
+ self.conn = None
+ self.tts_timeout = 10
self.delete_audio_file = delete_audio_file
- self.output_file = config.get("output_dir")
+ self.audio_file_type = "wav"
+ self.output_file = config.get("output_dir", "tmp/")
+ self.tts_text_queue = queue.Queue()
+ self.tts_audio_queue = queue.Queue()
+ self.tts_audio_first_sentence = True
+ self.before_stop_play_files = []
- @abstractmethod
- def generate_filename(self):
- pass
+ self.tts_text_buff = []
+ self.punctuations = (
+ "。",
+ ".",
+ "?",
+ "?",
+ "!",
+ "!",
+ ";",
+ ";",
+ ":",
+ )
+ self.first_sentence_punctuations = (
+ ",",
+ "~",
+ "~",
+ "、",
+ ",",
+ "。",
+ ".",
+ "?",
+ "?",
+ "!",
+ "!",
+ ";",
+ ";",
+ ":",
+ )
+ self.tts_stop_request = False
+ self.processed_chars = 0
+ self.is_first_sentence = True
+
+ def generate_filename(self, extension=".wav"):
+ return os.path.join(
+ self.output_file,
+ f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
+ )
def to_tts(self, text):
- tmp_file = self.generate_filename()
- try:
- max_repeat_time = 5
- text = MarkdownCleaner.clean_markdown(text)
- while not os.path.exists(tmp_file) and max_repeat_time > 0:
+ text = MarkdownCleaner.clean_markdown(text)
+ max_repeat_time = 5
+ if self.delete_audio_file:
+ # 需要删除文件的直接转为音频数据
+ while max_repeat_time > 0:
try:
- asyncio.run(self.text_to_speak(text, tmp_file))
+ audio_bytes = asyncio.run(self.text_to_speak(text, None))
+ if audio_bytes:
+ audio_datas, _ = audio_bytes_to_data(
+ audio_bytes, file_type=self.audio_file_type, is_opus=True
+ )
+ return audio_datas
+ else:
+ max_repeat_time -= 1
except Exception as e:
logger.bind(tag=TAG).warning(
f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
)
- # 未执行成功,删除文件
- if os.path.exists(tmp_file):
- os.remove(tmp_file)
max_repeat_time -= 1
-
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
- f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
+ f"语音生成成功: {text},重试{5 - max_repeat_time}次"
)
else:
logger.bind(tag=TAG).error(
f"语音生成失败: {text},请检查网络或服务是否正常"
)
-
- return tmp_file
- except Exception as e:
- logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
return None
+ else:
+ tmp_file = self.generate_filename()
+ try:
+ while not os.path.exists(tmp_file) and max_repeat_time > 0:
+ try:
+ asyncio.run(self.text_to_speak(text, tmp_file))
+ except Exception as e:
+ logger.bind(tag=TAG).warning(
+ f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
+ )
+ # 未执行成功,删除文件
+ if os.path.exists(tmp_file):
+ os.remove(tmp_file)
+ max_repeat_time -= 1
+
+ if max_repeat_time > 0:
+ logger.bind(tag=TAG).info(
+ f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
+ )
+ else:
+ logger.bind(tag=TAG).error(
+ f"语音生成失败: {text},请检查网络或服务是否正常"
+ )
+
+ return tmp_file
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
+ return None
@abstractmethod
async def text_to_speak(self, text, output_file):
@@ -60,3 +147,253 @@ class TTSProviderBase(ABC):
def audio_to_opus_data(self, audio_file_path):
"""音频文件转换为Opus编码"""
return audio_to_data(audio_file_path, is_opus=True)
+
+ def tts_one_sentence(
+ self,
+ conn,
+ content_type,
+ content_detail=None,
+ content_file=None,
+ sentence_id=None,
+ ):
+ """发送一句话"""
+ if not sentence_id:
+ if conn.sentence_id:
+ sentence_id = conn.sentence_id
+ else:
+ sentence_id = str(uuid.uuid4()).replace("-", "")
+ conn.sentence_id = sentence_id
+ self.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=sentence_id,
+ sentence_type=SentenceType.FIRST,
+ content_type=ContentType.ACTION,
+ )
+ )
+ # 对于单句的文本,进行分段处理
+ segments = re.split(r'([。!?!?;;\n])', content_detail)
+ for seg in segments:
+ self.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=sentence_id,
+ sentence_type=SentenceType.MIDDLE,
+ content_type=content_type,
+ content_detail=seg,
+ content_file=content_file,
+ )
+ )
+ self.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.ACTION,
+ )
+ )
+
+ async def open_audio_channels(self, conn):
+ self.conn = conn
+ self.tts_timeout = conn.config.get("tts_timeout", 10)
+ # tts 消化线程
+ self.tts_priority_thread = threading.Thread(
+ target=self.tts_text_priority_thread, daemon=True
+ )
+ self.tts_priority_thread.start()
+
+ # 音频播放 消化线程
+ self.audio_play_priority_thread = threading.Thread(
+ target=self._audio_play_priority_thread, daemon=True
+ )
+ self.audio_play_priority_thread.start()
+
+ # 这里默认是非流式的处理方式
+ # 流式处理方式请在子类中重写
+ def tts_text_priority_thread(self):
+ while not self.conn.stop_event.is_set():
+ try:
+ message = self.tts_text_queue.get(timeout=1)
+ if self.conn.client_abort:
+ logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
+ continue
+ if message.sentence_type == SentenceType.FIRST:
+ # 初始化参数
+ self.tts_stop_request = False
+ self.processed_chars = 0
+ self.tts_text_buff = []
+ self.is_first_sentence = True
+ self.tts_audio_first_sentence = True
+ elif ContentType.TEXT == message.content_type:
+ self.tts_text_buff.append(message.content_detail)
+ segment_text = self._get_segment_text()
+ if segment_text:
+ if self.delete_audio_file:
+ audio_datas = self.to_tts(segment_text)
+ if audio_datas:
+ self.tts_audio_queue.put(
+ (message.sentence_type, audio_datas, segment_text)
+ )
+ else:
+ tts_file = self.to_tts(segment_text)
+ if tts_file:
+ audio_datas = self._process_audio_file(tts_file)
+ self.tts_audio_queue.put(
+ (message.sentence_type, audio_datas, segment_text)
+ )
+ elif ContentType.FILE == message.content_type:
+ self._process_remaining_text()
+ tts_file = message.content_file
+ if tts_file and os.path.exists(tts_file):
+ audio_datas = self._process_audio_file(tts_file)
+ self.tts_audio_queue.put(
+ (message.sentence_type, audio_datas, message.content_detail)
+ )
+
+ if message.sentence_type == SentenceType.LAST:
+ self._process_remaining_text()
+ self.tts_audio_queue.put(
+ (message.sentence_type, [], message.content_detail)
+ )
+
+ except queue.Empty:
+ continue
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ )
+ continue
+
+ def _audio_play_priority_thread(self):
+ while not self.conn.stop_event.is_set():
+ text = None
+ try:
+ try:
+ sentence_type, audio_datas, text = self.tts_audio_queue.get(
+ timeout=1
+ )
+ except queue.Empty:
+ if self.conn.stop_event.is_set():
+ break
+ continue
+ future = asyncio.run_coroutine_threadsafe(
+ sendAudioMessage(self.conn, sentence_type, audio_datas, text),
+ self.conn.loop,
+ )
+ future.result()
+ if self.conn.max_output_size > 0 and text:
+ add_device_output(self.conn.headers.get("device-id"), len(text))
+ enqueue_tts_report(self.conn, text, audio_datas)
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"audio_play_priority priority_thread: {text} {e}"
+ )
+
+ async def start_session(self, session_id):
+ pass
+
+ async def finish_session(self, session_id):
+ pass
+
+ async def close(self):
+ """资源清理方法"""
+ if hasattr(self, "ws") and self.ws:
+ await self.ws.close()
+
+ def _get_segment_text(self):
+ # 合并当前全部文本并处理未分割部分
+ full_text = "".join(self.tts_text_buff)
+ current_text = full_text[self.processed_chars :] # 从未处理的位置开始
+ last_punct_pos = -1
+
+ # 根据是否是第一句话选择不同的标点符号集合
+ punctuations_to_use = (
+ self.first_sentence_punctuations
+ if self.is_first_sentence
+ else self.punctuations
+ )
+
+ for punct in punctuations_to_use:
+ pos = current_text.rfind(punct)
+ if (pos != -1 and last_punct_pos == -1) or (
+ pos != -1 and pos < last_punct_pos
+ ):
+ last_punct_pos = pos
+
+ if last_punct_pos != -1:
+ segment_text_raw = current_text[: last_punct_pos + 1]
+ segment_text = textUtils.get_string_no_punctuation_or_emoji(
+ segment_text_raw
+ )
+ self.processed_chars += len(segment_text_raw) # 更新已处理字符位置
+
+ # 如果是第一句话,在找到第一个逗号后,将标志设置为False
+ if self.is_first_sentence:
+ self.is_first_sentence = False
+
+ return segment_text
+ elif self.tts_stop_request and current_text:
+ segment_text = current_text
+ self.is_first_sentence = True # 重置标志
+ return segment_text
+ else:
+ return None
+
+ def _process_audio_file(self, tts_file):
+ """处理音频文件并转换为指定格式
+
+ Args:
+ tts_file: 音频文件路径
+ content_detail: 内容详情
+
+ Returns:
+ tuple: (sentence_type, audio_datas, content_detail)
+ """
+ audio_datas = []
+ if tts_file.endswith(".p3"):
+ audio_datas, _ = p3.decode_opus_from_file(tts_file)
+ elif self.conn.audio_format == "pcm":
+ audio_datas, _ = self.audio_to_pcm_data(tts_file)
+ else:
+ audio_datas, _ = self.audio_to_opus_data(tts_file)
+
+ if (
+ self.delete_audio_file
+ and tts_file is not None
+ and os.path.exists(tts_file)
+ and tts_file.startswith(self.output_file)
+ ):
+ os.remove(tts_file)
+ return audio_datas
+
+ def _process_before_stop_play_files(self):
+ for tts_file, text in self.before_stop_play_files:
+ if tts_file and os.path.exists(tts_file):
+ audio_datas = self._process_audio_file(tts_file)
+ self.tts_audio_queue.put((SentenceType.MIDDLE, audio_datas, text))
+ self.before_stop_play_files.clear()
+ self.tts_audio_queue.put((SentenceType.LAST, [], None))
+
+ def _process_remaining_text(self):
+ """处理剩余的文本并生成语音
+
+ Returns:
+ bool: 是否成功处理了文本
+ """
+ full_text = "".join(self.tts_text_buff)
+ remaining_text = full_text[self.processed_chars :]
+ if remaining_text:
+ segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
+ if segment_text:
+ if self.delete_audio_file:
+ audio_datas = self.to_tts(segment_text)
+ if audio_datas:
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, audio_datas, segment_text)
+ )
+ else:
+ tts_file = self.to_tts(segment_text)
+ audio_datas = self._process_audio_file(tts_file)
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, audio_datas, segment_text)
+ )
+ self.processed_chars += len(full_text)
+ return True
+ return False
diff --git a/main/xiaozhi-server/core/providers/tts/cozecn.py b/main/xiaozhi-server/core/providers/tts/cozecn.py
index 56314f4fc..6c5d05472 100644
--- a/main/xiaozhi-server/core/providers/tts/cozecn.py
+++ b/main/xiaozhi-server/core/providers/tts/cozecn.py
@@ -1,9 +1,4 @@
-import os
-import uuid
-import json
-import base64
import requests
-from datetime import datetime
from core.providers.tts.base import TTSProviderBase
@@ -16,17 +11,11 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice")
- self.response_format = config.get("response_format")
-
+ self.response_format = config.get("response_format", "wav")
+ self.audio_file_type = config.get("response_format", "wav")
self.host = "api.coze.cn"
self.api_url = f"https://{self.host}/v1/audio/speech"
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
-
async def text_to_speak(self, text, output_file):
request_json = {
"model": self.model,
@@ -44,7 +33,10 @@ class TTSProvider(TTSProviderBase):
"POST", self.api_url, json=request_json, headers=headers
)
data = response.content
- file_to_save = open(output_file, "wb")
- file_to_save.write(data)
+ if output_file:
+ with open(output_file, "wb") as file_to_save:
+ file_to_save.write(data)
+ else:
+ return data
except Exception as e:
- raise Exception(f"{__name__} error: {e}")
\ No newline at end of file
+ raise Exception(f"{__name__} error: {e}")
diff --git a/main/xiaozhi-server/core/providers/tts/custom.py b/main/xiaozhi-server/core/providers/tts/custom.py
index 5b8669dab..b417825e8 100644
--- a/main/xiaozhi-server/core/providers/tts/custom.py
+++ b/main/xiaozhi-server/core/providers/tts/custom.py
@@ -1,4 +1,5 @@
import os
+import json
import uuid
import requests
from config.logger import setup_logging
@@ -12,10 +13,20 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
+ self.method = config.get("method", "GET")
self.headers = config.get("headers", {})
- self.params = config.get("params")
self.format = config.get("format", "wav")
+ self.audio_file_type = config.get("format", "wav")
self.output_file = config.get("output_dir", "tmp/")
+ self.params = config.get("params")
+
+ if isinstance(self.params, str):
+ try:
+ self.params = json.loads(self.params)
+ except json.JSONDecodeError:
+ raise ValueError("Custom TTS配置参数出错,无法将字符串解析为对象")
+ elif not isinstance(self.params, dict):
+ raise TypeError("Custom TTS配置参数出错, 请参考配置说明")
def generate_filename(self):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}")
@@ -27,10 +38,16 @@ class TTSProvider(TTSProviderBase):
v = v.replace("{prompt_text}", text)
request_params[k] = v
- resp = requests.get(self.url, params=request_params, headers=self.headers)
+ if self.method.upper() == "POST":
+ resp = requests.post(self.url, json=request_params, headers=self.headers)
+ else:
+ resp = requests.get(self.url, params=request_params, headers=self.headers)
if resp.status_code == 200:
- with open(output_file, "wb") as file:
- file.write(resp.content)
+ if output_file:
+ with open(output_file, "wb") as file:
+ file.write(resp.content)
+ else:
+ return resp.content
else:
error_msg = f"Custom TTS请求失败: {resp.status_code} - {resp.text}"
logger.bind(tag=TAG).error(error_msg)
diff --git a/main/xiaozhi-server/core/providers/tts/default.py b/main/xiaozhi-server/core/providers/tts/default.py
new file mode 100644
index 000000000..7818d288b
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/default.py
@@ -0,0 +1,23 @@
+import os
+from config.logger import setup_logging
+from core.providers.tts.base import TTSProviderBase
+
+TAG = __name__
+logger = setup_logging()
+
+
+class DefaultTTS(TTSProviderBase):
+ def __init__(self, config, delete_audio_file=True):
+ super().__init__(config, delete_audio_file)
+ self.output_dir = config.get("output_dir", "output")
+ if not os.path.exists(self.output_dir):
+ os.makedirs(self.output_dir)
+
+ def generate_filename(self):
+ """生成唯一的音频文件名"""
+ import uuid
+
+ return os.path.join(self.output_dir, f"{uuid.uuid4()}.wav")
+
+ async def text_to_speak(self, text, output_file):
+ logger.bind(tag=TAG).error(f"无法实例化 TTS 服务,请检查配置")
diff --git a/main/xiaozhi-server/core/providers/tts/doubao.py b/main/xiaozhi-server/core/providers/tts/doubao.py
index 3a0fdde3a..2eed9bcfc 100644
--- a/main/xiaozhi-server/core/providers/tts/doubao.py
+++ b/main/xiaozhi-server/core/providers/tts/doubao.py
@@ -1,9 +1,7 @@
-import os
import uuid
import json
import base64
import requests
-from datetime import datetime
from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
@@ -31,7 +29,7 @@ class TTSProvider(TTSProviderBase):
speed_ratio = config.get("speed_ratio", "1.0")
volume_ratio = config.get("volume_ratio", "1.0")
pitch_ratio = config.get("pitch_ratio", "1.0")
-
+ self.audio_file_type = config.get("format", "wav")
self.speed_ratio = float(speed_ratio) if speed_ratio else 1.0
self.volume_ratio = float(volume_ratio) if volume_ratio else 1.0
self.pitch_ratio = float(pitch_ratio) if pitch_ratio else 1.0
@@ -39,13 +37,9 @@ class TTSProvider(TTSProviderBase):
self.api_url = config.get("api_url")
self.authorization = config.get("authorization")
self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
- check_model_key("TTS", self.access_token)
-
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
+ model_key_msg = check_model_key("TTS", self.access_token)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
async def text_to_speak(self, text, output_file):
request_json = {
@@ -57,7 +51,7 @@ class TTSProvider(TTSProviderBase):
"user": {"uid": "1"},
"audio": {
"voice_type": self.voice,
- "encoding": "wav",
+ "encoding": self.audio_file_type,
"speed_ratio": self.speed_ratio,
"volume_ratio": self.volume_ratio,
"pitch_ratio": self.pitch_ratio,
@@ -78,8 +72,12 @@ class TTSProvider(TTSProviderBase):
)
if "data" in resp.json():
data = resp.json()["data"]
- file_to_save = open(output_file, "wb")
- file_to_save.write(base64.b64decode(data))
+ audio_bytes = base64.b64decode(data)
+ if output_file:
+ with open(output_file, "wb") as file_to_save:
+ file_to_save.write(audio_bytes)
+ else:
+ return audio_bytes
else:
raise Exception(
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
diff --git a/main/xiaozhi-server/core/providers/tts/dto/dto.py b/main/xiaozhi-server/core/providers/tts/dto/dto.py
new file mode 100644
index 000000000..b23173409
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/dto/dto.py
@@ -0,0 +1,43 @@
+from enum import Enum
+from typing import Union, Optional
+
+
+class SentenceType(Enum):
+ # 说话阶段
+ FIRST = "FIRST" # 首句话
+ MIDDLE = "MIDDLE" # 说话中
+ LAST = "LAST" # 最后一句
+
+
+class ContentType(Enum):
+ # 内容类型
+ TEXT = "TEXT" # 文本内容
+ FILE = "FILE" # 文件内容
+ ACTION = "ACTION" # 动作内容
+
+
+class InterfaceType(Enum):
+ # 接口类型
+ DUAL_STREAM = "DUAL_STREAM" # 双流式
+ SINGLE_STREAM = "SINGLE_STREAM" # 单流式
+ NON_STREAM = "NON_STREAM" # 非流式
+
+
+class TTSMessageDTO:
+ def __init__(
+ self,
+ sentence_id: str,
+ # 说话阶段
+ sentence_type: SentenceType,
+ # 内容类型
+ content_type: ContentType,
+ # 内容详情,一般是需要转换的文本或者音频的歌词
+ content_detail: Optional[str] = None,
+ # 如果内容类型为文件,则需要传入文件路径
+ content_file: Optional[str] = None,
+ ):
+ self.sentence_id = sentence_id
+ self.sentence_type = sentence_type
+ self.content_type = content_type
+ self.content_detail = content_detail
+ self.content_file = content_file
diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py
index 3d9b2547a..ffa1c3aa7 100644
--- a/main/xiaozhi-server/core/providers/tts/edge.py
+++ b/main/xiaozhi-server/core/providers/tts/edge.py
@@ -12,6 +12,7 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice")
+ self.audio_file_type = config.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
return os.path.join(
@@ -22,16 +23,24 @@ class TTSProvider(TTSProviderBase):
async def text_to_speak(self, text, output_file):
try:
communicate = edge_tts.Communicate(text, voice=self.voice)
- # 确保目录存在并创建空文件
- os.makedirs(os.path.dirname(output_file), exist_ok=True)
- with open(output_file, "wb") as f:
- pass
+ if output_file:
+ # 确保目录存在并创建空文件
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
+ with open(output_file, "wb") as f:
+ pass
- # 流式写入音频数据
- with open(output_file, "ab") as f: # 改为追加模式避免覆盖
+ # 流式写入音频数据
+ with open(output_file, "ab") as f: # 改为追加模式避免覆盖
+ async for chunk in communicate.stream():
+ if chunk["type"] == "audio": # 只处理音频数据块
+ f.write(chunk["data"])
+ else:
+ # 返回音频二进制数据
+ audio_bytes = b""
async for chunk in communicate.stream():
- if chunk["type"] == "audio": # 只处理音频数据块
- f.write(chunk["data"])
+ if chunk["type"] == "audio":
+ audio_bytes += chunk["data"]
+ return audio_bytes
except Exception as e:
error_msg = f"Edge TTS请求失败: {e}"
raise Exception(error_msg) # 抛出异常,让调用方捕获
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py
index 71f1ac889..e192ff256 100644
--- a/main/xiaozhi-server/core/providers/tts/fishspeech.py
+++ b/main/xiaozhi-server/core/providers/tts/fishspeech.py
@@ -1,12 +1,9 @@
import base64
-import os
-import uuid
import requests
import ormsgpack
from pathlib import Path
from pydantic import BaseModel, Field, conint, model_validator
from typing_extensions import Annotated
-from datetime import datetime
from typing import Literal
from core.utils.util import check_model_key, parse_string_to_list
from core.providers.tts.base import TTSProviderBase
@@ -91,10 +88,11 @@ class TTSProvider(TTSProviderBase):
self.reference_audio = parse_string_to_list(config.get("reference_audio"))
self.reference_text = parse_string_to_list(config.get("reference_text"))
self.format = config.get("response_format", "wav")
-
+ self.audio_file_type = config.get("response_format", "wav")
self.api_key = config.get("api_key", "YOUR_API_KEY")
- have_key = check_model_key("FishSpeech TTS", self.api_key)
- if not have_key:
+ model_key_msg = check_model_key("FishSpeech TTS", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
return
self.normalize = str(config.get("normalize", True)).lower() in (
"true",
@@ -133,12 +131,6 @@ class TTSProvider(TTSProviderBase):
self.seed = int(config.get("seed")) if config.get("seed") else None
self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
-
async def text_to_speak(self, text, output_file):
# Prepare reference data
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in self.reference_audio]
@@ -179,8 +171,11 @@ class TTSProvider(TTSProviderBase):
if response.status_code == 200:
audio_content = response.content
- with open(output_file, "wb") as audio_file:
- audio_file.write(audio_content)
+ if output_file:
+ with open(output_file, "wb") as audio_file:
+ audio_file.write(audio_content)
+ else:
+ return audio_content
else:
error_msg = f"Request failed with status code {response.status_code}"
diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py
index 2d58679db..7f43ad7da 100644
--- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py
+++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py
@@ -1,10 +1,5 @@
-import os
-import uuid
-import json
-import base64
import requests
from config.logger import setup_logging
-from datetime import datetime
from core.providers.tts.base import TTSProviderBase
from core.utils.util import parse_string_to_list
@@ -70,12 +65,7 @@ class TTSProvider(TTSProviderBase):
self.aux_ref_audio_paths = parse_string_to_list(
config.get("aux_ref_audio_paths")
)
-
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
+ self.audio_file_type = config.get("format", "wav")
async def text_to_speak(self, text, output_file):
request_json = {
@@ -102,8 +92,11 @@ class TTSProvider(TTSProviderBase):
resp = requests.post(self.url, json=request_json)
if resp.status_code == 200:
- with open(output_file, "wb") as file:
- file.write(resp.content)
+ if output_file:
+ with open(output_file, "wb") as file:
+ file.write(resp.content)
+ else:
+ return resp.content
else:
error_msg = f"GPT_SoVITS_V2 TTS请求失败: {resp.status_code} - {resp.text}"
logger.bind(tag=TAG).error(error_msg)
diff --git a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py
index d4da23ed4..ae41fc4eb 100644
--- a/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py
+++ b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v3.py
@@ -1,8 +1,5 @@
-import os
-import uuid
import requests
from config.logger import setup_logging
-from datetime import datetime
from core.providers.tts.base import TTSProviderBase
from core.utils.util import parse_string_to_list
@@ -35,12 +32,7 @@ class TTSProvider(TTSProviderBase):
self.cut_punc = config.get("cut_punc", "")
self.inp_refs = parse_string_to_list(config.get("inp_refs"))
self.if_sr = str(config.get("if_sr", False)).lower() in ("true", "1", "yes")
-
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
+ self.audio_file_type = config.get("format", "wav")
async def text_to_speak(self, text, output_file):
request_params = {
@@ -61,10 +53,12 @@ class TTSProvider(TTSProviderBase):
resp = requests.get(self.url, params=request_params)
if resp.status_code == 200:
- with open(output_file, "wb") as file:
- file.write(resp.content)
+ if output_file:
+ with open(output_file, "wb") as file:
+ file.write(resp.content)
+ else:
+ return resp.content
else:
error_msg = f"GPT_SoVITS_V3 TTS请求失败: {resp.status_code} - {resp.text}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg)
-
diff --git a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py
new file mode 100644
index 000000000..1ebaf15a0
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py
@@ -0,0 +1,737 @@
+import os
+import uuid
+import json
+import queue
+import asyncio
+import traceback
+import websockets
+from core.utils.tts import MarkdownCleaner
+from config.logger import setup_logging
+from core.utils import opus_encoder_utils
+from core.utils.util import check_model_key
+from core.providers.tts.base import TTSProviderBase
+from core.handle.abortHandle import handleAbortMessage
+from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
+from asyncio import Task
+
+
+TAG = __name__
+logger = setup_logging()
+
+PROTOCOL_VERSION = 0b0001
+DEFAULT_HEADER_SIZE = 0b0001
+
+# Message Type:
+FULL_CLIENT_REQUEST = 0b0001
+AUDIO_ONLY_RESPONSE = 0b1011
+FULL_SERVER_RESPONSE = 0b1001
+ERROR_INFORMATION = 0b1111
+
+# Message Type Specific Flags
+MsgTypeFlagNoSeq = 0b0000 # Non-terminal packet with no sequence
+MsgTypeFlagPositiveSeq = 0b1 # Non-terminal packet with sequence > 0
+MsgTypeFlagLastNoSeq = 0b10 # last packet with no sequence
+MsgTypeFlagNegativeSeq = 0b11 # Payload contains event number (int32)
+MsgTypeFlagWithEvent = 0b100
+# Message Serialization
+NO_SERIALIZATION = 0b0000
+JSON = 0b0001
+# Message Compression
+COMPRESSION_NO = 0b0000
+COMPRESSION_GZIP = 0b0001
+
+EVENT_NONE = 0
+EVENT_Start_Connection = 1
+
+EVENT_FinishConnection = 2
+
+EVENT_ConnectionStarted = 50 # 成功建连
+
+EVENT_ConnectionFailed = 51 # 建连失败(可能是无法通过权限认证)
+
+EVENT_ConnectionFinished = 52 # 连接结束
+
+# 上行Session事件
+EVENT_StartSession = 100
+
+EVENT_FinishSession = 102
+# 下行Session事件
+EVENT_SessionStarted = 150
+EVENT_SessionFinished = 152
+
+EVENT_SessionFailed = 153
+
+# 上行通用事件
+EVENT_TaskRequest = 200
+
+# 下行TTS事件
+EVENT_TTSSentenceStart = 350
+
+EVENT_TTSSentenceEnd = 351
+
+EVENT_TTSResponse = 352
+
+
+class Header:
+ def __init__(
+ self,
+ protocol_version=PROTOCOL_VERSION,
+ header_size=DEFAULT_HEADER_SIZE,
+ message_type: int = 0,
+ message_type_specific_flags: int = 0,
+ serial_method: int = NO_SERIALIZATION,
+ compression_type: int = COMPRESSION_NO,
+ reserved_data=0,
+ ):
+ self.header_size = header_size
+ self.protocol_version = protocol_version
+ self.message_type = message_type
+ self.message_type_specific_flags = message_type_specific_flags
+ self.serial_method = serial_method
+ self.compression_type = compression_type
+ self.reserved_data = reserved_data
+
+ def as_bytes(self) -> bytes:
+ return bytes(
+ [
+ (self.protocol_version << 4) | self.header_size,
+ (self.message_type << 4) | self.message_type_specific_flags,
+ (self.serial_method << 4) | self.compression_type,
+ self.reserved_data,
+ ]
+ )
+
+
+class Optional:
+ def __init__(
+ self, event: int = EVENT_NONE, sessionId: str = None, sequence: int = None
+ ):
+ self.event = event
+ self.sessionId = sessionId
+ self.errorCode: int = 0
+ self.connectionId: str | None = None
+ self.response_meta_json: str | None = None
+ self.sequence = sequence
+
+ # 转成 byte 序列
+ def as_bytes(self) -> bytes:
+ option_bytes = bytearray()
+ if self.event != EVENT_NONE:
+ option_bytes.extend(self.event.to_bytes(4, "big", signed=True))
+ if self.sessionId is not None:
+ session_id_bytes = str.encode(self.sessionId)
+ size = len(session_id_bytes).to_bytes(4, "big", signed=True)
+ option_bytes.extend(size)
+ option_bytes.extend(session_id_bytes)
+ if self.sequence is not None:
+ option_bytes.extend(self.sequence.to_bytes(4, "big", signed=True))
+ return option_bytes
+
+
+class Response:
+ def __init__(self, header: Header, optional: Optional):
+ self.optional = optional
+ self.header = header
+ self.payload: bytes | None = None
+
+ def __str__(self):
+ return super().__str__()
+
+
+class TTSProvider(TTSProviderBase):
+ def __init__(self, config, delete_audio_file):
+ super().__init__(config, delete_audio_file)
+ self.ws = None
+ self.interface_type = InterfaceType.DUAL_STREAM
+ self._monitor_task = None # 监听任务引用
+ self.appId = config.get("appid")
+ self.access_token = config.get("access_token")
+ self.cluster = config.get("cluster")
+ self.resource_id = config.get("resource_id")
+ if config.get("private_voice"):
+ self.voice = config.get("private_voice")
+ else:
+ self.voice = config.get("speaker")
+ self.ws_url = config.get("ws_url")
+ self.authorization = config.get("authorization")
+ self.header = {"Authorization": f"{self.authorization}{self.access_token}"}
+ self.enable_two_way = True
+ self.tts_text = ""
+ self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
+ sample_rate=16000, channels=1, frame_size_ms=60
+ )
+ model_key_msg = check_model_key("TTS", self.access_token)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
+
+ async def open_audio_channels(self, conn):
+ try:
+ await super().open_audio_channels(conn)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to open audio channels: {str(e)}")
+ self.ws = None
+ raise
+
+ async def _ensure_connection(self):
+ """建立新的WebSocket连接"""
+ try:
+ logger.bind(tag=TAG).info("开始建立新连接...")
+ ws_header = {
+ "X-Api-App-Key": self.appId,
+ "X-Api-Access-Key": self.access_token,
+ "X-Api-Resource-Id": self.resource_id,
+ "X-Api-Connect-Id": uuid.uuid4(),
+ }
+ self.ws = await websockets.connect(
+ self.ws_url, additional_headers=ws_header, max_size=1000000000
+ )
+ logger.bind(tag=TAG).info("WebSocket连接建立成功")
+ return self.ws
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
+ self.ws = None
+ raise
+
+ def tts_text_priority_thread(self):
+ """火山引擎双流式TTS的文本处理线程"""
+ while not self.conn.stop_event.is_set():
+ try:
+ message = self.tts_text_queue.get(timeout=1)
+ logger.bind(tag=TAG).debug(
+ f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
+ )
+ if self.conn.client_abort:
+ logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
+ continue
+
+ 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).info(f"自动生成新的 会话ID: {self.conn.sentence_id}")
+
+ logger.bind(tag=TAG).info("开始启动TTS会话...")
+ future = asyncio.run_coroutine_threadsafe(
+ self.start_session(self.conn.sentence_id),
+ loop=self.conn.loop,
+ )
+ future.result()
+ self.tts_audio_first_sentence = True
+ self.before_stop_play_files.clear()
+ logger.bind(tag=TAG).info("TTS会话启动成功")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
+ continue
+
+ elif ContentType.TEXT == message.content_type:
+ if message.content_detail:
+ try:
+ logger.bind(tag=TAG).debug(
+ f"开始发送TTS文本: {message.content_detail}"
+ )
+ future = asyncio.run_coroutine_threadsafe(
+ self.text_to_speak(message.content_detail, None),
+ loop=self.conn.loop,
+ )
+ future.result()
+ logger.bind(tag=TAG).debug("TTS文本发送成功")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
+ continue
+
+ elif ContentType.FILE == message.content_type:
+ logger.bind(tag=TAG).info(
+ f"添加音频文件到待播放列表: {message.content_file}"
+ )
+ self.before_stop_play_files.append(
+ (message.content_file, message.content_detail)
+ )
+
+ if message.sentence_type == SentenceType.LAST:
+ try:
+ logger.bind(tag=TAG).info("开始结束TTS会话...")
+ future = asyncio.run_coroutine_threadsafe(
+ self.finish_session(self.conn.sentence_id),
+ loop=self.conn.loop,
+ )
+ future.result()
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
+ continue
+
+ except queue.Empty:
+ continue
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ )
+ continue
+
+ 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)
+
+ # 发送文本
+ await self.send_text(self.voice, filtered_text, self.conn.sentence_id)
+ return
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
+ if self.ws:
+ try:
+ await self.ws.close()
+ except:
+ pass
+ self.ws = None
+ raise
+
+ async def start_session(self, session_id):
+ logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
+ try:
+ task = self._monitor_task
+ if (
+ task is not None
+ and isinstance(task, Task)
+ and not task.done()
+ ):
+ logger.bind(tag=TAG).info("等待上一个监听任务结束...")
+ if self.ws is not None:
+ logger.bind(tag=TAG).info("强制关闭上一个WebSocket连接以唤醒监听任务...")
+ try:
+ await self.ws.close()
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"关闭上一个ws异常: {e}")
+ self.ws = None
+ try:
+ await asyncio.wait_for(task, timeout=8)
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"等待监听任务异常: {e}")
+ self._monitor_task = None
+ # 建立新连接
+ await self._ensure_connection()
+
+ # 启动监听任务
+ self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
+
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ serial_method=JSON,
+ ).as_bytes()
+ optional = Optional(
+ event=EVENT_StartSession, sessionId=session_id
+ ).as_bytes()
+ payload = self.get_payload_bytes(
+ event=EVENT_StartSession, speaker=self.voice
+ )
+ await self.send_event(self.ws, header, optional, payload)
+ logger.bind(tag=TAG).info("会话启动请求已发送")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
+ # 确保清理资源
+ if hasattr(self, "_monitor_task"):
+ try:
+ self._monitor_task.cancel()
+ await self._monitor_task
+ except:
+ pass
+ self._monitor_task = None
+ if self.ws:
+ try:
+ await self.ws.close()
+ except:
+ pass
+ self.ws = None
+ raise
+
+ async def finish_session(self, session_id):
+ logger.bind(tag=TAG).info(f"关闭会话~~{session_id}")
+ try:
+ if self.ws:
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ serial_method=JSON,
+ ).as_bytes()
+ optional = Optional(
+ event=EVENT_FinishSession, sessionId=session_id
+ ).as_bytes()
+ payload = str.encode("{}")
+ await self.send_event(self.ws, header, optional, payload)
+ logger.bind(tag=TAG).info("会话结束请求已发送")
+
+ # 等待监听任务完成
+ if hasattr(self, "_monitor_task"):
+ try:
+ await self._monitor_task
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"等待监听任务完成时发生错误: {str(e)}"
+ )
+ finally:
+ self._monitor_task = None
+
+ # 关闭连接
+ await self.close()
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
+ # 确保清理资源
+ if hasattr(self, "_monitor_task"):
+ try:
+ self._monitor_task.cancel()
+ await self._monitor_task
+ except:
+ pass
+ self._monitor_task = None
+ if self.ws:
+ try:
+ await self.ws.close()
+ except:
+ pass
+ self.ws = None
+ raise
+
+ async def close(self):
+ """资源清理方法"""
+ if self.ws:
+ try:
+ await self.ws.close()
+ except:
+ pass
+ self.ws = None
+
+ async def _start_monitor_tts_response(self):
+ """监听TTS响应"""
+ opus_datas_cache = []
+ is_first_sentence = True
+ first_sentence_segment_count = 0 # 添加计数器
+ try:
+ while not self.conn.stop_event.is_set():
+ try:
+ # 确保 `recv()` 运行在同一个 event loop
+ msg = await self.ws.recv()
+ res = self.parser_response(msg)
+ self.print_response(res, "send_text res:")
+
+ # 检查客户端是否中止
+ if self.conn.client_abort:
+ logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
+ break
+
+ if res.optional.event == EVENT_TTSSentenceStart:
+ json_data = json.loads(res.payload.decode("utf-8"))
+ self.tts_text = json_data.get("text", "")
+ logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}")
+ self.tts_audio_queue.put(
+ (SentenceType.FIRST, [], self.tts_text)
+ )
+ opus_datas_cache = []
+ first_sentence_segment_count = 0 # 重置计数器
+ elif (
+ res.optional.event == EVENT_TTSResponse
+ and res.header.message_type == AUDIO_ONLY_RESPONSE
+ ):
+ logger.bind(tag=TAG).debug(f"推送数据到队列里面~~")
+ opus_datas = self.wav_to_opus_data_audio_raw(res.payload)
+ logger.bind(tag=TAG).debug(
+ f"推送数据到队列里面帧数~~{len(opus_datas)}"
+ )
+ if is_first_sentence:
+ first_sentence_segment_count += 1
+ if first_sentence_segment_count <= 6:
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, opus_datas, None)
+ )
+ else:
+ opus_datas_cache = opus_datas_cache + opus_datas
+ else:
+ # 后续句子缓存
+ opus_datas_cache = opus_datas_cache + opus_datas
+ elif res.optional.event == EVENT_TTSSentenceEnd:
+ logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}")
+ if not is_first_sentence or first_sentence_segment_count > 10:
+ # 发送缓存的数据
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, opus_datas_cache, None)
+ )
+ # 第一句话结束后,将标志设置为False
+ is_first_sentence = False
+ elif res.optional.event == EVENT_SessionFinished:
+ logger.bind(tag=TAG).debug(f"会话结束~~")
+ self._process_before_stop_play_files()
+ break
+ except websockets.ConnectionClosed:
+ logger.bind(tag=TAG).warning("WebSocket连接已关闭")
+ break
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"Error in _start_monitor_tts_response: {e}"
+ )
+ traceback.print_exc()
+ break
+ finally:
+ # 确保清理资源
+ if self.ws:
+ try:
+ await self.ws.close()
+ except:
+ pass
+ self.ws = None
+ # 监听任务退出时清理引用
+ self._monitor_task = None
+
+ async def send_event(
+ self,
+ ws: websockets.WebSocketClientProtocol,
+ header: bytes,
+ optional: bytes | None = None,
+ payload: bytes = None,
+ ):
+ try:
+ full_client_request = bytearray(header)
+ if optional is not None:
+ full_client_request.extend(optional)
+ if payload is not None:
+ payload_size = len(payload).to_bytes(4, "big", signed=True)
+ full_client_request.extend(payload_size)
+ full_client_request.extend(payload)
+ await ws.send(full_client_request)
+ except websockets.ConnectionClosed:
+ logger.bind(tag=TAG).error(f"ConnectionClosed")
+ raise
+
+ async def send_text(self, speaker: str, text: str, session_id):
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ serial_method=JSON,
+ ).as_bytes()
+ optional = Optional(event=EVENT_TaskRequest, sessionId=session_id).as_bytes()
+ payload = self.get_payload_bytes(
+ event=EVENT_TaskRequest, text=text, speaker=speaker
+ )
+ return await self.send_event(self.ws, header, optional, payload)
+
+ # 读取 res 数组某段 字符串内容
+ def read_res_content(self, res: bytes, offset: int):
+ content_size = int.from_bytes(res[offset : offset + 4], "big", signed=True)
+ offset += 4
+ content = str(res[offset : offset + content_size])
+ offset += content_size
+ return content, offset
+
+ # 读取 payload
+ def read_res_payload(self, res: bytes, offset: int):
+ payload_size = int.from_bytes(res[offset : offset + 4], "big", signed=True)
+ offset += 4
+ payload = res[offset : offset + payload_size]
+ offset += payload_size
+ return payload, offset
+
+ def parser_response(self, res) -> Response:
+ if isinstance(res, str):
+ raise RuntimeError(res)
+ response = Response(Header(), Optional())
+ # 解析结果
+ # header
+ header = response.header
+ num = 0b00001111
+ header.protocol_version = res[0] >> 4 & num
+ header.header_size = res[0] & 0x0F
+ header.message_type = (res[1] >> 4) & num
+ header.message_type_specific_flags = res[1] & 0x0F
+ header.serialization_method = res[2] >> num
+ header.message_compression = res[2] & 0x0F
+ header.reserved = res[3]
+ #
+ offset = 4
+ optional = response.optional
+ if header.message_type == FULL_SERVER_RESPONSE or AUDIO_ONLY_RESPONSE:
+ # read event
+ if header.message_type_specific_flags == MsgTypeFlagWithEvent:
+ optional.event = int.from_bytes(res[offset:8], "big", signed=True)
+ offset += 4
+ if optional.event == EVENT_NONE:
+ return response
+ # read connectionId
+ elif optional.event == EVENT_ConnectionStarted:
+ optional.connectionId, offset = self.read_res_content(res, offset)
+ elif optional.event == EVENT_ConnectionFailed:
+ optional.response_meta_json, offset = self.read_res_content(
+ res, offset
+ )
+ elif (
+ optional.event == EVENT_SessionStarted
+ or optional.event == EVENT_SessionFailed
+ or optional.event == EVENT_SessionFinished
+ ):
+ optional.sessionId, offset = self.read_res_content(res, offset)
+ optional.response_meta_json, offset = self.read_res_content(
+ res, offset
+ )
+ else:
+ optional.sessionId, offset = self.read_res_content(res, offset)
+ response.payload, offset = self.read_res_payload(res, offset)
+
+ elif header.message_type == ERROR_INFORMATION:
+ optional.errorCode = int.from_bytes(
+ res[offset : offset + 4], "big", signed=True
+ )
+ offset += 4
+ response.payload, offset = self.read_res_payload(res, offset)
+ return response
+
+ async def start_connection(self):
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ ).as_bytes()
+ optional = Optional(event=EVENT_Start_Connection).as_bytes()
+ payload = str.encode("{}")
+ return await self.send_event(self.ws, header, optional, payload)
+
+ def print_response(self, res, tag_msg: str):
+ logger.bind(tag=TAG).debug(f"===>{tag_msg} header:{res.header.__dict__}")
+ logger.bind(tag=TAG).debug(f"===>{tag_msg} optional:{res.optional.__dict__}")
+
+ def get_payload_bytes(
+ self,
+ uid="1234",
+ event=EVENT_NONE,
+ text="",
+ speaker="",
+ audio_format="pcm",
+ audio_sample_rate=16000,
+ ):
+ return str.encode(
+ json.dumps(
+ {
+ "user": {"uid": uid},
+ "event": event,
+ "namespace": "BidirectionalTTS",
+ "req_params": {
+ "text": text,
+ "speaker": speaker,
+ "audio_params": {
+ "format": audio_format,
+ "sample_rate": audio_sample_rate,
+ },
+ },
+ }
+ )
+ )
+
+ def wav_to_opus_data_audio_raw(self, raw_data_var, is_end=False):
+ opus_datas = self.opus_encoder.encode_pcm_to_opus(raw_data_var, is_end)
+ return opus_datas
+
+ def to_tts(self, text: str) -> list:
+ """非流式生成音频数据,用于生成音频及测试场景
+
+ Args:
+ text: 要转换的文本
+
+ Returns:
+ list: 音频数据列表
+ """
+ try:
+ # 创建事件循环
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+
+ # 生成会话ID
+ session_id = uuid.uuid4().__str__().replace("-", "")
+
+ # 存储音频数据
+ audio_data = []
+
+ async def _generate_audio():
+ # 创建新的WebSocket连接
+ ws_header = {
+ "X-Api-App-Key": self.appId,
+ "X-Api-Access-Key": self.access_token,
+ "X-Api-Resource-Id": self.resource_id,
+ "X-Api-Connect-Id": uuid.uuid4(),
+ }
+ ws = await websockets.connect(
+ self.ws_url, additional_headers=ws_header, max_size=1000000000
+ )
+
+ try:
+ # 启动会话
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ serial_method=JSON,
+ ).as_bytes()
+ optional = Optional(
+ event=EVENT_StartSession, sessionId=session_id
+ ).as_bytes()
+ payload = self.get_payload_bytes(
+ event=EVENT_StartSession, speaker=self.voice
+ )
+ await self.send_event(ws, header, optional, payload)
+
+ # 发送文本
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ serial_method=JSON,
+ ).as_bytes()
+ optional = Optional(
+ event=EVENT_TaskRequest, sessionId=session_id
+ ).as_bytes()
+ payload = self.get_payload_bytes(
+ event=EVENT_TaskRequest, text=text, speaker=self.voice
+ )
+ await self.send_event(ws, header, optional, payload)
+
+ # 发送结束会话请求
+ header = Header(
+ message_type=FULL_CLIENT_REQUEST,
+ message_type_specific_flags=MsgTypeFlagWithEvent,
+ serial_method=JSON,
+ ).as_bytes()
+ optional = Optional(
+ event=EVENT_FinishSession, sessionId=session_id
+ ).as_bytes()
+ payload = str.encode("{}")
+ await self.send_event(ws, header, optional, payload)
+
+ # 接收音频数据
+ while True:
+ msg = await ws.recv()
+ res = self.parser_response(msg)
+
+ if (
+ res.optional.event == EVENT_TTSResponse
+ and res.header.message_type == AUDIO_ONLY_RESPONSE
+ ):
+ opus_datas = self.wav_to_opus_data_audio_raw(res.payload)
+ audio_data.extend(opus_datas)
+ elif res.optional.event == EVENT_SessionFinished:
+ break
+
+ finally:
+ # 清理资源
+ try:
+ await ws.close()
+ except:
+ pass
+
+ # 运行异步任务
+ loop.run_until_complete(_generate_audio())
+ loop.close()
+
+ return audio_data
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
+ return []
diff --git a/main/xiaozhi-server/core/providers/tts/linkerai.py b/main/xiaozhi-server/core/providers/tts/linkerai.py
new file mode 100644
index 000000000..ee1085406
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/linkerai.py
@@ -0,0 +1,305 @@
+import queue
+import asyncio
+import traceback
+import aiohttp
+import requests
+import time
+from config.logger import setup_logging
+from core.utils.tts import MarkdownCleaner
+from core.providers.tts.base import TTSProviderBase
+from core.utils import opus_encoder_utils, textUtils
+from core.providers.tts.dto.dto import SentenceType, ContentType, InterfaceType
+
+TAG = __name__
+logger = setup_logging()
+
+
+class TTSProvider(TTSProviderBase):
+ def __init__(self, config, delete_audio_file):
+ super().__init__(config, delete_audio_file)
+ self.interface_type = InterfaceType.SINGLE_STREAM
+ self.access_token = config.get("access_token")
+ self.voice = config.get("voice")
+ self.api_url = config.get("api_url")
+ self.audio_format = "pcm"
+ self.before_stop_play_files = []
+ self.segment_count = 0 # 添加片段计数器
+
+ # 创建Opus编码器
+ self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
+ sample_rate=16000, channels=1, frame_size_ms=60
+ )
+
+ # 添加文本缓冲区
+ self.text_buffer = ""
+
+ # PCM缓冲区
+ self.pcm_buffer = bytearray()
+
+ ###################################################################################
+ # linkerai单流式TTS重写父类的方法--开始
+ ###################################################################################
+
+ def tts_text_priority_thread(self):
+ """流式文本处理线程"""
+ while not self.conn.stop_event.is_set():
+ try:
+ message = self.tts_text_queue.get(timeout=1)
+ if message.sentence_type == SentenceType.FIRST:
+ # 初始化参数
+ self.tts_stop_request = False
+ self.processed_chars = 0
+ self.tts_text_buff = []
+ self.segment_count = 0
+ self.tts_audio_first_sentence = True
+ self.before_stop_play_files.clear()
+ elif ContentType.TEXT == message.content_type:
+ self.tts_text_buff.append(message.content_detail)
+ segment_text = self._get_segment_text()
+ if segment_text:
+ self.to_tts_single_stream(segment_text)
+
+ elif ContentType.FILE == message.content_type:
+ logger.bind(tag=TAG).info(
+ f"添加音频文件到待播放列表: {message.content_file}"
+ )
+ self.before_stop_play_files.append(
+ (message.content_file, message.content_detail)
+ )
+
+ if message.sentence_type == SentenceType.LAST:
+ # 处理剩余的文本
+ self._process_remaining_text(True)
+
+ except queue.Empty:
+ continue
+ except Exception as e:
+ logger.bind(tag=TAG).error(
+ f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ )
+
+ def _process_remaining_text(self, is_last=False):
+ """处理剩余的文本并生成语音
+
+ Returns:
+ bool: 是否成功处理了文本
+ """
+ full_text = "".join(self.tts_text_buff)
+ remaining_text = full_text[self.processed_chars :]
+ if remaining_text:
+ segment_text = textUtils.get_string_no_punctuation_or_emoji(remaining_text)
+ if segment_text:
+ self.to_tts_single_stream(segment_text, is_last)
+ self.processed_chars += len(full_text)
+ else:
+ self._process_before_stop_play_files()
+ else:
+ self._process_before_stop_play_files()
+
+ def to_tts_single_stream(self, text, is_last=False):
+ try:
+ max_repeat_time = 5
+ text = MarkdownCleaner.clean_markdown(text)
+ try:
+ asyncio.run(self.text_to_speak(text, is_last))
+ except Exception as e:
+ logger.bind(tag=TAG).warning(
+ f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
+ )
+ max_repeat_time -= 1
+
+ if max_repeat_time > 0:
+ logger.bind(tag=TAG).info(
+ f"语音生成成功: {text},重试{5 - max_repeat_time}次"
+ )
+ else:
+ logger.bind(tag=TAG).error(
+ f"语音生成失败: {text},请检查网络或服务是否正常"
+ )
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
+ finally:
+ return None
+
+ ###################################################################################
+ # linkerai单流式TTS重写父类的方法--结束
+ ###################################################################################
+
+ async def text_to_speak(self, text, is_last):
+ """流式处理TTS音频,每句只推送一次音频列表"""
+ await self._tts_request(text, is_last)
+
+ async def close(self):
+ """资源清理"""
+ await super().close()
+ if hasattr(self, "opus_encoder"):
+ self.opus_encoder.close()
+
+ async def _tts_request(self, text: str, is_last: bool) -> None:
+ params = {
+ "tts_text": text,
+ "spk_id": self.voice,
+ "frame_durition": 60,
+ "stream": "true",
+ "target_sr": 16000,
+ "audio_format": "pcm",
+ "instruct_text": "请生成一段自然流畅的语音",
+ }
+ headers = {
+ "Authorization": f"Bearer {self.access_token}",
+ "Content-Type": "application/json",
+ }
+
+ # 一帧 PCM 所需字节数:60 ms × 16 kHz × 1 ch × 2 B = 1 920
+ frame_bytes = int(
+ self.opus_encoder.sample_rate
+ * self.opus_encoder.channels # 1
+ * self.opus_encoder.frame_size_ms
+ / 1000
+ * 2
+ ) # 16-bit = 2 bytes
+
+ try:
+ async with aiohttp.ClientSession() as session:
+ async with session.get(
+ self.api_url, params=params, headers=headers, timeout=10
+ ) as resp:
+
+ if resp.status != 200:
+ logger.bind(tag=TAG).error(
+ f"TTS请求失败: {resp.status}, {await resp.text()}"
+ )
+ self.tts_audio_queue.put((SentenceType.LAST, [], None))
+ return
+
+ self.pcm_buffer.clear()
+ opus_datas_cache = []
+
+ self.tts_audio_queue.put((SentenceType.FIRST, [], text))
+
+ # 兼容 iter_chunked / iter_chunks / iter_any
+ async for chunk in resp.content.iter_any():
+ data = chunk[0] if isinstance(chunk, (list, tuple)) else chunk
+ if not data:
+ continue
+
+ # 拼到 buffer
+ self.pcm_buffer.extend(data)
+
+ # 够一帧就编码
+ while len(self.pcm_buffer) >= frame_bytes:
+ frame = bytes(self.pcm_buffer[:frame_bytes])
+ del self.pcm_buffer[:frame_bytes]
+
+ opus = self.opus_encoder.encode_pcm_to_opus(
+ frame, end_of_stream=False
+ )
+ if opus:
+ if self.segment_count < 10: # 前10个片段直接发送
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, opus, None)
+ )
+ self.segment_count += 1
+ else:
+ opus_datas_cache.extend(opus)
+
+ # flush 剩余不足一帧的数据
+ if self.pcm_buffer:
+ opus = self.opus_encoder.encode_pcm_to_opus(
+ bytes(self.pcm_buffer), end_of_stream=True
+ )
+ if opus:
+ if self.segment_count < 10: # 前10个片段直接发送
+ # 直接发送
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, opus, None)
+ )
+ self.segment_count += 1
+ else:
+ # 后续片段缓存
+ opus_datas_cache.extend(opus)
+ self.pcm_buffer.clear()
+
+ # 如果不是前10个片段,发送缓存的数据
+ if self.segment_count >= 10 and opus_datas_cache:
+ self.tts_audio_queue.put(
+ (SentenceType.MIDDLE, opus_datas_cache, None)
+ )
+
+ # 如果是最后一段,输出音频获取完毕
+ if is_last:
+ self._process_before_stop_play_files()
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
+ self.tts_audio_queue.put((SentenceType.LAST, [], None))
+
+ def to_tts(self, text: str) -> list:
+ """非流式TTS处理,用于测试及保存音频文件的场景
+
+ Args:
+ text: 要转换的文本
+
+ Returns:
+ list: 返回opus编码后的音频数据列表
+ """
+ start_time = time.time()
+ text = MarkdownCleaner.clean_markdown(text)
+
+ params = {
+ "tts_text": text,
+ "spk_id": self.voice,
+ "frame_duration": 60,
+ "stream": False,
+ "target_sr": 16000,
+ "audio_format": self.audio_format,
+ "instruct_text": "请生成一段自然流畅的语音",
+ }
+ headers = {
+ "Authorization": f"Bearer {self.access_token}",
+ "Content-Type": "application/json",
+ }
+
+ try:
+ with requests.get(
+ self.api_url, params=params, headers=headers, timeout=5
+ ) as response:
+ if response.status_code != 200:
+ logger.bind(tag=TAG).error(
+ f"TTS请求失败: {response.status_code}, {response.text}"
+ )
+ return []
+
+ logger.info(f"TTS请求成功: {text}, 耗时: {time.time() - start_time}秒")
+
+ # 使用opus编码器处理PCM数据
+ opus_datas = []
+ pcm_data = response.content
+
+ # 计算每帧的字节数
+ frame_bytes = int(
+ self.opus_encoder.sample_rate
+ * self.opus_encoder.channels
+ * self.opus_encoder.frame_size_ms
+ / 1000
+ * 2
+ )
+
+ # 分帧处理PCM数据
+ for i in range(0, len(pcm_data), frame_bytes):
+ frame = pcm_data[i : i + frame_bytes]
+ if len(frame) < frame_bytes:
+ # 最后一帧可能不足,用0填充
+ frame = frame + b"\x00" * (frame_bytes - len(frame))
+
+ opus = self.opus_encoder.encode_pcm_to_opus(
+ frame, end_of_stream=(i + frame_bytes >= len(pcm_data))
+ )
+ if opus:
+ opus_datas.extend(opus)
+
+ return opus_datas
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"TTS请求异常: {e}")
+ return []
diff --git a/main/xiaozhi-server/core/providers/tts/minimax.py b/main/xiaozhi-server/core/providers/tts/minimax.py
index dd406b64a..75e25e2ee 100644
--- a/main/xiaozhi-server/core/providers/tts/minimax.py
+++ b/main/xiaozhi-server/core/providers/tts/minimax.py
@@ -14,9 +14,9 @@ class TTSProvider(TTSProviderBase):
self.api_key = config.get("api_key")
self.model = config.get("model")
if config.get("private_voice"):
- self.voice_id = config.get("private_voice")
+ self.voice = config.get("private_voice")
else:
- self.voice_id = config.get("voice_id")
+ self.voice = config.get("voice_id")
default_voice_setting = {
"voice_id": "female-shaonv",
@@ -43,8 +43,8 @@ class TTSProvider(TTSProviderBase):
self.audio_setting = {**defult_audio_setting, **config.get("audio_setting", {})}
self.timber_weights = parse_string_to_list(config.get("timber_weights"))
- if self.voice_id:
- self.voice_setting["voice_id"] = self.voice_id
+ if self.voice:
+ self.voice_setting["voice_id"] = self.voice
self.host = "api.minimax.chat"
self.api_url = f"https://{self.host}/v1/t2a_v2?GroupId={self.group_id}"
@@ -52,6 +52,7 @@ class TTSProvider(TTSProviderBase):
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
}
+ self.audio_file_type = defult_audio_setting.get("format", "mp3")
def generate_filename(self, extension=".mp3"):
return os.path.join(
@@ -80,8 +81,12 @@ class TTSProvider(TTSProviderBase):
# 检查返回请求数据的status_code是否为0
if resp.json()["base_resp"]["status_code"] == 0:
data = resp.json()["data"]["audio"]
- file_to_save = open(output_file, "wb")
- file_to_save.write(bytes.fromhex(data))
+ audio_bytes = bytes.fromhex(data)
+ if output_file:
+ with open(output_file, "wb") as file_to_save:
+ file_to_save.write(audio_bytes)
+ else:
+ return audio_bytes
else:
raise Exception(
f"{__name__} status_code: {resp.status_code} response: {resp.content}"
diff --git a/main/xiaozhi-server/core/providers/tts/openai.py b/main/xiaozhi-server/core/providers/tts/openai.py
index a7c4e30d4..20bf9a96a 100644
--- a/main/xiaozhi-server/core/providers/tts/openai.py
+++ b/main/xiaozhi-server/core/providers/tts/openai.py
@@ -1,7 +1,4 @@
-import os
-import uuid
import requests
-from datetime import datetime
from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
@@ -20,20 +17,17 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice", "alloy")
- self.response_format = "wav"
+ self.response_format = config.get("format", "wav")
+ self.audio_file_type = config.get("format", "wav")
# 处理空字符串的情况
speed = config.get("speed", "1.0")
self.speed = float(speed) if speed else 1.0
self.output_file = config.get("output_dir", "tmp/")
- check_model_key("TTS", self.api_key)
-
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
+ model_key_msg = check_model_key("TTS", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
async def text_to_speak(self, text, output_file):
headers = {
@@ -49,8 +43,11 @@ class TTSProvider(TTSProviderBase):
}
response = requests.post(self.api_url, json=data, headers=headers)
if response.status_code == 200:
- with open(output_file, "wb") as audio_file:
- audio_file.write(response.content)
+ if output_file:
+ with open(output_file, "wb") as audio_file:
+ audio_file.write(response.content)
+ else:
+ return response.content
else:
raise Exception(
f"OpenAI TTS请求失败: {response.status_code} - {response.text}"
diff --git a/main/xiaozhi-server/core/providers/tts/siliconflow.py b/main/xiaozhi-server/core/providers/tts/siliconflow.py
index 9e30f7217..b85cebf43 100644
--- a/main/xiaozhi-server/core/providers/tts/siliconflow.py
+++ b/main/xiaozhi-server/core/providers/tts/siliconflow.py
@@ -1,7 +1,4 @@
-import os
-import uuid
import requests
-from datetime import datetime
from core.providers.tts.base import TTSProviderBase
@@ -14,7 +11,8 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("private_voice")
else:
self.voice = config.get("voice")
- self.response_format = config.get("response_format")
+ self.response_format = config.get("response_format", "mp3")
+ self.audio_file_type = config.get("response_format", "mp3")
self.sample_rate = config.get("sample_rate")
self.speed = float(config.get("speed", 1.0))
self.gain = config.get("gain")
@@ -22,12 +20,6 @@ class TTSProvider(TTSProviderBase):
self.host = "api.siliconflow.cn"
self.api_url = f"https://{self.host}/v1/audio/speech"
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
-
async def text_to_speak(self, text, output_file):
request_json = {
"model": self.model,
@@ -44,7 +36,10 @@ class TTSProvider(TTSProviderBase):
"POST", self.api_url, json=request_json, headers=headers
)
data = response.content
- file_to_save = open(output_file, "wb")
- file_to_save.write(data)
+ if output_file:
+ with open(output_file, "wb") as file_to_save:
+ file_to_save.write(data)
+ else:
+ return data
except Exception as e:
- raise Exception(f"{__name__} error: {e}")
\ No newline at end of file
+ raise Exception(f"{__name__} error: {e}")
diff --git a/main/xiaozhi-server/core/providers/tts/tencent.py b/main/xiaozhi-server/core/providers/tts/tencent.py
index f2501e2fc..a24936324 100644
--- a/main/xiaozhi-server/core/providers/tts/tencent.py
+++ b/main/xiaozhi-server/core/providers/tts/tencent.py
@@ -1,6 +1,5 @@
import hashlib
import hmac
-import os
import time
import uuid
import json
@@ -23,6 +22,7 @@ class TTSProvider(TTSProviderBase):
self.api_url = "https://tts.tencentcloudapi.com" # 正确的API端点
self.region = config.get("region")
self.output_file = config.get("output_dir")
+ self.audio_file_type = config.get("format", "wav")
def _get_auth_headers(self, request_body):
"""生成鉴权请求头"""
@@ -121,12 +121,6 @@ class TTSProvider(TTSProviderBase):
msg = msg.encode("utf-8")
return hmac.new(key, msg, hashlib.sha256).digest()
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
-
async def text_to_speak(self, text, output_file):
# 构建请求体
request_json = {
@@ -155,12 +149,14 @@ class TTSProvider(TTSProviderBase):
f"API返回错误: {error_info['Code']}: {error_info['Message']}"
)
- # 提取音频数据
- audio_data = response_data["Response"].get("Audio")
- if audio_data:
- # 解码Base64音频数据并保存
- with open(output_file, "wb") as f:
- f.write(base64.b64decode(audio_data))
+ # 解码Base64音频数据
+ audio_bytes = base64.b64decode(response_data["Response"].get("Audio"))
+ if audio_bytes:
+ if output_file:
+ with open(output_file, "wb") as f:
+ f.write(audio_bytes)
+ else:
+ return audio_bytes
else:
raise Exception(f"{__name__}: 没有返回音频数据: {response_data}")
else:
diff --git a/main/xiaozhi-server/core/providers/tts/ttson.py b/main/xiaozhi-server/core/providers/tts/ttson.py
index f3a0fbdcd..91deeed96 100644
--- a/main/xiaozhi-server/core/providers/tts/ttson.py
+++ b/main/xiaozhi-server/core/providers/tts/ttson.py
@@ -19,9 +19,9 @@ class TTSProvider(TTSProviderBase):
"https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=",
)
if config.get("private_voice"):
- self.voice_id = int(config.get("private_voice"))
+ self.voice = int(config.get("private_voice"))
else:
- self.voice_id = int(config.get("voice_id", 1695))
+ self.voice = int(config.get("voice_id", 1695))
self.token = config.get("token")
self.to_lang = config.get("to_lang")
self.volume_change_dB = int(config.get("volume_change_dB", 0))
@@ -30,6 +30,7 @@ class TTSProvider(TTSProviderBase):
self.output_file = config.get("output_dir")
self.pitch_factor = int(config.get("pitch_factor", 0))
self.format = config.get("format", "mp3")
+ self.audio_file_type = config.get("format", "mp3")
self.emotion = int(config.get("emotion", 1))
self.header = {"Content-Type": "application/json"}
@@ -49,7 +50,7 @@ class TTSProvider(TTSProviderBase):
"emotion": self.emotion,
"format": self.format,
"volume_change_dB": self.volume_change_dB,
- "voice_id": self.voice_id,
+ "voice_id": self.voice,
"pitch_factor": self.pitch_factor,
"speed_factor": self.speed_factor,
"token": self.token,
@@ -73,13 +74,15 @@ class TTSProvider(TTSProviderBase):
)
audio_content = requests.get(result)
- with open(output_file, "wb") as f:
- f.write(audio_content.content)
- return True
+ if output_file:
+ with open(output_file, "wb") as f:
+ f.write(audio_content.content)
+ else:
+ return audio_content.content
voice_path = resp_json.get("voice_path")
des_path = output_file
shutil.move(voice_path, des_path)
except Exception as e:
print("error:", e)
- raise Exception(f"{__name__}: TTS请求失败")
\ No newline at end of file
+ raise Exception(f"{__name__}: TTS请求失败")
diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py
index 8ec1f6eb5..9df5188c8 100644
--- a/main/xiaozhi-server/core/providers/vad/silero.py
+++ b/main/xiaozhi-server/core/providers/vad/silero.py
@@ -12,13 +12,12 @@ logger = setup_logging()
class VADProvider(VADProviderBase):
def __init__(self, config):
logger.bind(tag=TAG).info("SileroVAD", config)
- self.model, self.utils = torch.hub.load(
+ self.model, _ = torch.hub.load(
repo_or_dir=config["model_dir"],
source="local",
model="silero_vad",
force_reload=False,
)
- (get_speech_timestamps, _, _, _, _) = self.utils
self.decoder = opuslib_next.Decoder(16000, 1)
@@ -36,6 +35,10 @@ class VADProvider(VADProviderBase):
pcm_frame = self.decoder.decode(opus_packet, 960)
conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区
+ # 初始化帧计数器
+ if not hasattr(conn, "client_voice_frame_count"):
+ conn.client_voice_frame_count = 0
+
# 处理缓冲区中的完整帧(每次处理512采样点)
client_have_voice = False
while len(conn.client_audio_buffer) >= 512 * 2:
@@ -51,9 +54,17 @@ class VADProvider(VADProviderBase):
# 检测语音活动
with torch.no_grad():
speech_prob = self.model(audio_tensor, 16000).item()
- client_have_voice = speech_prob >= self.vad_threshold
+ is_voice = speech_prob >= self.vad_threshold
- # 如果之前有声音,但本次没有声音,且与上次有声音的时间查已经超过了静默阈值,则认为已经说完一句话
+ if is_voice:
+ conn.client_voice_frame_count += 1
+ else:
+ conn.client_voice_frame_count = 0
+
+ # 只有连续4帧检测到语音才认为有语音
+ client_have_voice = conn.client_voice_frame_count >= 4
+
+ # 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
if conn.client_have_voice and not client_have_voice:
stop_duration = (
time.time() * 1000 - conn.client_have_voice_last_time
diff --git a/main/xiaozhi-server/core/providers/vllm/base.py b/main/xiaozhi-server/core/providers/vllm/base.py
new file mode 100644
index 000000000..843873c90
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/vllm/base.py
@@ -0,0 +1,12 @@
+from abc import ABC, abstractmethod
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+
+class VLLMProviderBase(ABC):
+ @abstractmethod
+ def response(self, question, base64_image):
+ """VLLM response generator"""
+ pass
diff --git a/main/xiaozhi-server/core/providers/vllm/openai.py b/main/xiaozhi-server/core/providers/vllm/openai.py
new file mode 100644
index 000000000..12d8198dc
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/vllm/openai.py
@@ -0,0 +1,67 @@
+import openai
+import json
+from config.logger import setup_logging
+from core.utils.util import check_model_key
+from core.providers.vllm.base import VLLMProviderBase
+
+TAG = __name__
+logger = setup_logging()
+
+
+class VLLMProvider(VLLMProviderBase):
+ def __init__(self, config):
+ self.model_name = config.get("model_name")
+ self.api_key = config.get("api_key")
+ if "base_url" in config:
+ self.base_url = config.get("base_url")
+ else:
+ self.base_url = config.get("url")
+
+ param_defaults = {
+ "max_tokens": (500, int),
+ "temperature": (0.7, lambda x: round(float(x), 1)),
+ "top_p": (1.0, lambda x: round(float(x), 1)),
+ }
+
+ for param, (default, converter) in param_defaults.items():
+ value = config.get(param)
+ try:
+ setattr(
+ self,
+ param,
+ converter(value) if value not in (None, "") else default,
+ )
+ except (ValueError, TypeError):
+ setattr(self, param, default)
+
+ model_key_msg = check_model_key("VLLM", self.api_key)
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
+ self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
+
+ def response(self, question, base64_image):
+ try:
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": question},
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": f"data:image/jpeg;base64,{base64_image}"
+ },
+ },
+ ],
+ }
+ ]
+
+ response = self.client.chat.completions.create(
+ model=self.model_name, messages=messages, stream=False
+ )
+
+ return response.choices[0].message.content
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Error in response generation: {e}")
+ raise
diff --git a/main/xiaozhi-server/core/utils/auth.py b/main/xiaozhi-server/core/utils/auth.py
new file mode 100644
index 000000000..fd36cbeb0
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/auth.py
@@ -0,0 +1,126 @@
+import jwt
+import time
+import json
+import os
+from datetime import datetime, timedelta, timezone
+from typing import Tuple, Optional
+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
+from cryptography.hazmat.primitives import padding
+from cryptography.hazmat.backends import default_backend
+import base64
+
+
+class AuthToken:
+ def __init__(self, secret_key: str):
+ self.secret_key = secret_key.encode() # 转换为字节
+ # 从密钥派生固定长度的加密密钥 (32字节 for AES-256)
+ self.encryption_key = self._derive_key(32)
+
+ def _derive_key(self, length: int) -> bytes:
+ """派生固定长度的密钥"""
+ from cryptography.hazmat.primitives import hashes
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
+
+ # 使用固定盐值(实际生产环境应使用随机盐)
+ salt = b"fixed_salt_placeholder" # 生产环境应改为随机生成
+ kdf = PBKDF2HMAC(
+ algorithm=hashes.SHA256(),
+ length=length,
+ salt=salt,
+ iterations=100000,
+ backend=default_backend(),
+ )
+ return kdf.derive(self.secret_key)
+
+ def _encrypt_payload(self, payload: dict) -> str:
+ """使用AES-GCM加密整个payload"""
+ # 将payload转换为JSON字符串
+ payload_json = json.dumps(payload)
+
+ # 生成随机IV
+ iv = os.urandom(12)
+ # 创建加密器
+ cipher = Cipher(
+ algorithms.AES(self.encryption_key),
+ modes.GCM(iv),
+ backend=default_backend(),
+ )
+ encryptor = cipher.encryptor()
+
+ # 加密并生成标签
+ ciphertext = encryptor.update(payload_json.encode()) + encryptor.finalize()
+ tag = encryptor.tag
+
+ # 组合 IV + 密文 + 标签
+ encrypted_data = iv + ciphertext + tag
+ return base64.urlsafe_b64encode(encrypted_data).decode()
+
+ def _decrypt_payload(self, encrypted_data: str) -> dict:
+ """解密AES-GCM加密的payload"""
+ # 解码Base64
+ data = base64.urlsafe_b64decode(encrypted_data.encode())
+ # 拆分组件
+ iv = data[:12]
+ tag = data[-16:]
+ ciphertext = data[12:-16]
+
+ # 创建解密器
+ cipher = Cipher(
+ algorithms.AES(self.encryption_key),
+ modes.GCM(iv, tag),
+ backend=default_backend(),
+ )
+ decryptor = cipher.decryptor()
+
+ # 解密
+ plaintext = decryptor.update(ciphertext) + decryptor.finalize()
+ return json.loads(plaintext.decode())
+
+ def generate_token(self, device_id: str) -> str:
+ """
+ 生成JWT token
+ :param device_id: 设备ID
+ :return: JWT token字符串
+ """
+ # 设置过期时间为1小时后
+ expire_time = datetime.now(timezone.utc) + timedelta(hours=1)
+
+ # 创建原始payload
+ payload = {"device_id": device_id, "exp": expire_time.timestamp()}
+
+ # 加密整个payload
+ encrypted_payload = self._encrypt_payload(payload)
+
+ # 创建外层payload,包含加密数据
+ outer_payload = {"data": encrypted_payload}
+
+ # 使用JWT进行编码
+ token = jwt.encode(outer_payload, self.secret_key, algorithm="HS256")
+ return token
+
+ def verify_token(self, token: str) -> Tuple[bool, Optional[str]]:
+ """
+ 验证token
+ :param token: JWT token字符串
+ :return: (是否有效, 设备ID)
+ """
+ try:
+ # 先验证外层JWT(签名和过期时间)
+ outer_payload = jwt.decode(token, self.secret_key, algorithms=["HS256"])
+
+ # 解密内层payload
+ inner_payload = self._decrypt_payload(outer_payload["data"])
+
+ # 再次检查过期时间(双重验证)
+ if inner_payload["exp"] < time.time():
+ return False, None
+
+ return True, inner_payload["device_id"]
+
+ except jwt.InvalidTokenError:
+ return False, None
+ except json.JSONDecodeError:
+ return False, None
+ except Exception as e: # 捕获其他可能的错误
+ print(f"Token verification failed: {str(e)}")
+ return False, None
diff --git a/main/xiaozhi-server/core/utils/modules_initialize.py b/main/xiaozhi-server/core/utils/modules_initialize.py
new file mode 100644
index 000000000..f2e3968e2
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/modules_initialize.py
@@ -0,0 +1,128 @@
+from typing import Dict, Any
+from config.logger import setup_logging
+from core.utils import tts, llm, intent, memory, vad, asr
+
+TAG = __name__
+logger = setup_logging()
+
+
+def initialize_modules(
+ logger,
+ config: Dict[str, Any],
+ init_vad=False,
+ init_asr=False,
+ init_llm=False,
+ init_tts=False,
+ init_memory=False,
+ init_intent=False,
+) -> Dict[str, Any]:
+ """
+ 初始化所有模块组件
+
+ Args:
+ config: 配置字典
+
+ Returns:
+ Dict[str, Any]: 包含所有初始化后的模块的字典
+ """
+ modules = {}
+
+ # 初始化TTS模块
+ if init_tts:
+ select_tts_module = config["selected_module"]["TTS"]
+ modules["tts"] = initialize_tts(config)
+ logger.bind(tag=TAG).info(f"初始化组件: tts成功 {select_tts_module}")
+
+ # 初始化LLM模块
+ if init_llm:
+ select_llm_module = config["selected_module"]["LLM"]
+ llm_type = (
+ select_llm_module
+ if "type" not in config["LLM"][select_llm_module]
+ else config["LLM"][select_llm_module]["type"]
+ )
+ modules["llm"] = llm.create_instance(
+ llm_type,
+ config["LLM"][select_llm_module],
+ )
+ logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}")
+
+ # 初始化Intent模块
+ if init_intent:
+ select_intent_module = config["selected_module"]["Intent"]
+ intent_type = (
+ select_intent_module
+ if "type" not in config["Intent"][select_intent_module]
+ else config["Intent"][select_intent_module]["type"]
+ )
+ modules["intent"] = intent.create_instance(
+ intent_type,
+ config["Intent"][select_intent_module],
+ )
+ logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}")
+
+ # 初始化Memory模块
+ if init_memory:
+ select_memory_module = config["selected_module"]["Memory"]
+ memory_type = (
+ select_memory_module
+ if "type" not in config["Memory"][select_memory_module]
+ else config["Memory"][select_memory_module]["type"]
+ )
+ modules["memory"] = memory.create_instance(
+ memory_type,
+ config["Memory"][select_memory_module],
+ config.get("summaryMemory", None),
+ )
+ logger.bind(tag=TAG).info(f"初始化组件: memory成功 {select_memory_module}")
+
+ # 初始化VAD模块
+ if init_vad:
+ select_vad_module = config["selected_module"]["VAD"]
+ vad_type = (
+ select_vad_module
+ if "type" not in config["VAD"][select_vad_module]
+ else config["VAD"][select_vad_module]["type"]
+ )
+ modules["vad"] = vad.create_instance(
+ vad_type,
+ config["VAD"][select_vad_module],
+ )
+ logger.bind(tag=TAG).info(f"初始化组件: vad成功 {select_vad_module}")
+
+ # 初始化ASR模块
+ if init_asr:
+ select_asr_module = config["selected_module"]["ASR"]
+ modules["asr"] = initialize_asr(config)
+ logger.bind(tag=TAG).info(f"初始化组件: asr成功 {select_asr_module}")
+ return modules
+
+
+def initialize_tts(config):
+ select_tts_module = config["selected_module"]["TTS"]
+ tts_type = (
+ select_tts_module
+ if "type" not in config["TTS"][select_tts_module]
+ else config["TTS"][select_tts_module]["type"]
+ )
+ new_tts = tts.create_instance(
+ tts_type,
+ config["TTS"][select_tts_module],
+ str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
+ )
+ return new_tts
+
+
+def initialize_asr(config):
+ select_asr_module = config["selected_module"]["ASR"]
+ asr_type = (
+ select_asr_module
+ if "type" not in config["ASR"][select_asr_module]
+ else config["ASR"][select_asr_module]["type"]
+ )
+ new_asr = asr.create_instance(
+ asr_type,
+ config["ASR"][select_asr_module],
+ str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
+ )
+ return new_asr
diff --git a/main/xiaozhi-server/core/utils/opus_encoder_utils.py b/main/xiaozhi-server/core/utils/opus_encoder_utils.py
new file mode 100644
index 000000000..23d26c398
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/opus_encoder_utils.py
@@ -0,0 +1,136 @@
+"""
+Opus编码工具类
+将PCM音频数据编码为Opus格式
+"""
+
+import logging
+import traceback
+
+import numpy as np
+from typing import List, Optional
+from opuslib_next import Encoder
+from opuslib_next import constants
+
+
+class OpusEncoderUtils:
+ """PCM到Opus的编码器"""
+
+ def __init__(self, sample_rate: int, channels: int, frame_size_ms: int):
+ """
+ 初始化Opus编码器
+
+ Args:
+ sample_rate: 采样率 (Hz)
+ channels: 通道数 (1=单声道, 2=立体声)
+ frame_size_ms: 帧大小 (毫秒)
+ """
+ self.sample_rate = sample_rate
+ self.channels = channels
+ self.frame_size_ms = frame_size_ms
+ # 计算每帧样本数 = 采样率 * 帧大小(毫秒) / 1000
+ self.frame_size = (sample_rate * frame_size_ms) // 1000
+ # 总帧大小 = 每帧样本数 * 通道数
+ self.total_frame_size = self.frame_size * channels
+
+ # 比特率和复杂度设置
+ self.bitrate = 24000 # bps
+ self.complexity = 10 # 最高质量
+
+ # 缓冲区初始化为空
+ self.buffer = np.array([], dtype=np.int16)
+
+ try:
+ # 创建Opus编码器
+ self.encoder = Encoder(
+ sample_rate, channels, constants.APPLICATION_AUDIO # 音频优化模式
+ )
+ self.encoder.bitrate = self.bitrate
+ self.encoder.complexity = self.complexity
+ self.encoder.signal = constants.SIGNAL_VOICE # 语音信号优化
+ except Exception as e:
+ logging.error(f"初始化Opus编码器失败: {e}")
+ raise RuntimeError("初始化失败") from e
+
+ def reset_state(self):
+ """重置编码器状态"""
+ self.encoder.reset_state()
+ self.buffer = np.array([], dtype=np.int16)
+
+ def encode_pcm_to_opus(self, pcm_data: bytes, end_of_stream: bool) -> List[bytes]:
+ """
+ 将PCM数据编码为Opus格式
+
+ Args:
+ pcm_data: PCM字节数据
+ end_of_stream: 是否为流的结束
+
+ Returns:
+ Opus数据包列表
+ """
+ # 将字节数据转换为short数组
+ new_samples = self._convert_bytes_to_shorts(pcm_data)
+
+ # 校验PCM数据
+ self._validate_pcm_data(new_samples)
+
+ # 将新数据追加到缓冲区
+ self.buffer = np.append(self.buffer, new_samples)
+
+ opus_packets = []
+ offset = 0
+
+ # 处理所有完整帧
+ while offset <= len(self.buffer) - self.total_frame_size:
+ frame = self.buffer[offset : offset + self.total_frame_size]
+ output = self._encode(frame)
+ if output:
+ opus_packets.append(output)
+ offset += self.total_frame_size
+
+ # 保留未处理的样本
+ self.buffer = self.buffer[offset:]
+
+ # 流结束时处理剩余数据
+ if end_of_stream and len(self.buffer) > 0:
+ # 创建最后一帧并用0填充
+ last_frame = np.zeros(self.total_frame_size, dtype=np.int16)
+ last_frame[: len(self.buffer)] = self.buffer
+
+ output = self._encode(last_frame)
+ if output:
+ opus_packets.append(output)
+ self.buffer = np.array([], dtype=np.int16)
+
+ return opus_packets
+
+ def _encode(self, frame: np.ndarray) -> Optional[bytes]:
+ """编码一帧音频数据"""
+ try:
+ # 将numpy数组转换为bytes
+ frame_bytes = frame.tobytes()
+ # opuslib要求输入字节数必须是channels*2的倍数
+ encoded = self.encoder.encode(frame_bytes, self.frame_size)
+ return encoded
+ except Exception as e:
+ logging.error(f"Opus编码失败: {e}")
+ traceback.print_exc()
+ return None
+
+ def _convert_bytes_to_shorts(self, bytes_data: bytes) -> np.ndarray:
+ """将字节数组转换为short数组 (16位PCM)"""
+ # 假设输入是小端字节序的16位PCM
+ return np.frombuffer(bytes_data, dtype=np.int16)
+
+ def _validate_pcm_data(self, pcm_shorts: np.ndarray) -> None:
+ """验证PCM数据是否有效"""
+ # 16位PCM数据范围是 -32768 到 32767
+ if np.any((pcm_shorts < -32768) | (pcm_shorts > 32767)):
+ invalid_samples = pcm_shorts[(pcm_shorts < -32768) | (pcm_shorts > 32767)]
+ logging.warning(f"发现无效PCM样本: {invalid_samples[:5]}...")
+ # 在实际应用中可以选择裁剪而不是抛出异常
+ # np.clip(pcm_shorts, -32768, 32767, out=pcm_shorts)
+
+ def close(self):
+ """关闭编码器并释放资源"""
+ # opuslib没有明确的关闭方法,Python的垃圾回收会处理
+ pass
diff --git a/main/xiaozhi-server/core/utils/p3.py b/main/xiaozhi-server/core/utils/p3.py
index a022a2d24..c75b968e0 100644
--- a/main/xiaozhi-server/core/utils/p3.py
+++ b/main/xiaozhi-server/core/utils/p3.py
@@ -29,5 +29,31 @@ def decode_opus_from_file(input_file):
total_frames += 1
# 计算总时长
+ total_duration = (total_frames * frame_duration_ms) / 1000.0
+ return opus_datas, total_duration
+
+def decode_opus_from_bytes(input_bytes):
+ """
+ 从p3二进制数据中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。
+ """
+ import io
+ opus_datas = []
+ total_frames = 0
+ sample_rate = 16000 # 文件采样率
+ frame_duration_ms = 60 # 帧时长
+ frame_size = int(sample_rate * frame_duration_ms / 1000)
+
+ f = io.BytesIO(input_bytes)
+ while True:
+ header = f.read(4)
+ if not header:
+ break
+ _, _, data_len = struct.unpack('>BBH', header)
+ opus_data = f.read(data_len)
+ if len(opus_data) != data_len:
+ raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the bytes.")
+ opus_datas.append(opus_data)
+ total_frames += 1
+
total_duration = (total_frames * frame_duration_ms) / 1000.0
return opus_datas, total_duration
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/utils/textUtils.py b/main/xiaozhi-server/core/utils/textUtils.py
new file mode 100644
index 000000000..603d964c6
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/textUtils.py
@@ -0,0 +1,46 @@
+def get_string_no_punctuation_or_emoji(s):
+ """去除字符串首尾的空格、标点符号和表情符号"""
+ chars = list(s)
+ # 处理开头的字符
+ start = 0
+ while start < len(chars) and is_punctuation_or_emoji(chars[start]):
+ start += 1
+ # 处理结尾的字符
+ end = len(chars) - 1
+ while end >= start and is_punctuation_or_emoji(chars[end]):
+ end -= 1
+ return "".join(chars[start : end + 1])
+
+
+def is_punctuation_or_emoji(char):
+ """检查字符是否为空格、指定标点或表情符号"""
+ # 定义需要去除的中英文标点(包括全角/半角)
+ punctuation_set = {
+ ",",
+ ",", # 中文逗号 + 英文逗号
+ "。",
+ ".", # 中文句号 + 英文句号
+ "!",
+ "!", # 中文感叹号 + 英文感叹号
+ "-",
+ "-", # 英文连字符 + 中文全角横线
+ "、", # 中文顿号
+ "[",
+ "]", # 方括号
+ "【",
+ "】", # 中文方括号
+ }
+ if char.isspace() or char in punctuation_set:
+ return True
+ # 检查表情符号(保留原有逻辑)
+ code_point = ord(char)
+ emoji_ranges = [
+ (0x1F600, 0x1F64F),
+ (0x1F300, 0x1F5FF),
+ (0x1F680, 0x1F6FF),
+ (0x1F900, 0x1F9FF),
+ (0x1FA70, 0x1FAFF),
+ (0x2600, 0x26FF),
+ (0x2700, 0x27BF),
+ ]
+ return any(start <= code_point <= end for start, end in emoji_ranges)
diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py
index 9ab77a5a7..14f53b969 100644
--- a/main/xiaozhi-server/core/utils/util.py
+++ b/main/xiaozhi-server/core/utils/util.py
@@ -3,12 +3,14 @@ import socket
import subprocess
import re
import os
+import wave
+from io import BytesIO
+from core.utils import p3
import numpy as np
import requests
import opuslib_next
from pydub import AudioSegment
-from typing import Dict, Any
-from core.utils import tts, llm, intent, memory, vad, asr
+import copy
TAG = __name__
emoji_map = {
@@ -184,10 +186,8 @@ def remove_punctuation_and_length(text):
def check_model_key(modelType, modelKey):
if "你" in modelKey:
- raise ValueError(
- "你还没配置" + modelType + "的密钥,请检查一下所使用的LLM是否配置了密钥"
- )
- return True
+ return f"配置错误: {modelType} 的 API key 未设置,当前值为: {modelKey}"
+ return None
def parse_string_to_list(value, separator=";"):
@@ -244,116 +244,6 @@ def extract_json_from_string(input_string):
return None
-def initialize_modules(
- logger,
- config: Dict[str, Any],
- init_vad=False,
- init_asr=False,
- init_llm=False,
- init_tts=False,
- init_memory=False,
- init_intent=False,
-) -> Dict[str, Any]:
- """
- 初始化所有模块组件
-
- Args:
- config: 配置字典
-
- Returns:
- Dict[str, Any]: 包含所有初始化后的模块的字典
- """
- modules = {}
-
- # 初始化TTS模块
- if init_tts:
- select_tts_module = config["selected_module"]["TTS"]
- tts_type = (
- select_tts_module
- if "type" not in config["TTS"][select_tts_module]
- else config["TTS"][select_tts_module]["type"]
- )
- modules["tts"] = tts.create_instance(
- tts_type,
- config["TTS"][select_tts_module],
- str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
- )
- logger.bind(tag=TAG).info(f"初始化组件: tts成功 {select_tts_module}")
-
- # 初始化LLM模块
- if init_llm:
- select_llm_module = config["selected_module"]["LLM"]
- llm_type = (
- select_llm_module
- if "type" not in config["LLM"][select_llm_module]
- else config["LLM"][select_llm_module]["type"]
- )
- modules["llm"] = llm.create_instance(
- llm_type,
- config["LLM"][select_llm_module],
- )
- logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}")
-
- # 初始化Intent模块
- if init_intent:
- select_intent_module = config["selected_module"]["Intent"]
- intent_type = (
- select_intent_module
- if "type" not in config["Intent"][select_intent_module]
- else config["Intent"][select_intent_module]["type"]
- )
- modules["intent"] = intent.create_instance(
- intent_type,
- config["Intent"][select_intent_module],
- )
- logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}")
-
- # 初始化Memory模块
- if init_memory:
- select_memory_module = config["selected_module"]["Memory"]
- memory_type = (
- select_memory_module
- if "type" not in config["Memory"][select_memory_module]
- else config["Memory"][select_memory_module]["type"]
- )
- modules["memory"] = memory.create_instance(
- memory_type,
- config["Memory"][select_memory_module],
- config.get('summaryMemory', None),
- )
- logger.bind(tag=TAG).info(f"初始化组件: memory成功 {select_memory_module}")
-
- # 初始化VAD模块
- if init_vad:
- select_vad_module = config["selected_module"]["VAD"]
- vad_type = (
- select_vad_module
- if "type" not in config["VAD"][select_vad_module]
- else config["VAD"][select_vad_module]["type"]
- )
- modules["vad"] = vad.create_instance(
- vad_type,
- config["VAD"][select_vad_module],
- )
- logger.bind(tag=TAG).info(f"初始化组件: vad成功 {select_vad_module}")
-
- # 初始化ASR模块
- if init_asr:
- select_asr_module = config["selected_module"]["ASR"]
- asr_type = (
- select_asr_module
- if "type" not in config["ASR"][select_asr_module]
- else config["ASR"][select_asr_module]["type"]
- )
- modules["asr"] = asr.create_instance(
- asr_type,
- config["ASR"][select_asr_module],
- str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
- )
- logger.bind(tag=TAG).info(f"初始化组件: asr成功 {select_asr_module}")
- return modules
-
-
def analyze_emotion(text):
"""
分析文本情感并返回对应的emoji名称(支持中英文)
@@ -881,7 +771,28 @@ def audio_to_data(audio_file_path, is_opus=True):
# 获取原始PCM数据(16位小端)
raw_data = audio.raw_data
+ return pcm_to_data(raw_data, is_opus), duration
+
+def audio_bytes_to_data(audio_bytes, file_type, is_opus=True):
+ """
+ 直接用音频二进制数据转为opus/pcm数据,支持wav、mp3、p3
+ """
+ if file_type == "p3":
+ # 直接用p3解码
+ return p3.decode_opus_from_bytes(audio_bytes)
+ else:
+ # 其他格式用pydub
+ audio = AudioSegment.from_file(
+ BytesIO(audio_bytes), format=file_type, parameters=["-nostdin"]
+ )
+ audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
+ duration = len(audio) / 1000.0
+ raw_data = audio.raw_data
+ return pcm_to_data(raw_data, is_opus), duration
+
+
+def pcm_to_data(raw_data, is_opus=True):
# 初始化Opus编码器
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
@@ -909,7 +820,34 @@ def audio_to_data(audio_file_path, is_opus=True):
datas.append(frame_data)
- return datas, duration
+ return datas
+
+
+def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1):
+ """
+ 将opus帧列表解码为wav字节流
+ """
+ decoder = opuslib_next.Decoder(sample_rate, channels)
+ pcm_datas = []
+
+ frame_duration = 60 # ms
+ frame_size = int(sample_rate * frame_duration / 1000) # 960
+
+ for opus_frame in opus_datas:
+ # 解码为PCM(返回bytes,2字节/采样点)
+ pcm = decoder.decode(opus_frame, frame_size)
+ pcm_datas.append(pcm)
+
+ pcm_bytes = b"".join(pcm_datas)
+
+ # 写入wav字节流
+ wav_buffer = BytesIO()
+ with wave.open(wav_buffer, "wb") as wf:
+ wf.setnchannels(channels)
+ wf.setsampwidth(2) # 16bit
+ wf.setframerate(sample_rate)
+ wf.writeframes(pcm_bytes)
+ return wav_buffer.getvalue()
def check_vad_update(before_config, new_config):
@@ -956,3 +894,90 @@ def check_asr_update(before_config, new_config):
)
update_asr = current_asr_type != new_asr_type
return update_asr
+
+
+def filter_sensitive_info(config: dict) -> dict:
+ """
+ 过滤配置中的敏感信息
+ Args:
+ config: 原始配置字典
+ Returns:
+ 过滤后的配置字典
+ """
+ sensitive_keys = [
+ "api_key",
+ "personal_access_token",
+ "access_token",
+ "token",
+ "secret",
+ "access_key_secret",
+ "secret_key",
+ ]
+
+ def _filter_dict(d: dict) -> dict:
+ filtered = {}
+ for k, v in d.items():
+ if any(sensitive in k.lower() for sensitive in sensitive_keys):
+ filtered[k] = "***"
+ elif isinstance(v, dict):
+ filtered[k] = _filter_dict(v)
+ elif isinstance(v, list):
+ filtered[k] = [_filter_dict(i) if isinstance(i, dict) else i for i in v]
+ else:
+ filtered[k] = v
+ return filtered
+
+ return _filter_dict(copy.deepcopy(config))
+
+
+def get_vision_url(config: dict) -> str:
+ """获取 vision URL
+
+ Args:
+ config: 配置字典
+
+ Returns:
+ str: vision URL
+ """
+ server_config = config["server"]
+ vision_explain = server_config.get("vision_explain", "")
+ if "你的" in vision_explain:
+ local_ip = get_local_ip()
+ port = int(server_config.get("http_port", 8003))
+ vision_explain = f"http://{local_ip}:{port}/mcp/vision/explain"
+ return vision_explain
+
+
+def is_valid_image_file(file_data: bytes) -> bool:
+ """
+ 检查文件数据是否为有效的图片格式
+
+ Args:
+ file_data: 文件的二进制数据
+
+ Returns:
+ bool: 如果是有效的图片格式返回True,否则返回False
+ """
+ # 常见图片格式的魔数(文件头)
+ image_signatures = {
+ b"\xff\xd8\xff": "JPEG",
+ b"\x89PNG\r\n\x1a\n": "PNG",
+ b"GIF87a": "GIF",
+ b"GIF89a": "GIF",
+ b"BM": "BMP",
+ b"II*\x00": "TIFF",
+ b"MM\x00*": "TIFF",
+ b"RIFF": "WEBP",
+ }
+
+ # 检查文件头是否匹配任何已知的图片格式
+ for signature in image_signatures:
+ if file_data.startswith(signature):
+ return True
+
+ return False
+
+
+def sanitize_tool_name(name: str) -> str:
+ """Sanitize tool names for OpenAI compatibility."""
+ return re.sub(r"[^a-zA-Z0-9_-]", "_", name)
diff --git a/main/xiaozhi-server/core/utils/vllm.py b/main/xiaozhi-server/core/utils/vllm.py
new file mode 100644
index 000000000..465580f76
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/vllm.py
@@ -0,0 +1,23 @@
+import os
+import sys
+
+# 添加项目根目录到Python路径
+current_dir = os.path.dirname(os.path.abspath(__file__))
+project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
+sys.path.insert(0, project_root)
+
+from config.logger import setup_logging
+import importlib
+
+logger = setup_logging()
+
+
+def create_instance(class_name, *args, **kwargs):
+ # 创建LLM实例
+ if os.path.exists(os.path.join("core", "providers", "vllm", f"{class_name}.py")):
+ lib_name = f"core.providers.vllm.{class_name}"
+ if lib_name not in sys.modules:
+ sys.modules[lib_name] = importlib.import_module(f"{lib_name}")
+ return sys.modules[lib_name].VLLMProvider(*args, **kwargs)
+
+ raise ValueError(f"不支持的VLLM类型: {class_name},请检查该配置的type是否设置正确")
diff --git a/main/xiaozhi-server/core/utils/wakeup_word.py b/main/xiaozhi-server/core/utils/wakeup_word.py
new file mode 100644
index 000000000..ab58f290b
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/wakeup_word.py
@@ -0,0 +1,140 @@
+import os
+import re
+import yaml
+import time
+import hashlib
+import portalocker
+from typing import Dict
+
+
+class FileLock:
+ def __init__(self, file, timeout=5):
+ self.file = file
+ self.timeout = timeout
+ self.start_time = None
+
+ def __enter__(self):
+ self.start_time = time.time()
+ while True:
+ try:
+ portalocker.lock(self.file, portalocker.LOCK_EX | portalocker.LOCK_NB)
+ return self.file
+ except portalocker.LockException:
+ if time.time() - self.start_time > self.timeout:
+ raise TimeoutError("获取文件锁超时")
+ time.sleep(0.1)
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ portalocker.unlock(self.file)
+
+
+class WakeupWordsConfig:
+ def __init__(self):
+ self.config_file = "data/.wakeup_words.yaml"
+ self.assets_dir = "config/assets/wakeup_words"
+ self._ensure_directories()
+ self._config_cache = None
+ self._last_load_time = 0
+ self._cache_ttl = 1 # 缓存有效期(秒)
+ self._lock_timeout = 5 # 文件锁超时时间(秒)
+
+ def _ensure_directories(self):
+ """确保必要的目录存在"""
+ os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
+ os.makedirs(self.assets_dir, exist_ok=True)
+
+ def _load_config(self) -> Dict:
+ """加载配置文件,使用缓存机制"""
+ current_time = time.time()
+
+ # 如果缓存有效,直接返回缓存
+ if (
+ self._config_cache is not None
+ and current_time - self._last_load_time < self._cache_ttl
+ ):
+ return self._config_cache
+
+ try:
+ with open(self.config_file, "a+") as f:
+ with FileLock(f, timeout=self._lock_timeout):
+ f.seek(0)
+ content = f.read()
+ config = yaml.safe_load(content) if content else {}
+ self._config_cache = config
+ self._last_load_time = current_time
+ return config
+ except (TimeoutError, IOError) as e:
+ print(f"加载配置文件失败: {e}")
+ return {}
+ except Exception as e:
+ print(f"加载配置文件时发生未知错误: {e}")
+ return {}
+
+ def _save_config(self, config: Dict):
+ """保存配置到文件,使用文件锁保护"""
+ try:
+ with open(self.config_file, "w") as f:
+ with FileLock(f, timeout=self._lock_timeout):
+ yaml.dump(config, f, allow_unicode=True)
+ self._config_cache = config
+ self._last_load_time = time.time()
+ except (TimeoutError, IOError) as e:
+ print(f"保存配置文件失败: {e}")
+ raise
+ except Exception as e:
+ print(f"保存配置文件时发生未知错误: {e}")
+ raise
+
+ def get_wakeup_response(self, voice: str) -> Dict:
+ voice = hashlib.md5(voice.encode()).hexdigest()
+ """获取唤醒词回复配置"""
+ config = self._load_config()
+
+ if not config or voice not in config:
+ return None
+
+ # 检查文件大小
+ file_path = config[voice]["file_path"]
+ if not os.path.exists(file_path) or os.stat(file_path).st_size < (15 * 1024):
+ return None
+
+ return config[voice]
+
+ def update_wakeup_response(self, voice: str, file_path: str, text: str):
+ """更新唤醒词回复配置"""
+ try:
+ # 过滤表情符号
+ filtered_text = re.sub(r'[\U0001F600-\U0001F64F\U0001F900-\U0001F9FF]', '', text)
+
+ config = self._load_config()
+ voice_hash = hashlib.md5(voice.encode()).hexdigest()
+ config[voice_hash] = {
+ "voice": voice,
+ "file_path": file_path,
+ "time": time.time(),
+ "text": filtered_text,
+ }
+ self._save_config(config)
+ except Exception as e:
+ print(f"更新唤醒词回复配置失败: {e}")
+ raise
+
+ def generate_file_path(self, voice: str) -> str:
+ """生成音频文件路径,使用voice的哈希值作为文件名"""
+ try:
+ # 生成voice的哈希值
+ voice_hash = hashlib.md5(voice.encode()).hexdigest()
+ file_path = os.path.join(self.assets_dir, f"{voice_hash}.wav")
+
+ # 如果文件已存在,先删除
+ if os.path.exists(file_path):
+ try:
+ os.remove(file_path)
+ except Exception as e:
+ print(f"删除已存在的音频文件失败: {e}")
+ raise
+
+ return file_path
+ except Exception as e:
+ print(f"生成音频文件路径失败: {e}")
+ raise
diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py
index 441fd4e11..1a1ba4c04 100644
--- a/main/xiaozhi-server/core/websocket_server.py
+++ b/main/xiaozhi-server/core/websocket_server.py
@@ -2,8 +2,9 @@ import asyncio
import websockets
from config.logger import setup_logging
from core.connection import ConnectionHandler
-from core.utils.util import initialize_modules, check_vad_update, check_asr_update
from config.config_loader import get_config_from_api
+from core.utils.modules_initialize import initialize_modules
+from core.utils.util import check_vad_update, check_asr_update
TAG = __name__
@@ -19,16 +20,16 @@ class WebSocketServer:
"VAD" in self.config["selected_module"],
"ASR" in self.config["selected_module"],
"LLM" in self.config["selected_module"],
- "TTS" in self.config["selected_module"],
+ False,
"Memory" in self.config["selected_module"],
"Intent" in self.config["selected_module"],
)
self._vad = modules["vad"] if "vad" in modules else None
self._asr = modules["asr"] if "asr" in modules else None
- self._tts = modules["tts"] if "tts" in modules else None
self._llm = modules["llm"] if "llm" in modules else None
self._intent = modules["intent"] if "intent" in modules else None
self._memory = modules["memory"] if "memory" in modules else None
+
self.active_connections = set()
async def start(self):
@@ -49,7 +50,6 @@ class WebSocketServer:
self._vad,
self._asr,
self._llm,
- self._tts,
self._memory,
self._intent,
self, # 传入server实例
@@ -82,11 +82,13 @@ class WebSocketServer:
if new_config is None:
self.logger.bind(tag=TAG).error("获取新配置失败")
return False
-
+ self.logger.bind(tag=TAG).info(f"获取新配置成功")
# 检查 VAD 和 ASR 类型是否需要更新
update_vad = check_vad_update(self.config, new_config)
update_asr = check_asr_update(self.config, new_config)
-
+ self.logger.bind(tag=TAG).info(
+ f"检查VAD和ASR类型是否需要更新: {update_vad} {update_asr}"
+ )
# 更新配置
self.config = new_config
# 重新初始化组件
@@ -96,7 +98,7 @@ class WebSocketServer:
update_vad,
update_asr,
"LLM" in new_config["selected_module"],
- "TTS" in new_config["selected_module"],
+ False,
"Memory" in new_config["selected_module"],
"Intent" in new_config["selected_module"],
)
@@ -106,15 +108,13 @@ class WebSocketServer:
self._vad = modules["vad"]
if "asr" in modules:
self._asr = modules["asr"]
- if "tts" in modules:
- self._tts = modules["tts"]
if "llm" in modules:
self._llm = modules["llm"]
if "intent" in modules:
self._intent = modules["intent"]
if "memory" in modules:
self._memory = modules["memory"]
-
+ self.logger.bind(tag=TAG).info(f"更新配置任务执行完毕")
return True
except Exception as e:
self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}")
diff --git a/main/xiaozhi-server/docker-compose.yml b/main/xiaozhi-server/docker-compose.yml
index f66f9eeaa..089a04a58 100644
--- a/main/xiaozhi-server/docker-compose.yml
+++ b/main/xiaozhi-server/docker-compose.yml
@@ -13,8 +13,8 @@ services:
ports:
# ws服务端
- "8000:8000"
- # ota服务端
- - "8002:8002"
+ # http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口
+ - "8003:8003"
volumes:
# 配置文件目录
- ./data:/opt/xiaozhi-esp32-server/data
diff --git a/main/xiaozhi-server/docker-compose_all.yml b/main/xiaozhi-server/docker-compose_all.yml
index 9339329e6..4707a449c 100644
--- a/main/xiaozhi-server/docker-compose_all.yml
+++ b/main/xiaozhi-server/docker-compose_all.yml
@@ -15,6 +15,8 @@ services:
ports:
# ws服务端
- "8000:8000"
+ # http服务的端口,用于视觉分析接口
+ - "8003:8003"
security_opt:
- seccomp:unconfined
environment:
@@ -50,7 +52,7 @@ services:
volumes:
# 配置文件目录
- ./uploadfile:/uploadfile
-
+ # 数据库模块
xiaozhi-esp32-server-db:
image: mysql:latest
container_name: xiaozhi-esp32-server-db
@@ -71,6 +73,7 @@ services:
- MYSQL_ROOT_PASSWORD=123456
- MYSQL_DATABASE=xiaozhi_esp32_server
- MYSQL_INITDB_ARGS="--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci"
+ # redis模块
xiaozhi-esp32-server-redis:
image: redis
expose:
diff --git a/main/xiaozhi-server/performance_tester.py b/main/xiaozhi-server/performance_tester.py
index 38daea009..a5fc52219 100644
--- a/main/xiaozhi-server/performance_tester.py
+++ b/main/xiaozhi-server/performance_tester.py
@@ -1,15 +1,17 @@
-import time
-import aiohttp
import asyncio
+import logging
+import os
+import statistics
+import time
+from typing import Dict
+
+import aiohttp
from tabulate import tabulate
-from typing import Dict, List
+
+from config.settings import load_config
+from core.utils.asr import create_instance as create_stt_instance
from core.utils.llm import create_instance as create_llm_instance
from core.utils.tts import create_instance as create_tts_instance
-import statistics
-from config.settings import load_config
-import inspect
-import os
-import logging
# 设置全局日志级别为WARNING,抑制INFO级别日志
logging.basicConfig(level=logging.WARNING)
@@ -26,7 +28,17 @@ class AsyncPerformanceTester:
"请用100字概括量子计算的基本原理和应用前景",
],
)
- self.results = {"llm": {}, "tts": {}, "combinations": []}
+
+ self.test_wav_list = []
+ self.wav_root = r"config/assets"
+ for file_name in os.listdir(self.wav_root):
+ file_path = os.path.join(self.wav_root, file_name)
+ # 检查文件大小是否大于300KB
+ if os.path.getsize(file_path) > 300 * 1024: # 300KB = 300 * 1024 bytes
+ with open(file_path, "rb") as f:
+ self.test_wav_list.append(f.read())
+
+ self.results = {"llm": {}, "tts": {}, "stt": {}, "combinations": []}
async def _check_ollama_service(self, base_url: str, model_name: str) -> bool:
"""异步检查Ollama服务状态"""
@@ -109,6 +121,59 @@ class AsyncPerformanceTester:
print(f"⚠️ {tts_name} 测试失败: {str(e)}")
return {"name": tts_name, "type": "tts", "errors": 1}
+ async def _test_stt(self, stt_name: str, config: Dict) -> Dict:
+ """异步测试单个STT性能"""
+ try:
+ logging.getLogger("core.providers.asr.base").setLevel(logging.WARNING)
+ token_fields = ["access_token", "api_key", "token"]
+ if any(
+ field in config
+ and any(x in config[field] for x in ["你的", "placeholder"])
+ for field in token_fields
+ ):
+ print(f"⏭️ STT {stt_name} 未配置access_token/api_key,已跳过")
+ return {"name": stt_name, "type": "stt", "errors": 1}
+
+ module_type = config.get("type", stt_name)
+ stt = create_stt_instance(module_type, config, delete_audio_file=True)
+ stt.audio_format = "pcm"
+
+ print(f"🎵 测试 STT: {stt_name}")
+
+ text, _ = await stt.speech_to_text(
+ [self.test_wav_list[0]], "1", stt.audio_format
+ )
+
+ if text is None:
+ print(f"❌ {stt_name} 连接失败")
+ return {"name": stt_name, "type": "stt", "errors": 1}
+
+ total_time = 0
+ test_count = len(self.test_wav_list)
+
+ for i, sentence in enumerate(self.test_wav_list, 1):
+ start = time.time()
+ text, _ = await stt.speech_to_text([sentence], "1", stt.audio_format)
+ duration = time.time() - start
+ total_time += duration
+
+ if text:
+ print(f"✓ {stt_name} [{i}/{test_count}]")
+ else:
+ print(f"✗ {stt_name} [{i}/{test_count}]")
+ return {"name": stt_name, "type": "stt", "errors": 1}
+
+ return {
+ "name": stt_name,
+ "type": "stt",
+ "avg_time": total_time / test_count,
+ "errors": 0,
+ }
+
+ except Exception as e:
+ print(f"⚠️ {stt_name} 测试失败: {str(e)}")
+ return {"name": stt_name, "type": "stt", "errors": 1}
+
async def _test_llm(self, llm_name: str, config: Dict) -> Dict:
"""异步测试单个LLM性能"""
try:
@@ -234,6 +299,7 @@ class AsyncPerformanceTester:
if v["errors"] == 0 and v["avg_first_token"] >= 0.05
]
valid_tts = [k for k, v in self.results["tts"].items() if v["errors"] == 0]
+ valid_stt = [k for k, v in self.results["stt"].items() if v["errors"] == 0]
# 找出基准值
min_first_token = (
@@ -246,42 +312,53 @@ class AsyncPerformanceTester:
if valid_tts
else 1
)
+ min_stt_time = (
+ min([self.results["stt"][stt]["avg_time"] for stt in valid_stt])
+ if valid_stt
+ else 1
+ )
for llm in valid_llms:
for tts in valid_tts:
- # 计算相对性能分数(越小越好)
- llm_score = (
- self.results["llm"][llm]["avg_first_token"] / min_first_token
- )
- tts_score = self.results["tts"][tts]["avg_time"] / min_tts_time
+ for stt in valid_stt:
+ # 计算相对性能分数(越小越好)
+ llm_score = (
+ self.results["llm"][llm]["avg_first_token"] / min_first_token
+ )
+ tts_score = self.results["tts"][tts]["avg_time"] / min_tts_time
+ stt_score = self.results["stt"][stt]["avg_time"] / min_stt_time
- # 计算稳定性分数(标准差/平均值,越小越稳定)
- llm_stability = (
- self.results["llm"][llm]["std_first_token"]
- / self.results["llm"][llm]["avg_first_token"]
- )
+ # 计算稳定性分数(标准差/平均值,越小越稳定)
+ llm_stability = (
+ self.results["llm"][llm]["std_first_token"]
+ / self.results["llm"][llm]["avg_first_token"]
+ )
- # 综合得分(考虑性能和稳定性)
- # 性能权重0.7,稳定性权重0.3
- llm_final_score = llm_score * 0.7 + llm_stability * 0.3
+ # 综合得分(考虑性能和稳定性)
+ # LLM得分: 性能权重(70%) + 稳定性权重(30%)
+ llm_final_score = llm_score * 0.7 + llm_stability * 0.3
- # 总分 = LLM得分(70%) + TTS得分(30%)
- total_score = llm_final_score * 0.7 + tts_score * 0.3
+ # 总分 = LLM得分(70%) + TTS得分(30%) + STT得分(30%)
+ total_score = (
+ llm_final_score * 0.7 + tts_score * 0.3 + stt_score * 0.3
+ )
- self.results["combinations"].append(
- {
- "llm": llm,
- "tts": tts,
- "score": total_score,
- "details": {
- "llm_first_token": self.results["llm"][llm][
- "avg_first_token"
- ],
- "llm_stability": llm_stability,
- "tts_time": self.results["tts"][tts]["avg_time"],
- },
- }
- )
+ self.results["combinations"].append(
+ {
+ "llm": llm,
+ "tts": tts,
+ "stt": stt,
+ "score": total_score,
+ "details": {
+ "llm_first_token": self.results["llm"][llm][
+ "avg_first_token"
+ ],
+ "llm_stability": llm_stability,
+ "tts_time": self.results["tts"][tts]["avg_time"],
+ "stt_time": self.results["stt"][stt]["avg_time"],
+ },
+ }
+ )
# 分数越小越好
self.results["combinations"].sort(key=lambda x: x["score"])
@@ -302,7 +379,7 @@ class AsyncPerformanceTester:
)
if llm_table:
- print("\nLLM 性能排行:")
+ print("\nLLM 性能排行:\n")
print(
tabulate(
llm_table,
@@ -321,7 +398,7 @@ class AsyncPerformanceTester:
tts_table.append([name, f"{data['avg_time']:.3f}秒"]) # 不需要固定宽度
if tts_table:
- print("\nTTS 性能排行:")
+ print("\nTTS 性能排行:\n")
print(
tabulate(
tts_table,
@@ -334,17 +411,37 @@ class AsyncPerformanceTester:
else:
print("\n⚠️ 没有可用的TTS模块进行测试。")
+ stt_table = []
+ for name, data in self.results["stt"].items():
+ if data["errors"] == 0:
+ stt_table.append([name, f"{data['avg_time']:.3f}秒"]) # 不需要固定宽度
+
+ if stt_table:
+ print("\nSTT 性能排行:\n")
+ print(
+ tabulate(
+ stt_table,
+ headers=["模型名称", "合成耗时"],
+ tablefmt="github",
+ colalign=("left", "right"),
+ disable_numparse=True,
+ )
+ )
+ else:
+ print("\n⚠️ 没有可用的STT模块进行测试。")
+
if self.results["combinations"]:
- print("\n推荐配置组合 (得分越小越好):")
+ print("\n推荐配置组合 (得分越小越好):\n")
combo_table = []
- for combo in self.results["combinations"][:5]:
+ for combo in self.results["combinations"][:]:
combo_table.append(
[
- f"{combo['llm']} + {combo['tts']}", # 不需要固定宽度
+ f"{combo['llm']} + {combo['tts']} + {combo['stt']}", # 不需要固定宽度
f"{combo['score']:.3f}",
f"{combo['details']['llm_first_token']:.3f}秒",
f"{combo['details']['llm_stability']:.3f}",
f"{combo['details']['tts_time']:.3f}秒",
+ f"{combo['details']['stt_time']:.3f}秒",
]
)
@@ -357,9 +454,10 @@ class AsyncPerformanceTester:
"LLM首字耗时",
"稳定性",
"TTS合成耗时",
+ "STT合成耗时",
],
tablefmt="github",
- colalign=("left", "right", "right", "right", "right"),
+ colalign=("left", "right", "right", "right", "right", "right"),
disable_numparse=True,
)
)
@@ -372,8 +470,12 @@ class AsyncPerformanceTester:
if result["errors"] == 0:
if result["type"] == "llm":
self.results["llm"][result["name"]] = result
- else:
+ elif result["type"] == "tts":
self.results["tts"][result["name"]] = result
+ elif result["type"] == "stt":
+ self.results["stt"][result["name"]] = result
+ else:
+ pass
async def run(self):
"""执行全量异步测试"""
@@ -383,52 +485,73 @@ class AsyncPerformanceTester:
all_tasks = []
# LLM测试任务
- for llm_name, config in self.config.get("LLM", {}).items():
- # 检查配置有效性
- if llm_name == "CozeLLM":
- if any(x in config.get("bot_id", "") for x in ["你的"]) or any(
- x in config.get("user_id", "") for x in ["你的"]
+ if self.config.get("LLM") is not None:
+ for llm_name, config in self.config.get("LLM", {}).items():
+ # 检查配置有效性
+ if llm_name == "CozeLLM":
+ if any(x in config.get("bot_id", "") for x in ["你的"]) or any(
+ x in config.get("user_id", "") for x in ["你的"]
+ ):
+ print(f"⏭️ LLM {llm_name} 未配置bot_id/user_id,已跳过")
+ continue
+ elif "api_key" in config and any(
+ x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
):
- print(f"⏭️ LLM {llm_name} 未配置bot_id/user_id,已跳过")
- continue
- elif "api_key" in config and any(
- x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
- ):
- print(f"⏭️ LLM {llm_name} 未配置api_key,已跳过")
- continue
-
- # 对于Ollama,先检查服务状态
- if llm_name == "Ollama":
- base_url = config.get("base_url", "http://localhost:11434")
- model_name = config.get("model_name")
- if not model_name:
- print(f"🚫 Ollama未配置model_name")
+ print(f"⏭️ LLM {llm_name} 未配置api_key,已跳过")
continue
- if not await self._check_ollama_service(base_url, model_name):
- continue
+ # 对于Ollama,先检查服务状态
+ if llm_name == "Ollama":
+ base_url = config.get("base_url", "http://localhost:11434")
+ model_name = config.get("model_name")
+ if not model_name:
+ print(f"🚫 Ollama未配置model_name")
+ continue
- print(f"📋 添加LLM测试任务: {llm_name}")
- module_type = config.get("type", llm_name)
- llm = create_llm_instance(module_type, config)
+ if not await self._check_ollama_service(base_url, model_name):
+ continue
- # 为每个句子创建独立任务
- for sentence in self.test_sentences:
- sentence = sentence.encode("utf-8").decode("utf-8")
- all_tasks.append(self._test_single_sentence(llm_name, llm, sentence))
+ print(f"📋 添加LLM测试任务: {llm_name}")
+ module_type = config.get("type", llm_name)
+ llm = create_llm_instance(module_type, config)
+
+ # 为每个句子创建独立任务
+ for sentence in self.test_sentences:
+ sentence = sentence.encode("utf-8").decode("utf-8")
+ all_tasks.append(
+ self._test_single_sentence(llm_name, llm, sentence)
+ )
# TTS测试任务
- for tts_name, config in self.config.get("TTS", {}).items():
- token_fields = ["access_token", "api_key", "token"]
- if any(
- field in config
- and any(x in config[field] for x in ["你的", "placeholder"])
- for field in token_fields
- ):
- print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过")
- continue
- print(f"🎵 添加TTS测试任务: {tts_name}")
- all_tasks.append(self._test_tts(tts_name, config))
+ if self.config.get("TTS") is not None:
+ for tts_name, config in self.config.get("TTS", {}).items():
+ token_fields = ["access_token", "api_key", "token"]
+ if any(
+ field in config
+ and any(x in config[field] for x in ["你的", "placeholder"])
+ for field in token_fields
+ ):
+ print(f"⏭️ TTS {tts_name} 未配置access_token/api_key,已跳过")
+ continue
+ print(f"🎵 添加TTS测试任务: {tts_name}")
+ all_tasks.append(self._test_tts(tts_name, config))
+
+ # STT测试任务
+ if len(self.test_wav_list) >= 1:
+ if self.config.get("ASR") is not None:
+ for stt_name, config in self.config.get("ASR", {}).items():
+ token_fields = ["access_token", "api_key", "token"]
+ if any(
+ field in config
+ and any(x in config[field] for x in ["你的", "placeholder"])
+ for field in token_fields
+ ):
+ print(f"⏭️ ASR {stt_name} 未配置access_token/api_key,已跳过")
+ continue
+ print(f"🎵 添加ASR测试任务: {stt_name}")
+ all_tasks.append(self._test_stt(stt_name, config))
+ else:
+ print(f"\n⚠️ {self.wav_root} 路径下没有音频文件,已跳过STT测试任务")
print(
f"\n✅ 找到 {len([t for t in all_tasks if 'test_single_sentence' in str(t)]) / len(self.test_sentences):.0f} 个可用LLM模块"
@@ -436,6 +559,9 @@ class AsyncPerformanceTester:
print(
f"✅ 找到 {len([t for t in all_tasks if '_test_tts' in str(t)])} 个可用TTS模块"
)
+ print(
+ f"✅ 找到 {len([t for t in all_tasks if '_test_stt' in str(t)])} 个可用STT模块"
+ )
print("\n⏳ 开始并发测试所有模块...\n")
# 并发执行所有测试任务
@@ -494,6 +620,15 @@ class AsyncPerformanceTester:
if result["errors"] == 0:
self.results["tts"][result["name"]] = result
+ # 处理STT结果
+ for result in [
+ r
+ for r in all_results
+ if r and isinstance(r, dict) and r.get("type") == "stt"
+ ]:
+ if result["errors"] == 0:
+ self.results["stt"][result["name"]] = result
+
# 生成组合建议并打印结果
print("\n📊 生成测试报告...")
self._generate_combinations()
diff --git a/main/xiaozhi-server/performance_tester_vllm.py b/main/xiaozhi-server/performance_tester_vllm.py
new file mode 100644
index 000000000..4dafddcc1
--- /dev/null
+++ b/main/xiaozhi-server/performance_tester_vllm.py
@@ -0,0 +1,189 @@
+import time
+import asyncio
+import logging
+import statistics
+import base64
+from typing import Dict
+from tabulate import tabulate
+from config.settings import load_config
+from core.utils.vllm import create_instance
+
+# 设置全局日志级别为WARNING,抑制INFO级别日志
+logging.basicConfig(level=logging.WARNING)
+
+
+class AsyncVisionPerformanceTester:
+ def __init__(self):
+ self.config = load_config()
+ self.test_images = [
+ "../../docs/images/demo1.png",
+ "../../docs/images/demo2.png",
+ ]
+ self.test_questions = [
+ "这张图片里有什么?",
+ "请详细描述这张图片的内容",
+ ]
+
+ # 加载测试图片
+ self.results = {"vllm": {}}
+
+ async def _test_vllm(self, vllm_name: str, config: Dict) -> Dict:
+ """异步测试单个视觉大模型性能"""
+ try:
+ # 检查API密钥配置
+ if "api_key" in config and any(
+ x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
+ ):
+ print(f"⏭️ VLLM {vllm_name} 未配置api_key,已跳过")
+ return {"name": vllm_name, "type": "vllm", "errors": 1}
+
+ # 获取实际类型(兼容旧配置)
+ module_type = config.get("type", vllm_name)
+ vllm = create_instance(module_type, config)
+
+ print(f"🖼️ 测试 VLLM: {vllm_name}")
+
+ # 创建所有测试任务
+ test_tasks = []
+ for question in self.test_questions:
+ for image in self.test_images:
+ test_tasks.append(
+ self._test_single_vision(vllm_name, vllm, question, image)
+ )
+
+ # 并发执行所有测试
+ test_results = await asyncio.gather(*test_tasks)
+
+ # 处理结果
+ valid_results = [r for r in test_results if r is not None]
+ if not valid_results:
+ print(f"⚠️ {vllm_name} 无有效数据,可能配置错误")
+ return {"name": vllm_name, "type": "vllm", "errors": 1}
+
+ response_times = [r["response_time"] for r in valid_results]
+
+ # 过滤异常数据
+ mean = statistics.mean(response_times)
+ stdev = statistics.stdev(response_times) if len(response_times) > 1 else 0
+ filtered_times = [t for t in response_times if t <= mean + 3 * stdev]
+
+ if len(filtered_times) < len(test_tasks) * 0.5:
+ print(f"⚠️ {vllm_name} 有效数据不足,可能网络不稳定")
+ return {"name": vllm_name, "type": "vllm", "errors": 1}
+
+ return {
+ "name": vllm_name,
+ "type": "vllm",
+ "avg_response": sum(response_times) / len(response_times),
+ "std_response": (
+ statistics.stdev(response_times) if len(response_times) > 1 else 0
+ ),
+ "errors": 0,
+ }
+
+ except Exception as e:
+ print(f"⚠️ VLLM {vllm_name} 测试失败: {str(e)}")
+ return {"name": vllm_name, "type": "vllm", "errors": 1}
+
+ async def _test_single_vision(
+ self, vllm_name: str, vllm, question: str, image: str
+ ) -> Dict:
+ """测试单个视觉问题的性能"""
+ try:
+ print(f"📝 {vllm_name} 开始测试: {question[:20]}...")
+ start_time = time.time()
+
+ # 读取图片并转换为base64
+ with open(image, "rb") as image_file:
+ image_data = image_file.read()
+ image_base64 = base64.b64encode(image_data).decode("utf-8")
+
+ # 直接获取响应
+ response = vllm.response(question, image_base64)
+ response_time = time.time() - start_time
+ print(f"✓ {vllm_name} 完成响应: {response_time:.3f}s")
+
+ return {
+ "name": vllm_name,
+ "type": "vllm",
+ "response_time": response_time,
+ }
+ except Exception as e:
+ print(f"⚠️ {vllm_name} 测试失败: {str(e)}")
+ return None
+
+ def _print_results(self):
+ """打印测试结果"""
+ vllm_table = []
+ for name, data in self.results["vllm"].items():
+ if data["errors"] == 0:
+ stability = data["std_response"] / data["avg_response"]
+ vllm_table.append(
+ [
+ name,
+ f"{data['avg_response']:.3f}秒",
+ f"{stability:.3f}",
+ ]
+ )
+
+ if vllm_table:
+ print("\n视觉大模型性能排行:\n")
+ print(
+ tabulate(
+ vllm_table,
+ headers=["模型名称", "响应耗时", "稳定性"],
+ tablefmt="github",
+ colalign=("left", "right", "right"),
+ disable_numparse=True,
+ )
+ )
+ else:
+ print("\n⚠️ 没有可用的视觉大模型进行测试。")
+
+ async def run(self):
+ """执行全量异步测试"""
+ print("🔍 开始筛选可用视觉大模型...")
+
+ if not self.test_images:
+ print(f"\n⚠️ {self.image_root} 路径下没有图片文件,无法进行测试")
+ return
+
+ # 创建所有测试任务
+ all_tasks = []
+
+ # VLLM测试任务
+ if self.config.get("VLLM") is not None:
+ for vllm_name, config in self.config.get("VLLM", {}).items():
+ if "api_key" in config and any(
+ x in config["api_key"] for x in ["你的", "placeholder", "sk-xxx"]
+ ):
+ print(f"⏭️ VLLM {vllm_name} 未配置api_key,已跳过")
+ continue
+ print(f"🖼️ 添加VLLM测试任务: {vllm_name}")
+ all_tasks.append(self._test_vllm(vllm_name, config))
+
+ print(f"\n✅ 找到 {len(all_tasks)} 个可用视觉大模型")
+ print(f"✅ 使用 {len(self.test_images)} 张测试图片")
+ print(f"✅ 使用 {len(self.test_questions)} 个测试问题")
+ print("\n⏳ 开始并发测试所有模型...\n")
+
+ # 并发执行所有测试任务
+ all_results = await asyncio.gather(*all_tasks, return_exceptions=True)
+
+ # 处理结果
+ for result in all_results:
+ if isinstance(result, dict) and result["errors"] == 0:
+ self.results["vllm"][result["name"]] = result
+
+ # 打印结果
+ print("\n📊 生成测试报告...")
+ self._print_results()
+
+
+async def main():
+ tester = AsyncVisionPerformanceTester()
+ await tester.run()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py b/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py
index 64d499b16..e5ca0d1f8 100644
--- a/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py
+++ b/main/xiaozhi-server/plugins_func/functions/get_news_from_chinanews.py
@@ -120,16 +120,16 @@ def map_category(category_text):
# 类别映射字典,目前支持社会、国际、财经新闻,如需更多类型,参见配置文件
category_map = {
# 社会新闻
- "社会": "society",
- "社会新闻": "society",
+ "社会": "society_rss_url",
+ "社会新闻": "society_rss_url",
# 国际新闻
- "国际": "world",
- "国际新闻": "world",
+ "国际": "world_rss_url",
+ "国际新闻": "world_rss_url",
# 财经新闻
- "财经": "finance",
- "财经新闻": "finance",
- "金融": "finance",
- "经济": "finance",
+ "财经": "finance_rss_url",
+ "财经新闻": "finance_rss_url",
+ "金融": "finance_rss_url",
+ "经济": "finance_rss_url",
}
# 转换为小写并去除空格
@@ -205,8 +205,8 @@ def get_news_from_chinanews(
# 如果提供了类别,尝试从配置中获取对应的URL
rss_url = default_rss_url
- if mapped_category and mapped_category in rss_config.get("category_urls", {}):
- rss_url = rss_config["category_urls"][mapped_category]
+ if mapped_category and mapped_category in rss_config:
+ rss_url = rss_config[mapped_category]
logger.bind(tag=TAG).info(
f"获取新闻: 原始类别={category}, 映射类别={mapped_category}, URL={rss_url}"
diff --git a/main/xiaozhi-server/plugins_func/functions/handle_device.py b/main/xiaozhi-server/plugins_func/functions/handle_device.py
deleted file mode 100644
index 70902c55f..000000000
--- a/main/xiaozhi-server/plugins_func/functions/handle_device.py
+++ /dev/null
@@ -1,111 +0,0 @@
-from config.logger import setup_logging
-from plugins_func.register import register_function, ToolType, ActionResponse, Action
-from core.handle.iotHandle import get_iot_status, send_iot_conn
-import asyncio
-
-TAG = __name__
-logger = setup_logging()
-
-
-async def _get_device_status(conn, device_name, device_type, property_name):
- """获取设备状态"""
- status = await get_iot_status(conn, device_type, property_name)
- if status is None:
- raise Exception(f"你的设备不支持{device_name}控制")
- return status
-
-
-async def _set_device_property(conn, device_name, device_type, method_name, property_name, new_value=None, action=None, step=10):
- """设置设备属性"""
- current_value = await _get_device_status(conn, device_name, device_type, property_name)
-
- if action == 'raise':
- current_value += step
- elif action == 'lower':
- current_value -= step
- elif action == 'set':
- if new_value is None:
- raise Exception(f"缺少{property_name}参数")
- current_value = new_value
-
- # 限制属性范围在0到100之间
- current_value = max(0, min(100, current_value))
-
- await send_iot_conn(conn, device_type, method_name, {property_name: current_value})
- return current_value
-
-
-def _handle_device_action(conn, func, success_message, error_message, *args, **kwargs):
- """处理设备操作的通用函数"""
- future = asyncio.run_coroutine_threadsafe(
- func(conn, *args, **kwargs), conn.loop)
- try:
- result = future.result()
- logger.bind(tag=TAG).info(f"{success_message}: {result}")
- response = f"{success_message}{result}"
- return ActionResponse(action=Action.RESPONSE, result=result, response=response)
- except Exception as e:
- logger.bind(tag=TAG).error(f"{error_message}: {e}")
- response = f"{error_message}: {e}"
- return ActionResponse(action=Action.RESPONSE, result=None, response=response)
-
-
-# 设备控制
-handle_device_function_desc = {
- "type": "function",
- "function": {
- "name": "handle_device",
- "description": (
- "用户想要获取或者设置设备的音量/亮度大小,或者用户觉得声音/亮度过高或过低,或者用户想提高或降低音量/亮度。"
- "比如用户说现在亮度多少,参数为:device_type:Screen,action:get。"
- "比如用户说设置音量为50,参数为:device_type:Speaker,action:set,value:50。"
- "比如用户说亮度太高了,参数为:device_type:Screen,action:lower。"
- "比如用户说调大音量,参数为:device_type:Speaker,action:raise。"
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "device_type": {
- "type": "string",
- "description": "设备类型,可选值:Speaker(音量),Screen(亮度)"
- },
- "action": {
- "type": "string",
- "description": "动作名称,可选值:get(获取),set(设置),raise(提高),lower(降低)"
- },
- "value": {
- "type": "integer",
- "description": "值大小,可选值:0-100之间的整数"
- }
- },
- "required": ["device_type", "action"]
- }
- }
-}
-
-
-@register_function('handle_device', handle_device_function_desc, ToolType.IOT_CTL)
-def handle_device(conn, device_type: str, action: str, value: int = None):
- if device_type == "Speaker":
- method_name, property_name, device_name = "SetVolume", "volume", "音量"
- elif device_type == "Screen":
- method_name, property_name, device_name = "SetBrightness", "brightness", "亮度"
- else:
- raise Exception(f"未识别的设备类型: {device_type}")
-
- if action not in ["get", "set", "raise", "lower"]:
- raise Exception(f"未识别的动作名称: {action}")
-
- if action == "get":
- # get
- return _handle_device_action(
- conn, _get_device_status, f"当前{device_name}", f"获取{device_name}失败",
- device_name=device_name, device_type=device_type, property_name=property_name,
- )
- else:
- # set, raise, lower
- return _handle_device_action(
- conn, _set_device_property, f"{device_name}已调整到", f"{device_name}调整失败",
- device_name=device_name, device_type=device_type, method_name=method_name,
- property_name=property_name, new_value=value, action=action
- )
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py
index 5ce511eb2..e8167db46 100644
--- a/main/xiaozhi-server/plugins_func/functions/hass_get_state.py
+++ b/main/xiaozhi-server/plugins_func/functions/hass_get_state.py
@@ -17,57 +17,78 @@ hass_get_state_function_desc = {
"properties": {
"entity_id": {
"type": "string",
- "description": "需要操作的设备id,homeassistant里的entity_id"
+ "description": "需要操作的设备id,homeassistant里的entity_id",
}
},
- "required": ["entity_id"]
- }
- }
+ "required": ["entity_id"],
+ },
+ },
}
@register_function("hass_get_state", hass_get_state_function_desc, ToolType.SYSTEM_CTL)
-def hass_get_state(conn, entity_id=''):
+def hass_get_state(conn, entity_id=""):
try:
future = asyncio.run_coroutine_threadsafe(
- handle_hass_get_state(conn, entity_id),
- conn.loop
+ handle_hass_get_state(conn, entity_id), conn.loop
)
ha_response = future.result()
- return ActionResponse( Action.REQLLM, ha_response , None )
+ return ActionResponse(Action.REQLLM, ha_response, None)
except Exception as e:
logger.bind(tag=TAG).error(f"处理设置属性意图错误: {e}")
async def handle_hass_get_state(conn, entity_id):
- HASS_CACHE = initialize_hass_handler(conn)
- api_key = HASS_CACHE['api_key']
- base_url = HASS_CACHE['base_url']
+ ha_config = initialize_hass_handler(conn)
+ api_key = ha_config.get("api_key")
+ base_url = ha_config.get("base_url")
url = f"{base_url}/api/states/{entity_id}"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json"
- }
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
- responsetext = '设备状态:' + response.json()['state'] + ' '
+ responsetext = "设备状态:" + response.json()["state"] + " "
logger.bind(tag=TAG).info(f"api返回内容: {response.json()}")
- if 'media_title' in response.json()['attributes']:
- responsetext = responsetext+ '正在播放的是:'+str(response.json()['attributes']['media_title'])+' '
- if 'volume_level' in response.json()['attributes']:
- responsetext = responsetext+ '音量是:'+str(response.json()['attributes']['volume_level'])+' '
- if 'color_temp_kelvin' in response.json()['attributes']:
- responsetext = responsetext+ '色温是:'+str(response.json()['attributes']['color_temp_kelvin'])+' '
- if 'rgb_color' in response.json()['attributes']:
- responsetext = responsetext+ 'rgb颜色是:'+str(response.json()['attributes']['rgb_color'])+' '
- if 'brightness' in response.json()['attributes']:
- responsetext = responsetext+ '亮度是:'+str(response.json()['attributes']['brightness'])+' '
+ if "media_title" in response.json()["attributes"]:
+ responsetext = (
+ responsetext
+ + "正在播放的是:"
+ + str(response.json()["attributes"]["media_title"])
+ + " "
+ )
+ if "volume_level" in response.json()["attributes"]:
+ responsetext = (
+ responsetext
+ + "音量是:"
+ + str(response.json()["attributes"]["volume_level"])
+ + " "
+ )
+ if "color_temp_kelvin" in response.json()["attributes"]:
+ responsetext = (
+ responsetext
+ + "色温是:"
+ + str(response.json()["attributes"]["color_temp_kelvin"])
+ + " "
+ )
+ if "rgb_color" in response.json()["attributes"]:
+ responsetext = (
+ responsetext
+ + "rgb颜色是:"
+ + str(response.json()["attributes"]["rgb_color"])
+ + " "
+ )
+ if "brightness" in response.json()["attributes"]:
+ responsetext = (
+ responsetext
+ + "亮度是:"
+ + str(response.json()["attributes"]["brightness"])
+ + " "
+ )
logger.bind(tag=TAG).info(f"查询返回内容: {responsetext}")
return responsetext
- #return response.json()['attributes']
- #response.attributes
+ # return response.json()['attributes']
+ # response.attributes
else:
return f"切换失败,错误码: {response.status_code}"
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_init.py b/main/xiaozhi-server/plugins_func/functions/hass_init.py
index 3a5458d3d..11cbb7a0c 100644
--- a/main/xiaozhi-server/plugins_func/functions/hass_init.py
+++ b/main/xiaozhi-server/plugins_func/functions/hass_init.py
@@ -4,40 +4,49 @@ from core.utils.util import check_model_key
TAG = __name__
logger = setup_logging()
-HASS_CACHE = {}
-
def append_devices_to_prompt(conn):
if conn.intent_type == "function_call":
funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get(
"functions", []
)
+
+ config_source = (
+ "home_assistant"
+ if conn.config["plugins"].get("home_assistant")
+ else "hass_get_state"
+ )
+
if "hass_get_state" in funcs or "hass_set_state" in funcs:
prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
- devices = conn.config["plugins"]["home_assistant"].get("devices", [])
- if len(devices) == 0:
- return
- for device in devices:
- prompt += device + "\n"
- conn.prompt += prompt
+ deviceStr = conn.config["plugins"].get(config_source, {}).get("devices", "")
+ conn.prompt += prompt + deviceStr + "\n"
# 更新提示词
conn.dialogue.update_system_message(conn.prompt)
def initialize_hass_handler(conn):
- global HASS_CACHE
- if HASS_CACHE == {}:
- if conn.load_function_plugin:
- funcs = conn.config["Intent"][conn.config["selected_module"]["Intent"]].get(
- "functions", []
- )
- if "hass_get_state" in funcs or "hass_set_state" in funcs:
- HASS_CACHE["base_url"] = conn.config["plugins"]["home_assistant"].get(
- "base_url"
- )
- HASS_CACHE["api_key"] = conn.config["plugins"]["home_assistant"].get(
- "api_key"
- )
+ ha_config = {}
+ if not conn.load_function_plugin:
+ return ha_config
- check_model_key("home_assistant", HASS_CACHE["api_key"])
- return HASS_CACHE
+ # 确定配置来源
+ config_source = (
+ "home_assistant"
+ if conn.config["plugins"].get("home_assistant")
+ else "hass_get_state"
+ )
+ if not conn.config["plugins"].get(config_source):
+ return ha_config
+
+ # 统一获取配置
+ plugin_config = conn.config["plugins"][config_source]
+ ha_config["base_url"] = plugin_config.get("base_url")
+ ha_config["api_key"] = plugin_config.get("api_key")
+
+ # 统一检查API密钥
+ model_key_msg = check_model_key("home_assistant", ha_config.get("api_key"))
+ if model_key_msg:
+ logger.bind(tag=TAG).error(model_key_msg)
+
+ return ha_config
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_play_music.py b/main/xiaozhi-server/plugins_func/functions/hass_play_music.py
index 502f784ec..fa6527b62 100644
--- a/main/xiaozhi-server/plugins_func/functions/hass_play_music.py
+++ b/main/xiaozhi-server/plugins_func/functions/hass_play_music.py
@@ -17,46 +17,43 @@ hass_play_music_function_desc = {
"properties": {
"media_content_id": {
"type": "string",
- "description": "可以是音乐或有声书的专辑名称、歌曲名、演唱者,如果未指定就填random"
+ "description": "可以是音乐或有声书的专辑名称、歌曲名、演唱者,如果未指定就填random",
},
"entity_id": {
"type": "string",
- "description": "需要操作的音箱的设备id,homeassistant里的entity_id,media_player开头"
- }
+ "description": "需要操作的音箱的设备id,homeassistant里的entity_id,media_player开头",
+ },
},
- "required": ["media_content_id", "entity_id"]
- }
- }
+ "required": ["media_content_id", "entity_id"],
+ },
+ },
}
-@register_function('hass_play_music', hass_play_music_function_desc, ToolType.SYSTEM_CTL)
-def hass_play_music(conn, entity_id='', media_content_id='random'):
+@register_function(
+ "hass_play_music", hass_play_music_function_desc, ToolType.SYSTEM_CTL
+)
+def hass_play_music(conn, entity_id="", media_content_id="random"):
try:
# 执行音乐播放命令
future = asyncio.run_coroutine_threadsafe(
- handle_hass_play_music(conn, entity_id, media_content_id),
- conn.loop
+ handle_hass_play_music(conn, entity_id, media_content_id), conn.loop
)
ha_response = future.result()
- return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=ha_response)
+ return ActionResponse(
+ action=Action.RESPONSE, result="退出意图已处理", response=ha_response
+ )
except Exception as e:
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
async def handle_hass_play_music(conn, entity_id, media_content_id):
- HASS_CACHE = initialize_hass_handler(conn)
- api_key = HASS_CACHE['api_key']
- base_url = HASS_CACHE['base_url']
+ ha_config = initialize_hass_handler(conn)
+ api_key = ha_config.get("api_key")
+ base_url = ha_config.get("base_url")
url = f"{base_url}/api/services/music_assistant/play_media"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json"
- }
- data = {
- "entity_id": entity_id,
- "media_id": media_content_id
- }
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
+ data = {"entity_id": entity_id, "media_id": media_content_id}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return f"正在播放{media_content_id}的音乐"
diff --git a/main/xiaozhi-server/plugins_func/functions/hass_set_state.py b/main/xiaozhi-server/plugins_func/functions/hass_set_state.py
index b9de146b1..704148ee6 100644
--- a/main/xiaozhi-server/plugins_func/functions/hass_set_state.py
+++ b/main/xiaozhi-server/plugins_func/functions/hass_set_state.py
@@ -20,40 +20,40 @@ hass_set_state_function_desc = {
"properties": {
"type": {
"type": "string",
- "description": "需要操作的动作,打开设备:turn_on,关闭设备:turn_off,增加亮度:brightness_up,降低亮度:brightness_down,设置亮度:brightness_value,增加音量:volume_up,降低音量:volume_down,设置音量:volume_set,设置色温:set_kelvin,设置颜色:set_color,设备暂停:pause,设备继续:continue,静音/取消静音:volume_mute"
+ "description": "需要操作的动作,打开设备:turn_on,关闭设备:turn_off,增加亮度:brightness_up,降低亮度:brightness_down,设置亮度:brightness_value,增加音量:volume_up,降低音量:volume_down,设置音量:volume_set,设置色温:set_kelvin,设置颜色:set_color,设备暂停:pause,设备继续:continue,静音/取消静音:volume_mute",
},
"input": {
"type": "integer",
- "description": "只有在设置音量,设置亮度时候才需要,有效值为1-100,对应音量和亮度的1%-100%"
+ "description": "只有在设置音量,设置亮度时候才需要,有效值为1-100,对应音量和亮度的1%-100%",
},
"is_muted": {
"type": "string",
- "description": "只有在设置静音操作时才需要,设置静音的时候该值为true,取消静音时该值为false"
+ "description": "只有在设置静音操作时才需要,设置静音的时候该值为true,取消静音时该值为false",
+ },
+ "rgb_color": {
+ "type": "array",
+ "items": {"type": "integer"},
+ "description": "只有在设置颜色时需要,这里填目标颜色的rgb值",
},
- "rgb_color":{
- "type":"list",
- "description": "只有在设置颜色时需要,这里填目标颜色的rgb值"
- }
},
- "required": ["type"]
+ "required": ["type"],
},
"entity_id": {
"type": "string",
- "description": "需要操作的设备id,homeassistant里的entity_id"
- }
+ "description": "需要操作的设备id,homeassistant里的entity_id",
+ },
},
- "required": ["state", "entity_id"]
- }
- }
+ "required": ["state", "entity_id"],
+ },
+ },
}
-@register_function('hass_set_state', hass_set_state_function_desc, ToolType.SYSTEM_CTL)
-def hass_set_state(conn, entity_id='', state={}):
+@register_function("hass_set_state", hass_set_state_function_desc, ToolType.SYSTEM_CTL)
+def hass_set_state(conn, entity_id="", state={}):
try:
future = asyncio.run_coroutine_threadsafe(
- handle_hass_set_state(conn, entity_id, state),
- conn.loop
+ handle_hass_set_state(conn, entity_id, state), conn.loop
)
ha_response = future.result()
return ActionResponse(Action.REQLLM, ha_response, None)
@@ -62,21 +62,21 @@ def hass_set_state(conn, entity_id='', state={}):
async def handle_hass_set_state(conn, entity_id, state):
- HASS_CACHE = initialize_hass_handler(conn)
- api_key = HASS_CACHE['api_key']
- base_url = HASS_CACHE['base_url']
- '''
+ ha_config = initialize_hass_handler(conn)
+ api_key = ha_config.get("api_key")
+ base_url = ha_config.get("base_url")
+ """
state = { "type":"brightness_up","input":"80","is_muted":"true"}
- '''
+ """
domains = entity_id.split(".")
if len(domains) > 1:
domain = domains[0]
else:
return "执行失败,错误的设备id"
- action = ''
- arg = ''
- value = ''
- if state['type'] == 'turn_on':
+ action = ""
+ arg = ""
+ value = ""
+ if state["type"] == "turn_on":
description = "设备已打开"
if domain == "cover":
action = "open_cover"
@@ -84,91 +84,87 @@ async def handle_hass_set_state(conn, entity_id, state):
action = "start"
else:
action = "turn_on"
- elif state['type'] == 'turn_off':
+ elif state["type"] == "turn_off":
description = "设备已关闭"
- if domain == 'cover':
+ if domain == "cover":
action = "close_cover"
- elif domain == 'vacuum':
+ elif domain == "vacuum":
action = "stop"
else:
action = "turn_off"
- elif state['type'] == 'brightness_up':
+ elif state["type"] == "brightness_up":
description = "灯光已调亮"
- action = 'turn_on'
- arg = 'brightness_step_pct'
+ action = "turn_on"
+ arg = "brightness_step_pct"
value = 10
- elif state['type'] == 'brightness_down':
+ elif state["type"] == "brightness_down":
description = "灯光已调暗"
- action = 'turn_on'
- arg = 'brightness_step_pct'
+ action = "turn_on"
+ arg = "brightness_step_pct"
value = -10
- elif state['type'] == 'brightness_value':
+ elif state["type"] == "brightness_value":
description = f"亮度已调整到{state['input']}"
- action = 'turn_on'
- arg = 'brightness_pct'
- value = state['input']
- elif state['type'] == 'set_color':
+ action = "turn_on"
+ arg = "brightness_pct"
+ value = state["input"]
+ elif state["type"] == "set_color":
description = f"颜色已调整到{state['rgb_color']}"
- action = 'turn_on'
- arg = 'rgb_color'
- value = state['rgb_color']
- elif state['type'] == 'set_kelvin':
+ action = "turn_on"
+ arg = "rgb_color"
+ value = state["rgb_color"]
+ elif state["type"] == "set_kelvin":
description = f"色温已调整到{state['input']}K"
- action = 'turn_on'
- arg = 'kelvin'
- value = state['input']
- elif state['type'] == 'volume_up':
+ action = "turn_on"
+ arg = "kelvin"
+ value = state["input"]
+ elif state["type"] == "volume_up":
description = "音量已调大"
- action = state['type']
- elif state['type'] == 'volume_down':
+ action = state["type"]
+ elif state["type"] == "volume_down":
description = "音量已调小"
- action = state['type']
- elif state['type'] == 'volume_set':
+ action = state["type"]
+ elif state["type"] == "volume_set":
description = f"音量已调整到{state['input']}"
- action = state['type']
- arg = 'volume_level'
- value = state['input']
- if state['input'] >= 1:
- value = state['input']/100
- elif state['type'] == 'volume_mute':
+ action = state["type"]
+ arg = "volume_level"
+ value = state["input"]
+ if state["input"] >= 1:
+ value = state["input"] / 100
+ elif state["type"] == "volume_mute":
description = f"设备已静音"
- action = state['type']
- arg = 'is_volume_muted'
- value = state['is_muted']
- elif state['type'] == 'pause':
+ action = state["type"]
+ arg = "is_volume_muted"
+ value = state["is_muted"]
+ elif state["type"] == "pause":
description = f"设备已暂停"
- action = state['type']
- if domain == 'media_player':
- action = 'media_pause'
- if domain == 'cover':
- action = 'stop_cover'
- if domain == 'vacuum':
- action = 'pause'
- elif state['type'] == 'continue':
+ action = state["type"]
+ if domain == "media_player":
+ action = "media_pause"
+ if domain == "cover":
+ action = "stop_cover"
+ if domain == "vacuum":
+ action = "pause"
+ elif state["type"] == "continue":
description = f"设备已继续"
- if domain == 'media_player':
- action = 'media_play'
- if domain == 'vacuum':
- action = 'start'
+ if domain == "media_player":
+ action = "media_play"
+ if domain == "vacuum":
+ action = "start"
else:
return f"{domain} {state.type}功能尚未支持"
- if arg == '':
+ if arg == "":
data = {
"entity_id": entity_id,
}
else:
- data = {
- "entity_id": entity_id,
- arg: value
- }
+ data = {"entity_id": entity_id, arg: value}
url = f"{base_url}/api/services/{domain}/{action}"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json"
- }
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=data)
- logger.bind(tag=TAG).info(f"设置状态:{description},url:{url},return_code:{response.status_code}")
+ logger.bind(tag=TAG).info(
+ f"设置状态:{description},url:{url},return_code:{response.status_code}"
+ )
if response.status_code == 200:
return description
else:
diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py
index 3de19d764..6d184b6b4 100644
--- a/main/xiaozhi-server/plugins_func/functions/play_music.py
+++ b/main/xiaozhi-server/plugins_func/functions/play_music.py
@@ -11,6 +11,7 @@ from core.utils import p3
from core.handle.sendAudioHandle import send_stt_message
from plugins_func.register import register_function, ToolType, ActionResponse, Action
from core.utils.dialogue import Message
+from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
TAG = __name__
@@ -216,23 +217,37 @@ async def play_local_music(conn, specific_file=None):
text = _get_random_play_prompt(selected_music)
await send_stt_message(conn, text)
conn.dialogue.put(Message(role="assistant", content=text))
- conn.tts_first_text_index = 0
- conn.tts_last_text_index = 0
- tts_file = await asyncio.to_thread(conn.tts.to_tts, text)
- if tts_file is not None and os.path.exists(tts_file):
- conn.tts_last_text_index = 1
- opus_packets, _ = conn.tts.audio_to_opus_data(tts_file)
- conn.audio_play_queue.put((opus_packets, None, 0))
- os.remove(tts_file)
-
- conn.llm_finish_task = True
-
- if music_path.endswith(".p3"):
- opus_packets, _ = p3.decode_opus_from_file(music_path)
- else:
- opus_packets, _ = conn.tts.audio_to_opus_data(music_path)
- conn.audio_play_queue.put((opus_packets, None, conn.tts_last_text_index))
+ conn.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=conn.sentence_id,
+ sentence_type=SentenceType.FIRST,
+ content_type=ContentType.ACTION,
+ )
+ )
+ conn.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=conn.sentence_id,
+ sentence_type=SentenceType.MIDDLE,
+ content_type=ContentType.TEXT,
+ content_detail=text,
+ )
+ )
+ conn.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=conn.sentence_id,
+ sentence_type=SentenceType.MIDDLE,
+ content_type=ContentType.FILE,
+ content_file=music_path,
+ )
+ )
+ conn.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=conn.sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.ACTION,
+ )
+ )
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
diff --git a/main/xiaozhi-server/plugins_func/functions/plugin_loader.py b/main/xiaozhi-server/plugins_func/functions/plugin_loader.py
deleted file mode 100644
index 7041d7a03..000000000
--- a/main/xiaozhi-server/plugins_func/functions/plugin_loader.py
+++ /dev/null
@@ -1,56 +0,0 @@
-from plugins_func.register import register_function, ToolType, ActionResponse, Action
-
-plugin_loader_function_desc = {
- "type": "function",
- "function": {
- "name": "plugin_loader",
- "description": "当用户想加载或卸载插件/function时,调用此函数:支持的插件列表为[plugins]",
- "parameters": {
- "type": "object",
- "properties": {
- "oper": {"type": "string", "description": "load or unload"},
- "name": {"type": "string", "description": "要加载或卸载的插件名字"},
- },
- "required": ["oper", "name"],
- },
- },
-}
-
-
-@register_function("plugin_loader", plugin_loader_function_desc, ToolType.SYSTEM_CTL)
-def plugin_loader(conn, oper: str, name: str):
- """插件加载"""
- if oper not in ["load", "unload"]:
- return ActionResponse(
- action=Action.RESPONSE, result="插件操作失败", response="不支持的操作"
- )
-
- cur_support = conn.func_handler.current_support_functions()
- if oper == "load":
- if name in cur_support:
- return ActionResponse(
- action=Action.RESPONSE,
- result="插件加载失败",
- response=f"{name}插件已加载,无需重复加载",
- )
- func = conn.func_handler.function_registry.register_function(name)
- if not func:
- return ActionResponse(
- action=Action.RESPONSE, result="插件加载失败", response="插件未找到"
- )
- res = f"{name}插件加载成功"
- else:
- if name not in cur_support:
- return ActionResponse(
- action=Action.RESPONSE,
- result="插件卸载失败",
- response=f"{name}插件未加载",
- )
- bOK = conn.func_handler.function_registry.unregister_function(name)
- if not bOK:
- return ActionResponse(
- action=Action.RESPONSE, result="插件卸载失败", response="插件未找到"
- )
- res = f"{name}插件卸载成功"
- conn.func_handler.upload_functions_desc()
- return ActionResponse(action=Action.RESPONSE, result="插件操作成功", response=res)
diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py
index b96f2f29b..873c61e11 100644
--- a/main/xiaozhi-server/plugins_func/register.py
+++ b/main/xiaozhi-server/plugins_func/register.py
@@ -77,7 +77,6 @@ class DeviceTypeRegistry:
# 初始化函数注册字典
all_function_registry = {}
-device_type_registry = DeviceTypeRegistry()
def register_function(name, desc, type=None):
@@ -91,13 +90,29 @@ def register_function(name, desc, type=None):
return decorator
+def register_device_function(name, desc, type=None):
+ """注册设备级别的函数到函数注册字典的装饰器"""
+
+ def decorator(func):
+ logger.bind(tag=TAG).debug(f"设备函数 '{name}' 已加载")
+ return func
+
+ return decorator
+
+
class FunctionRegistry:
def __init__(self):
self.function_registry = {}
self.logger = setup_logging()
- def register_function(self, name):
- # 查找all_function_registry中是否有对应的函数
+ def register_function(self, name, func_item=None):
+ # 如果提供了func_item,直接注册
+ if func_item:
+ self.function_registry[name] = func_item
+ self.logger.bind(tag=TAG).debug(f"函数 '{name}' 直接注册成功")
+ return func_item
+
+ # 否则从all_function_registry中查找
func = all_function_registry.get(name)
if not func:
self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到")
diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt
index 9df7dde11..3ffbcfa46 100755
--- a/main/xiaozhi-server/requirements.txt
+++ b/main/xiaozhi-server/requirements.txt
@@ -21,7 +21,7 @@ cozepy==0.12.0
mem0ai==0.1.62
bs4==0.0.2
modelscope==1.23.2
-sherpa_onnx==1.11.0
+sherpa_onnx==1.12.0
mcp==1.8.1
cnlunar==0.2.0
PySocks==1.7.1
@@ -31,3 +31,6 @@ chardet==5.2.0
aioconsole==0.8.1
markitdown==0.1.1
mcp-proxy==0.6.0
+PyJWT==2.8.0
+psutil==7.0.0
+portalocker==2.10.1
\ No newline at end of file
diff --git a/main/xiaozhi-server/test/test_page.html b/main/xiaozhi-server/test/test_page.html
index d9b2eff62..567332b83 100644
--- a/main/xiaozhi-server/test/test_page.html
+++ b/main/xiaozhi-server/test/test_page.html
@@ -14,7 +14,7 @@
}
.container {
- max-width: 800px;
+ max-width: 1000px;
margin: 0 auto;
background-color: white;
border-radius: 10px;
@@ -482,9 +482,10 @@
-
+
+ placeholder="WebSocket服务器地址,如:ws://127.0.0.1:8000/xiaozhi/v1/" />
@@ -802,7 +803,10 @@
if (frameData && frameData.length > 0) {
// 转换为Float32
const floatData = convertInt16ToFloat32(frameData);
- decodedSamples.push(...floatData);
+ // 使用循环替代展开运算符
+ for (let i = 0; i < floatData.length; i++) {
+ decodedSamples.push(floatData[i]);
+ }
}
} catch (error) {
log("Opus解码失败: " + error.message, 'error');
@@ -810,8 +814,10 @@
}
if (decodedSamples.length > 0) {
- // 添加到解码队列
- this.queue.push(...decodedSamples);
+ // 使用循环替代展开运算符
+ for (let i = 0; i < decodedSamples.length; i++) {
+ this.queue.push(decodedSamples[i]);
+ }
this.totalSamples += decodedSamples.length;
// 如果累积了至少0.2秒的音频,开始播放
@@ -867,35 +873,39 @@
this.source = null;
this.playing = false;
- // 如果队列中还有数据或者缓冲区有新数据,继续播放
- if (this.queue.length > 0) {
- setTimeout(() => this.startPlaying(), 10);
- } else if (audioBufferQueue.length > 0) {
- // 缓冲区有新数据,进行解码
- const frames = [...audioBufferQueue];
- audioBufferQueue = [];
- this.decodeOpusFrames(frames);
- } else if (this.endOfStream) {
- // 流已结束且没有更多数据
- log("音频播放完成", 'info');
- isAudioPlaying = false;
- streamingContext = null;
- } else {
- // 等待更多数据
- setTimeout(() => {
- // 如果仍然没有新数据,但有更多的包到达
- if (this.queue.length === 0 && audioBufferQueue.length > 0) {
- const frames = [...audioBufferQueue];
- audioBufferQueue = [];
- this.decodeOpusFrames(frames);
- } else if (this.queue.length === 0 && audioBufferQueue.length === 0) {
- // 真的没有更多数据了
- log("音频播放完成 (超时)", 'info');
- isAudioPlaying = false;
- streamingContext = null;
- }
- }, 500); // 500ms超时
- }
+ // 使用setTimeout避免递归调用
+ setTimeout(() => {
+ // 如果队列中还有数据,继续播放
+ if (this.queue.length > 0) {
+ this.startPlaying();
+ } else if (audioBufferQueue.length > 0) {
+ // 缓冲区有新数据,进行解码
+ const frames = [...audioBufferQueue];
+ audioBufferQueue = [];
+ this.decodeOpusFrames(frames);
+ } else if (this.endOfStream) {
+ // 流已结束且没有更多数据
+ log("音频播放完成", 'info');
+ isAudioPlaying = false;
+ this.endOfStream = false;
+ streamingContext = null;
+ } else {
+ // 等待更多数据
+ setTimeout(() => {
+ // 如果仍然没有新数据,但有更多的包到达
+ if (this.queue.length === 0 && audioBufferQueue.length > 0) {
+ const frames = [...audioBufferQueue];
+ audioBufferQueue = [];
+ this.decodeOpusFrames(frames);
+ } else if (this.queue.length === 0 && audioBufferQueue.length === 0) {
+ // 真的没有更多数据了
+ log("音频播放完成 (超时)", 'info');
+ isAudioPlaying = false;
+ streamingContext = null;
+ }
+ }, 500); // 500ms超时
+ }
+ }, 10); // 10ms延迟,避免立即递归
};
this.source.start();
@@ -1061,7 +1071,7 @@
}
}
- // 初始化音频录制和处理
+ // 初始化音频录制和处理
async function initAudio() {
try {
// 请求麦克风权限
@@ -1306,7 +1316,8 @@
// 先检查OTA状态
log('正在检查OTA状态...', 'info');
const otaUrl = document.getElementById('otaUrl').value.trim();
-
+ localStorage.setItem('otaUrl', otaUrl);
+ localStorage.setItem('wsUrl', url);
try {
const otaResponse = await fetch(otaUrl, {
method: 'POST',
@@ -1473,6 +1484,23 @@
if (message.text && message.text !== '😊') {
addMessage(message.text);
}
+ }else if (message.type === 'mcp') {
+ const payload = message.payload || {};
+ log(`服务器下发: ${JSON.stringify(message)}`, 'info');
+ if (payload) {
+ // 模拟小智客户端行为
+ if(payload.method === 'tools/list'){
+ const replay_message = JSON.stringify({"session_id":"","type":"mcp","payload":{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"self.get_device_status","description":"Provides the real-time information of the device, including the current status of the audio speaker, screen, battery, network, etc.\nUse this tool for: \n1. Answering questions about current condition (e.g. what is the current volume of the audio speaker?)\n2. As the first step to control the device (e.g. turn up / down the volume of the audio speaker, etc.)","inputSchema":{"type":"object","properties":{}}},{"name":"self.audio_speaker.set_volume","description":"Set the volume of the audio speaker. If the current volume is unknown, you must call `self.get_device_status` tool first and then call this tool.","inputSchema":{"type":"object","properties":{"volume":{"type":"integer","minimum":0,"maximum":100}},"required":["volume"]}},{"name":"self.screen.set_brightness","description":"Set the brightness of the screen.","inputSchema":{"type":"object","properties":{"brightness":{"type":"integer","minimum":0,"maximum":100}},"required":["brightness"]}},{"name":"self.screen.set_theme","description":"Set the theme of the screen. The theme can be 'light' or 'dark'.","inputSchema":{"type":"object","properties":{"theme":{"type":"string"}},"required":["theme"]}}]}}})
+ websocket.send(replay_message);
+ log(`回复MCP消息: ${replay_message}`, 'info');
+ } else if(payload.method === 'tools/call'){
+ // 模拟回复
+ const replay_message = JSON.stringify({"session_id":"9f261599","type":"mcp","payload":{"jsonrpc":"2.0","id": payload.id,"result":{"content":[{"type":"text","text":"true"}],"isError":false}}})
+ websocket.send(replay_message);
+ log(`回复MCP消息: ${replay_message}`, 'info');
+ }
+ }
+
} else {
// 未知消息类型
log(`未知消息类型: ${message.type}`, 'info');
@@ -1512,7 +1540,10 @@
device_id: config.deviceId,
device_name: config.deviceName,
device_mac: config.deviceMac,
- token: config.token
+ token: config.token,
+ features: {
+ mcp: true
+ }
};
log('发送hello握手消息', 'info');
@@ -1563,6 +1594,10 @@
const message = messageInput.value.trim();
if (message === '' || !websocket || websocket.readyState !== WebSocket.OPEN) return;
+ audioBufferQueue = [];
+ isAudioBuffering = false;
+ isAudioPlaying = false;
+
try {
// 直接发送listen消息,不需要重复发送hello
const listenMessage = {
@@ -1633,6 +1668,16 @@
// 初始更新显示值
updateDisplayValues();
+ const savedOtaUrl = localStorage.getItem('otaUrl');
+ if (savedOtaUrl) {
+ document.getElementById('otaUrl').value = savedOtaUrl;
+ }
+
+ const savedWsUrl = localStorage.getItem('wsUrl');
+ if (savedWsUrl) {
+ document.getElementById('serverUrl').value = savedWsUrl;
+ }
+
// 切换面板显示
toggleButton.addEventListener('click', () => {
const isExpanded = configPanel.classList.contains('expanded');
@@ -1954,7 +1999,7 @@
this.buffer = new Int16Array(this.frameSize);
this.bufferIndex = 0;
this.isRecording = false;
-
+
// 监听来自主线程的消息
this.port.onmessage = (event) => {
if (event.data.command === 'start') {
@@ -1962,7 +2007,7 @@
this.port.postMessage({ type: 'status', status: 'started' });
} else if (event.data.command === 'stop') {
this.isRecording = false;
-
+
// 发送剩余的缓冲区
if (this.bufferIndex > 0) {
const finalBuffer = this.buffer.slice(0, this.bufferIndex);
@@ -1972,18 +2017,18 @@
});
this.bufferIndex = 0;
}
-
+
this.port.postMessage({ type: 'status', status: 'stopped' });
}
};
}
-
+
process(inputs, outputs, parameters) {
if (!this.isRecording) return true;
-
+
const input = inputs[0][0]; // 获取第一个输入通道
if (!input) return true;
-
+
// 将浮点采样转换为16位整数并存储
for (let i = 0; i < input.length; i++) {
if (this.bufferIndex >= this.frameSize) {
@@ -1994,15 +2039,15 @@
});
this.bufferIndex = 0;
}
-
+
// 转换为16位整数 (-32768到32767)
this.buffer[this.bufferIndex++] = Math.max(-32768, Math.min(32767, Math.floor(input[i] * 32767)));
}
-
+
return true;
}
}
-
+
registerProcessor('audio-recorder-processor', AudioRecorderProcessor);
`;