update:server连接manager-api

This commit is contained in:
hrz 2025-04-10 17:31:44 +08:00
parent 81d2571f8f
commit 325c570f2b
19 changed files with 289 additions and 144 deletions

View file

@ -51,4 +51,5 @@ public interface ErrorCode {
int PARAM_NUMBER_INVALID = 10037;
int PARAM_BOOLEAN_INVALID = 10038;
int PARAM_ARRAY_INVALID = 10039;
int PARAM_JSON_INVALID = 10040;
}

View file

@ -77,7 +77,7 @@ public class ShiroConfig {
filterMap.put("/user/captcha", "anon");
filterMap.put("/user/login", "anon");
filterMap.put("/user/register", "anon");
filterMap.put("/device/register", "anon");
filterMap.put("/admin/params/config", "anon");
filterMap.put("/**", "oauth2");
shiroFilter.setFilterChainDefinitionMap(filterMap);

View file

@ -28,6 +28,7 @@ import xiaozhi.common.validator.ValidatorUtils;
import xiaozhi.common.validator.group.AddGroup;
import xiaozhi.common.validator.group.DefaultGroup;
import xiaozhi.common.validator.group.UpdateGroup;
import xiaozhi.modules.sys.dto.ConfigSecretDTO;
import xiaozhi.modules.sys.dto.SysParamsDTO;
import xiaozhi.modules.sys.service.SysParamsService;
@ -107,4 +108,11 @@ public class SysParamsController {
return new Result<Void>();
}
@PostMapping("config")
@Operation(summary = "获取配置")
public Result<Object> getConfig(@RequestBody ConfigSecretDTO dto) {
Object config = sysParamsService.getConfig(dto.getSecret());
return new Result<Object>().ok(config);
}
}

View file

@ -0,0 +1,11 @@
package xiaozhi.modules.sys.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "配置密钥DTO")
public class ConfigSecretDTO {
@Schema(description = "密钥")
private String secret;
}

View file

@ -53,4 +53,12 @@ public interface SysParamsService extends BaseService<SysParamsEntity> {
* 初始化服务器密钥
*/
void initServerSecret();
/**
* 获取配置
*
* @param secret 密钥
* @return 配置信息
*/
Object getConfig(String secret);
}

View file

@ -1,6 +1,8 @@
package xiaozhi.modules.sys.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ -125,6 +127,13 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
throw new RenException(ErrorCode.PARAM_BOOLEAN_INVALID);
}
break;
case "json":
try {
JsonUtils.parseObject(paramValue, Object.class);
} catch (Exception e) {
throw new RenException(ErrorCode.PARAM_JSON_INVALID);
}
break;
default:
throw new RenException(ErrorCode.PARAM_TYPE_INVALID);
}
@ -189,4 +198,75 @@ public class SysParamsServiceImpl extends BaseServiceImpl<SysParamsDao, SysParam
updateValueByCode(Constant.SERVER_SECRET, newSecret);
}
}
@Override
@SuppressWarnings("unchecked")
public Object getConfig(String secret) {
String secretParam = getValue(Constant.SERVER_SECRET, true);
// 验证密钥
if (StringUtils.isBlank(secret) || !secret.equals(secretParam)) {
throw new RenException("密钥错误");
}
// 查询所有非系统参数
QueryWrapper<SysParamsEntity> wrapper = new QueryWrapper<>();
wrapper.eq("param_type", 1);
List<SysParamsEntity> paramsList = baseDao.selectList(wrapper);
// 构建配置信息
Map<String, Object> config = new HashMap<>();
for (SysParamsEntity param : paramsList) {
String[] keys = param.getParamCode().split("\\.");
Map<String, Object> current = config;
// 遍历除最后一个key之外的所有key
for (int i = 0; i < keys.length - 1; i++) {
String key = keys[i];
if (!current.containsKey(key)) {
current.put(key, new HashMap<String, Object>());
}
current = (Map<String, Object>) current.get(key);
}
// 处理最后一个key
String lastKey = keys[keys.length - 1];
String value = param.getParamValue();
// 根据valueType转换值
switch (param.getValueType().toLowerCase()) {
case "number":
try {
current.put(lastKey, Double.parseDouble(value));
} catch (NumberFormatException e) {
current.put(lastKey, value);
}
break;
case "boolean":
current.put(lastKey, Boolean.parseBoolean(value));
break;
case "array":
// 将分号分隔的字符串转换为数字数组
List<String> list = new ArrayList<>();
for (String num : value.split(";")) {
if (StringUtils.isNotBlank(num)) {
list.add(num.trim());
}
}
current.put(lastKey, list);
break;
case "json":
try {
current.put(lastKey, JsonUtils.parseObject(value, Object.class));
} catch (Exception e) {
current.put(lastKey, value);
}
break;
default:
current.put(lastKey, value);
}
}
return config;
}
}

View file

@ -47,15 +47,15 @@ INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, r
"channels": 1,
"frame_duration": 60
}
}', 'string', 1, '小智类型');
}', 'json', 1, '小智类型');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (310, 'wakeup_words', '你好小智;你好小志;小爱同学;你好小鑫;你好小新;小美同学;小龙小龙;喵喵同学;小滨小滨;小冰小冰', 'array', 1, '唤醒词列表,用于识别唤醒词');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (400, 'plugin.weather.api_key', 'a861d0d5e7bf4ee1a83d9a9e4f96d4da', 'string', 1, '天气插件API密钥');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (401, 'plugin.weather.default_location', '广州', 'string', 1, '天气插件默认城市');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (410, 'plugin.news.default_rss_url', 'https://www.chinanews.com.cn/rss/society.xml', 'string', 1, '新闻插件默认RSS地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (411, 'plugin.news.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"}', 'string', 1, '新闻插件分类RSS地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (421, 'plugin.home_assistant.devices', '客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1;卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1', 'array', 1, 'Home Assistant设备列表');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (422, 'plugin.home_assistant.base_url', 'http://homeassistant.local:8123', 'string', 1, 'Home Assistant服务器地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (423, 'plugin.home_assistant.api_key', '你的home assistant api访问令牌', 'string', 1, 'Home Assistant API密钥');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (430, 'plugin.music.music_dir', './music', 'string', 1, '音乐文件存放路径');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (431, 'plugin.music.music_ext', 'mp3;wav;p3', 'array', 1, '音乐文件类型');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (432, 'plugin.music.refresh_time', '300', 'number', 1, '音乐列表刷新间隔(秒)');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (400, 'plugins.get_weather.api_key', 'a861d0d5e7bf4ee1a83d9a9e4f96d4da', 'string', 1, '天气插件API密钥');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (401, 'plugins.get_weather.default_location', '广州', 'string', 1, '天气插件默认城市');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (410, 'plugins.get_news.default_rss_url', 'https://www.chinanews.com.cn/rss/society.xml', 'string', 1, '新闻插件默认RSS地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (411, 'plugins.get_news.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"}', 'json', 1, '新闻插件分类RSS地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (421, 'plugins.home_assistant.devices', '客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1;卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1', 'array', 1, 'Home Assistant设备列表');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (422, 'plugins.home_assistant.base_url', 'http://homeassistant.local:8123', 'string', 1, 'Home Assistant服务器地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (423, 'plugins.home_assistant.api_key', '你的home assistant api访问令牌', 'string', 1, 'Home Assistant API密钥');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (430, 'plugins.play_music.music_dir', './music', 'string', 1, '音乐文件存放路径');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (431, 'plugins.play_music.music_ext', 'mp3;wav;p3', 'array', 1, '音乐文件类型');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (432, 'plugins.play_music.refresh_time', '300', 'number', 1, '音乐列表刷新间隔(秒)');

View file

@ -37,13 +37,6 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504082211.sql
- changeSet:
id: 202504092313
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504092313.sql
- changeSet:
id: 202504092335
author: John
@ -51,3 +44,10 @@ databaseChangeLog:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504092335.sql
- changeSet:
id: 202504101506
author: John
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202504101506.sql

View file

@ -40,3 +40,4 @@
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F

View file

@ -40,3 +40,4 @@
10037=Parameter value must be a valid number
10038=Parameter value must be true or false
10039=Parameter value must be a valid JSON array format
10040=Parameter value must be a valid JSON format

View file

@ -40,3 +40,4 @@
10037=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684\u6570\u5B57
10038=\u53C2\u6570\u503C\u5FC5\u987B\u662Ftrue\u6216false
10039=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u6570\u7EC4\u683C\u5F0F
10040=\u53C2\u6570\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684JSON\u683C\u5F0F

View file

@ -40,3 +40,4 @@
10037=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684\u6578\u5B57
10038=\u53C3\u6578\u503C\u5FC5\u9808\u662Ftrue\u6216false
10039=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u6578\u7D44\u683C\u5F0F
10040=\u53C3\u6578\u503C\u5FC5\u9808\u662F\u6709\u6548\u7684JSON\u683C\u5F0F

View file

@ -52,7 +52,7 @@ enable_stop_tts_notify: false
# 说完话是否开启提示音,音效地址
stop_tts_notify_voice: "config/assets/tts_notify.mp3"
CMD_exit:
exit_commands:
- "退出"
- "关闭"

View file

@ -19,7 +19,7 @@ def setup_logging():
"{time:YYYY-MM-DD HH:mm:ss} - {version_{selected_module}} - {name} - {level} - {extra[tag]} - {message}",
)
selected_module = config.get("selected_module")
selected_module = config.get("selected_module", {})
selected_module_str = "".join(
[value[0] + value[1] for key, value in selected_module.items()]
)

View file

@ -5,6 +5,7 @@ from collections.abc import Mapping
from core.utils.util import read_config, get_project_dir
default_config_file = "config.yaml"
read_config_from_api = False
def ensure_directories(config):
@ -12,24 +13,24 @@ def ensure_directories(config):
dirs_to_create = set()
project_dir = get_project_dir() # 获取项目根目录
# 日志文件目录
log_dir = config.get('log', {}).get('log_dir', 'tmp')
log_dir = config.get("log", {}).get("log_dir", "tmp")
dirs_to_create.add(os.path.join(project_dir, log_dir))
# ASR/TTS模块输出目录
for module in ['ASR', 'TTS']:
for module in ["ASR", "TTS"]:
for provider in config.get(module, {}).values():
output_dir = provider.get('output_dir', '')
output_dir = provider.get("output_dir", "")
if output_dir:
dirs_to_create.add(output_dir)
# 根据selected_module创建模型目录
selected_modules = config.get('selected_module', {})
for module_type in ['ASR', 'LLM', 'TTS']:
selected_modules = config.get("selected_module", {})
for module_type in ["ASR", "LLM", "TTS"]:
selected_provider = selected_modules.get(module_type)
if not selected_provider:
continue
provider_config = config.get(module_type, {}).get(selected_provider, {})
output_dir = provider_config.get('output_dir')
output_dir = provider_config.get("output_dir")
if output_dir:
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
@ -44,6 +45,7 @@ def ensure_directories(config):
def get_config_file():
global default_config_file
global read_config_from_api
"""获取配置文件路径,优先使用私有配置文件(若存在)。
Returns:
@ -52,6 +54,10 @@ def get_config_file():
config_file = default_config_file
if os.path.exists(get_project_dir() + "data/." + default_config_file):
config_file = "data/." + default_config_file
config = read_config(config_file)
"""如果存在manager-api,则使用manager-api的配置"""
if config.get("manager-api", {}).get("url"):
read_config_from_api = True
return config_file
@ -72,11 +78,11 @@ def update_config(config):
yaml = YAML()
yaml.preserve_quotes = True
"""将配置保存到YAML文件"""
with open(get_config_file(), 'w') as f:
with open(get_config_file(), "w") as f:
yaml.dump(config, f)
def find_missing_keys(new_config, old_config, parent_key=''):
def find_missing_keys(new_config, old_config, parent_key=""):
"""
递归查找缺失的配置项
返回格式:[缺失配置路径]
@ -98,30 +104,59 @@ def find_missing_keys(new_config, old_config, parent_key=''):
# 递归检查嵌套字典
if isinstance(value, Mapping):
sub_missing = find_missing_keys(
value,
old_config[key],
parent_key=full_path
value, old_config[key], parent_key=full_path
)
missing_keys.extend(sub_missing)
return missing_keys
def check_config_file():
old_config_file = get_config_file()
global default_config_file
if not 'data' in old_config_file:
global read_config_from_api
if not "data" in old_config_file:
return
old_config = read_config(get_project_dir() + old_config_file)
new_config = read_config(get_project_dir() + default_config_file)
# 查找缺失的配置项
missing_keys = find_missing_keys(new_config, old_config)
if read_config_from_api:
missing_keys = remove_api_config(missing_keys)
if missing_keys:
error_msg = "您的配置文件太旧了,缺少了:\n"
error_msg += "\n".join(f"- {key}" for key in missing_keys)
error_msg += "\n建议您:\n"
error_msg += "1、备份data/.config.yaml文件\n"
error_msg += "2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n"
error_msg += "3、将密钥逐个复制到新的配置文件中\n"
missing_keys_str = "\n".join(f"- {key}" for key in missing_keys)
if read_config_from_api:
error_msg = "您的配置文件太旧了,缺少了:\n"
error_msg += missing_keys_str
error_msg += "\n建议您:\n"
error_msg += "1、备份data/.config.yaml文件\n"
error_msg += (
"2、将根目录的config.yaml文件复制到data下,重命名为.config.yaml\n"
)
error_msg += "3、将密钥逐个复制到新的配置文件中\n"
else:
error_msg = "您的服务器配置和本地配置不一致,缺少了:\n"
error_msg += missing_keys_str
error_msg += "\n建议您:\n"
error_msg += "1、保持manager-api和xiaozhi-server版本一致\n"
error_msg += "2、或手动恢复被删除的配置\n"
raise ValueError(error_msg)
def remove_api_config(missing_keys):
"""从缺失配置列表中移除API相关的配置项"""
ignore_keys = {
"server.auth",
"module_test",
"prompt",
"selected_module",
"Intent",
"Memory",
"ASR",
"VAD",
"LLM",
"TTS",
}
missing_keys = [key for key in missing_keys if key not in ignore_keys]
return missing_keys

View file

@ -0,0 +1,12 @@
# 如果你只想轻量化安装xiaozhi-server,只使用本地的配置文件,不需要理会这个文件,不需要改动本文件任何东西
# 如果你想从manager-api获取配置,请往下看:
# 请将本文件复制到xiaozhi-server/data目录下,没有data目录,请创建一个,并将复制过去的文件命名为.config.yaml
# 注意如果data目录有.config.yaml文件,请先删除它
# 先启动manager-api和manager-web,注册一个账号,第一个注册的账号为管理员
# 使用管理员,进入【参数管理】页面,找到【server.secret】,复制它到参数值,注意每次从零部署,server.secret都会变化
# 打开本data目录下的.config.yaml文件,修改manager-api.secret为刚才复制出来的server.secret
manager-api:
# 你的manager-api的地址,最好使用局域网ip
url: http://127.0.0.1:8002/xiaozhi
# 你的manager-api的token,就是刚才复制出来的server.secret
secret: 你的server.secret值

View file

@ -1,4 +1,5 @@
import os
import copy
import json
import uuid
import time
@ -20,6 +21,7 @@ from core.utils.util import (
)
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from core.handle.sendAudioHandle import sendAudioMessage
from core.utils import llm, tts, memory, intent
from core.handle.receiveAudioHandle import handleAudioMessage
from core.handle.functionHandler import FunctionHandler
from plugins_func.register import Action, ActionResponse
@ -38,10 +40,8 @@ class TTSException(RuntimeError):
class ConnectionHandler:
def __init__(
self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent
):
self.config = config
def __init__(self, config: Dict[str, Any], _vad, _asr):
self.config = copy.deepcopy(config)
self.logger = setup_logging()
self.auth = AuthMiddleware(config)
@ -67,10 +67,10 @@ class ConnectionHandler:
# 依赖的组件
self.vad = _vad
self.asr = _asr
self.llm = _llm
self.tts = _tts
self.memory = _memory
self.intent = _intent
self.llm = None
self.tts = None
self.memory = None
self.intent = None
# vad相关变量
self.client_audio_buffer = bytearray()
@ -95,7 +95,7 @@ class ConnectionHandler:
self.iot_descriptors = {}
self.func_handler = None
self.cmd_exit = self.config["CMD_exit"]
self.cmd_exit = self.config["exit_commands"]
self.max_cmd_length = 0
for cmd in self.cmd_exit:
if len(cmd) > self.max_cmd_length:
@ -121,7 +121,6 @@ class ConnectionHandler:
# 进行认证
await self.auth.authenticate(self.headers)
device_id = self.headers.get("device-id", None)
# 认证通过,继续处理
self.websocket = ws
@ -130,39 +129,6 @@ class ConnectionHandler:
self.welcome_msg = self.config["xiaozhi"]
self.welcome_msg["session_id"] = self.session_id
await self.websocket.send(json.dumps(self.welcome_msg))
# Load private configuration if device_id is provided
bUsePrivateConfig = self.config.get("use_private_config", False)
if bUsePrivateConfig and device_id:
try:
self.private_config = PrivateConfig(
device_id, self.config, self.auth_code_gen
)
await self.private_config.load_or_create()
# 判断是否已经绑定
owner = self.private_config.get_owner()
self.is_device_verified = owner is not None
if self.is_device_verified:
await self.private_config.update_last_chat_time()
llm, tts = self.private_config.create_private_instances()
if all([llm, tts]):
self.llm = llm
self.tts = tts
self.logger.bind(tag=TAG).info(
f"Loaded private config and instances for device {device_id}"
)
else:
self.logger.bind(tag=TAG).error(
f"Failed to create instances for device {device_id}"
)
self.private_config = None
except Exception as e:
self.logger.bind(tag=TAG).error(
f"Error initializing private config: {e}"
)
self.private_config = None
raise
# 异步初始化
self.executor.submit(self._initialize_components)
@ -210,7 +176,62 @@ class ConnectionHandler:
elif isinstance(message, bytes):
await handleAudioMessage(self, message)
def _initialize_modules(self):
"""初始化组件"""
_tts = tts.create_instance(
(
self.config["selected_module"]["TTS"]
if not "type"
in self.config["TTS"][self.config["selected_module"]["TTS"]]
else self.config["TTS"][self.config["selected_module"]["TTS"]]["type"]
),
self.config["TTS"][self.config["selected_module"]["TTS"]],
self.config["delete_audio"],
)
self.tts = _tts
print("初始化组件_tts")
_llm = llm.create_instance(
(
self.config["selected_module"]["LLM"]
if not "type"
in self.config["LLM"][self.config["selected_module"]["LLM"]]
else self.config["LLM"][self.config["selected_module"]["LLM"]]["type"]
),
self.config["LLM"][self.config["selected_module"]["LLM"]],
)
self.llm = _llm
print("初始化组件_llm")
_intent = intent.create_instance(
(
self.config["selected_module"]["Intent"]
if not "type"
in self.config["Intent"][self.config["selected_module"]["Intent"]]
else self.config["Intent"][self.config["selected_module"]["Intent"]][
"type"
]
),
self.config["Intent"][self.config["selected_module"]["Intent"]],
)
self.intent = _intent
print("初始化组件_intent")
_memory = memory.create_instance(
(
self.config["selected_module"]["Memory"]
if not "type"
in self.config["Memory"][self.config["selected_module"]["Memory"]]
else self.config["Memory"][self.config["selected_module"]["Memory"]][
"type"
]
),
self.config["Memory"][self.config["selected_module"]["Memory"]],
)
self.memory = _memory
print("初始化组件_memory")
def _initialize_components(self):
print("初始化组件11")
self._initialize_modules()
print("初始化组件22")
"""加载提示词"""
self.prompt = self.config["prompt"]
if self.private_config:

View file

@ -88,6 +88,24 @@ def get_ip_info(ip_addr):
def read_config(config_path):
with open(config_path, "r", encoding="utf-8") as file:
config = yaml.safe_load(file)
if config.get("manager-api", {}).get("url"):
# 从Java API获取配置
api_url = config["manager-api"].get("url", "")
secret = config["manager-api"].get("secret", "")
if not api_url or not secret:
raise Exception("manager-api的url或secret配置错误")
if "你" in secret:
raise Exception("请先配置manager-api的secret")
response = requests.post(
f"{api_url}/admin/params/config", json={"secret": secret}
)
if response.status_code == 200:
config = response.json()["data"]
config["manager-api"] = {"url": api_url, "secret": secret}
return config
else:
raise Exception(f"从Java API获取配置失败,网络错误: {response.text}")
return config

View file

@ -3,7 +3,7 @@ import websockets
from config.logger import setup_logging
from core.connection import ConnectionHandler
from core.utils.util import get_local_ip
from core.utils import asr, vad, llm, tts, memory, intent
from core.utils import asr, vad
TAG = __name__
@ -12,20 +12,10 @@ class WebSocketServer:
def __init__(self, config: dict):
self.config = config
self.logger = setup_logging()
self._vad, self._asr, self._llm, self._tts, self._memory, self.intent = (
self._create_processing_instances()
)
self.active_connections = set() # 添加全局连接记录
self._vad, self._asr = self._create_processing_instances()
self.active_connections = set()
def _create_processing_instances(self):
memory_cls_name = self.config["selected_module"].get(
"Memory", "nomem"
) # 默认使用nomem
has_memory_cfg = (
self.config.get("Memory") and memory_cls_name in self.config["Memory"]
)
memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {}
"""创建处理模块实例"""
return (
vad.create_instance(
@ -44,41 +34,6 @@ class WebSocketServer:
self.config["ASR"][self.config["selected_module"]["ASR"]],
self.config["delete_audio"],
),
llm.create_instance(
(
self.config["selected_module"]["LLM"]
if not "type"
in self.config["LLM"][self.config["selected_module"]["LLM"]]
else self.config["LLM"][self.config["selected_module"]["LLM"]][
"type"
]
),
self.config["LLM"][self.config["selected_module"]["LLM"]],
),
tts.create_instance(
(
self.config["selected_module"]["TTS"]
if not "type"
in self.config["TTS"][self.config["selected_module"]["TTS"]]
else self.config["TTS"][self.config["selected_module"]["TTS"]][
"type"
]
),
self.config["TTS"][self.config["selected_module"]["TTS"]],
self.config["delete_audio"],
),
memory.create_instance(memory_cls_name, memory_cfg),
intent.create_instance(
(
self.config["selected_module"]["Intent"]
if not "type"
in self.config["Intent"][self.config["selected_module"]["Intent"]]
else self.config["Intent"][
self.config["selected_module"]["Intent"]
]["type"]
),
self.config["Intent"][self.config["selected_module"]["Intent"]],
),
)
async def start(self):
@ -104,15 +59,7 @@ class WebSocketServer:
async def _handle_connection(self, websocket):
"""处理新连接,每次创建独立的ConnectionHandler"""
# 创建ConnectionHandler时传入当前server实例
handler = ConnectionHandler(
self.config,
self._vad,
self._asr,
self._llm,
self._tts,
self._memory,
self.intent,
)
handler = ConnectionHandler(self.config, self._vad, self._asr)
self.active_connections.add(handler)
try:
await handler.handle_connection(websocket)