mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
update:加载私有模型配置
This commit is contained in:
parent
c5ea1da95b
commit
d9371fa185
10 changed files with 181 additions and 40 deletions
|
|
@ -68,4 +68,11 @@ public class RedisKeys {
|
|||
public static String getServerConfigKey() {
|
||||
return "server:config";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取音色详情缓存key
|
||||
*/
|
||||
public static String getTimbreDetailsKey(String id) {
|
||||
return "timbre:details:" + id;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ public class ConfigController {
|
|||
// 效验数据
|
||||
ValidatorUtils.validateEntity(dto);
|
||||
checkSecret(dto.getSecret());
|
||||
Object models = configService.getAgentModels(dto.getMacAddress());
|
||||
Object models = configService.getAgentModels(dto.getMacAddress(), dto.getSelectedModule());
|
||||
return new Result<Object>().ok(models);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
package xiaozhi.modules.config.dto;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
|
|
@ -18,4 +21,8 @@ public class AgentModelsDTO {
|
|||
@NotBlank(message = "客户端ID不能为空")
|
||||
@Schema(description = "客户端ID")
|
||||
private String clientId;
|
||||
|
||||
@NotNull(message = "客户端已实例化的模型不能为空")
|
||||
@Schema(description = "客户端已实例化的模型")
|
||||
private Map<String, String> selectedModule;
|
||||
}
|
||||
|
|
@ -14,8 +14,9 @@ public interface ConfigService {
|
|||
/**
|
||||
* 获取智能体模型配置
|
||||
*
|
||||
* @param macAddress MAC地址
|
||||
* @param macAddress MAC地址
|
||||
* @param selectedModule 客户端已实例化的模型
|
||||
* @return 模型配置信息
|
||||
*/
|
||||
Map<String, Object> getAgentModels(String macAddress);
|
||||
Map<String, Object> getAgentModels(String macAddress, Map<String, String> selectedModule);
|
||||
}
|
||||
|
|
@ -24,6 +24,8 @@ import xiaozhi.modules.model.entity.ModelConfigEntity;
|
|||
import xiaozhi.modules.model.service.ModelConfigService;
|
||||
import xiaozhi.modules.sys.dto.SysParamsDTO;
|
||||
import xiaozhi.modules.sys.service.SysParamsService;
|
||||
import xiaozhi.modules.timbre.service.TimbreService;
|
||||
import xiaozhi.modules.timbre.vo.TimbreDetailsVO;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
|
|
@ -34,6 +36,7 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
private final AgentService agentService;
|
||||
private final AgentTemplateService agentTemplateService;
|
||||
private final RedisUtils redisUtils;
|
||||
private final TimbreService timbreService;
|
||||
|
||||
@Override
|
||||
public Object getConfig(Boolean isCache) {
|
||||
|
|
@ -58,6 +61,7 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
// 构建模块配置
|
||||
buildModuleConfig(
|
||||
agent.getSystemPrompt(),
|
||||
null,
|
||||
agent.getVadModelId(),
|
||||
agent.getAsrModelId(),
|
||||
agent.getLlmModelId(),
|
||||
|
|
@ -74,7 +78,7 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getAgentModels(String macAddress) {
|
||||
public Map<String, Object> getAgentModels(String macAddress, Map<String, String> selectedModule) {
|
||||
// 根据MAC地址查找设备
|
||||
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
|
||||
if (device == null) {
|
||||
|
|
@ -85,12 +89,41 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
if (agent == null) {
|
||||
throw new RenException("智能体未找到");
|
||||
}
|
||||
// 获取音色信息
|
||||
String voice = null;
|
||||
TimbreDetailsVO timbre = timbreService.get(agent.getTtsVoiceId());
|
||||
if (timbre != null) {
|
||||
voice = timbre.getTtsVoice();
|
||||
}
|
||||
// 构建返回数据
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
// 如果客户端已实例化模型,则不返回
|
||||
String alreadySelectedVadModelId = (String) selectedModule.get("VAD");
|
||||
if (alreadySelectedVadModelId != null && alreadySelectedVadModelId.equals(agent.getVadModelId())) {
|
||||
agent.setVadModelId(null);
|
||||
}
|
||||
String alreadySelectedAsrModelId = (String) selectedModule.get("ASR");
|
||||
if (alreadySelectedAsrModelId != null && alreadySelectedAsrModelId.equals(agent.getAsrModelId())) {
|
||||
agent.setAsrModelId(null);
|
||||
}
|
||||
String alreadySelectedLlmModelId = (String) selectedModule.get("LLM");
|
||||
if (alreadySelectedLlmModelId != null && alreadySelectedLlmModelId.equals(agent.getLlmModelId())) {
|
||||
agent.setLlmModelId(null);
|
||||
}
|
||||
String alreadySelectedMemModelId = (String) selectedModule.get("Memory");
|
||||
if (alreadySelectedMemModelId != null && alreadySelectedMemModelId.equals(agent.getMemModelId())) {
|
||||
agent.setMemModelId(null);
|
||||
}
|
||||
String alreadySelectedIntentModelId = (String) selectedModule.get("Intent");
|
||||
if (alreadySelectedIntentModelId != null && alreadySelectedIntentModelId.equals(agent.getIntentModelId())) {
|
||||
agent.setIntentModelId(null);
|
||||
}
|
||||
|
||||
// 构建模块配置
|
||||
buildModuleConfig(
|
||||
agent.getSystemPrompt(),
|
||||
voice,
|
||||
agent.getVadModelId(),
|
||||
agent.getAsrModelId(),
|
||||
agent.getLlmModelId(),
|
||||
|
|
@ -172,6 +205,8 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
/**
|
||||
* 构建模块配置
|
||||
*
|
||||
* @param prompt 提示词
|
||||
* @param voice 音色
|
||||
* @param vadModelId VAD模型ID
|
||||
* @param asrModelId ASR模型ID
|
||||
* @param llmModelId LLM模型ID
|
||||
|
|
@ -182,6 +217,7 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
*/
|
||||
private void buildModuleConfig(
|
||||
String prompt,
|
||||
String voice,
|
||||
String vadModelId,
|
||||
String asrModelId,
|
||||
String llmModelId,
|
||||
|
|
@ -196,11 +232,20 @@ public class ConfigServiceImpl implements ConfigService {
|
|||
String[] modelIds = { vadModelId, asrModelId, llmModelId, ttsModelId, memModelId, intentModelId };
|
||||
|
||||
for (int i = 0; i < modelIds.length; i++) {
|
||||
if (modelIds[i] == null) {
|
||||
continue;
|
||||
}
|
||||
ModelConfigEntity model = modelConfigService.getModelById(modelIds[i], isCache);
|
||||
Map<String, Object> typeConfig = new HashMap<>();
|
||||
typeConfig.put(model.getModelCode(), model.getConfigJson());
|
||||
if (model.getConfigJson() != null) {
|
||||
typeConfig.put(model.getId(), model.getConfigJson());
|
||||
// 如果是TTS类型,添加private_voice属性
|
||||
if ("TTS".equals(modelTypes[i]) && voice != null) {
|
||||
((Map<String, Object>) model.getConfigJson()).put("private_voice", voice);
|
||||
}
|
||||
}
|
||||
result.put(modelTypes[i], typeConfig);
|
||||
selectedModule.put(modelTypes[i], model.getModelCode());
|
||||
selectedModule.put(modelTypes[i], model.getId());
|
||||
}
|
||||
result.put("selected_module", selectedModule);
|
||||
result.put("prompt", prompt);
|
||||
|
|
|
|||
|
|
@ -94,6 +94,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
|
|||
modelConfigEntity.setId(id);
|
||||
modelConfigEntity.setModelType(modelType);
|
||||
modelConfigDao.updateById(modelConfigEntity);
|
||||
// 清除缓存
|
||||
redisUtils.delete(RedisKeys.getModelConfigById(modelConfigEntity.getId()));
|
||||
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ public interface TimbreService extends BaseService<TimbreEntity> {
|
|||
* @param timbreId 音色表id
|
||||
* @return 音色信息
|
||||
*/
|
||||
TimbreDetailsVO get(Long timbreId);
|
||||
TimbreDetailsVO get(String timbreId);
|
||||
|
||||
/**
|
||||
* 保存音色信息
|
||||
|
|
|
|||
|
|
@ -59,9 +59,33 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
|||
}
|
||||
|
||||
@Override
|
||||
public TimbreDetailsVO get(Long timbreId) {
|
||||
public TimbreDetailsVO get(String timbreId) {
|
||||
if (StringUtils.isBlank(timbreId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 先从Redis获取缓存
|
||||
String key = RedisKeys.getTimbreDetailsKey(timbreId);
|
||||
TimbreDetailsVO cachedDetails = (TimbreDetailsVO) redisUtils.get(key);
|
||||
if (cachedDetails != null) {
|
||||
return cachedDetails;
|
||||
}
|
||||
|
||||
// 如果缓存中没有,则从数据库获取
|
||||
TimbreEntity entity = baseDao.selectById(timbreId);
|
||||
return ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class);
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 转换为VO对象
|
||||
TimbreDetailsVO details = ConvertUtils.sourceToTarget(entity, TimbreDetailsVO.class);
|
||||
|
||||
// 存入Redis缓存
|
||||
if (details != null) {
|
||||
redisUtils.set(key, details);
|
||||
}
|
||||
|
||||
return details;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -79,6 +103,8 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
|
|||
TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class);
|
||||
timbreEntity.setId(timbreId);
|
||||
baseDao.updateById(timbreEntity);
|
||||
// 删除缓存
|
||||
redisUtils.delete(RedisKeys.getTimbreDetailsKey(timbreId));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import os
|
|||
import argparse
|
||||
import requests
|
||||
import yaml
|
||||
import time
|
||||
|
||||
# 添加全局配置缓存
|
||||
_config_cache = None
|
||||
|
|
@ -74,22 +75,38 @@ def _make_api_request(api_url, secret, endpoint, json_data=None):
|
|||
if "你" in secret:
|
||||
raise Exception("请先配置manager-api的secret")
|
||||
|
||||
response = requests.post(f"{api_url}{endpoint}", json=json_data)
|
||||
if response.status_code != 200:
|
||||
error_msg = f"API请求失败,状态码: {response.status_code}"
|
||||
max_retries = 10
|
||||
retry_delay = 2 # 秒
|
||||
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
error_data = response.json()
|
||||
if "msg" in error_data:
|
||||
error_msg = f"{error_msg}, 错误信息: {error_data['msg']}"
|
||||
except:
|
||||
error_msg = f"{error_msg}, 响应内容: {response.text}"
|
||||
raise Exception(error_msg)
|
||||
response = requests.post(f"{api_url}{endpoint}", json=json_data)
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
if result.get("code") != 0:
|
||||
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
|
||||
return result.get("data")
|
||||
|
||||
result = response.json()
|
||||
if result.get("code") != 0:
|
||||
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
|
||||
error_msg = f"manager-api请求失败,状态码: {response.status_code}"
|
||||
try:
|
||||
error_data = response.json()
|
||||
if "msg" in error_data:
|
||||
error_msg = f"{error_msg}, 错误信息: {error_data['msg']}"
|
||||
except:
|
||||
error_msg = f"{error_msg}, 响应内容: {response.text}"
|
||||
|
||||
return result.get("data")
|
||||
if attempt < max_retries - 1:
|
||||
print(f"请求manager-api失败,正在重试 ({attempt + 1}/{max_retries})...")
|
||||
time.sleep(retry_delay)
|
||||
else:
|
||||
raise Exception(error_msg)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if attempt < max_retries - 1:
|
||||
print(f"请求manager-api异常,正在重试 ({attempt + 1}/{max_retries})...")
|
||||
time.sleep(retry_delay)
|
||||
else:
|
||||
raise Exception(f"manager-api请求异常: {str(e)}")
|
||||
|
||||
|
||||
def get_config_from_api(config):
|
||||
|
|
@ -117,7 +134,12 @@ def get_private_config_from_api(config, device_id, client_id):
|
|||
api_url,
|
||||
secret,
|
||||
"/config/agent-models",
|
||||
{"secret": secret, "macAddress": device_id, "clientId": client_id},
|
||||
{
|
||||
"secret": secret,
|
||||
"macAddress": device_id,
|
||||
"clientId": client_id,
|
||||
"selectedModule": config["selected_module"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -206,6 +206,8 @@ class ConnectionHandler:
|
|||
self.headers.get("device-id", None),
|
||||
self.headers.get("client-id", None),
|
||||
)
|
||||
private_config["delete_audio"] = self.config["delete_audio"]
|
||||
self.logger.bind(tag=TAG).info(f"获取差异化配置成功: {private_config}")
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
|
||||
private_config = {}
|
||||
|
|
@ -218,29 +220,58 @@ class ConnectionHandler:
|
|||
False,
|
||||
False,
|
||||
)
|
||||
if private_config.get("vad", None) is not None:
|
||||
if private_config.get("VAD", None) is not None:
|
||||
init_vad = True
|
||||
if private_config.get("asr", None) is not None:
|
||||
self.config["vad"] = private_config["VAD"]
|
||||
self.config["selected_module"]["VAD"] = private_config["selected_module"][
|
||||
"VAD"
|
||||
]
|
||||
if private_config.get("ASR", None) is not None:
|
||||
init_asr = True
|
||||
if private_config.get("llm", None) is not None:
|
||||
self.config["asr"] = private_config["ASR"]
|
||||
self.config["selected_module"]["ASR"] = private_config["selected_module"][
|
||||
"ASR"
|
||||
]
|
||||
if private_config.get("LLM", None) is not None:
|
||||
init_llm = True
|
||||
if private_config.get("tts", None) is not None:
|
||||
self.config["llm"] = private_config["LLM"]
|
||||
self.config["selected_module"]["LLM"] = private_config["selected_module"][
|
||||
"LLM"
|
||||
]
|
||||
if private_config.get("TTS", None) is not None:
|
||||
init_tts = True
|
||||
if private_config.get("memory", None) is not None:
|
||||
self.config["tts"] = private_config["TTS"]
|
||||
self.config["selected_module"]["TTS"] = private_config["selected_module"][
|
||||
"TTS"
|
||||
]
|
||||
if private_config.get("Memory", None) is not None:
|
||||
init_memory = True
|
||||
if private_config.get("intent", None) is not None:
|
||||
self.config["memory"] = private_config["Memory"]
|
||||
self.config["selected_module"]["Memory"] = private_config[
|
||||
"selected_module"
|
||||
]["Memory"]
|
||||
if private_config.get("Intent", None) is not None:
|
||||
init_intent = True
|
||||
|
||||
modules = initialize_modules(
|
||||
self.logger,
|
||||
private_config,
|
||||
init_vad,
|
||||
init_asr,
|
||||
init_llm,
|
||||
init_tts,
|
||||
init_memory,
|
||||
init_intent,
|
||||
)
|
||||
self.config["intent"] = private_config["Intent"]
|
||||
self.config["selected_module"]["Intent"] = private_config[
|
||||
"selected_module"
|
||||
]["Intent"]
|
||||
if private_config.get("prompt", None) is not None:
|
||||
self.config["prompt"] = private_config["prompt"]
|
||||
try:
|
||||
modules = initialize_modules(
|
||||
self.logger,
|
||||
private_config,
|
||||
init_vad,
|
||||
init_asr,
|
||||
init_llm,
|
||||
init_tts,
|
||||
init_memory,
|
||||
init_intent,
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
|
||||
modules = {}
|
||||
if modules.get("tts", None) is not None:
|
||||
self.tts = modules["tts"]
|
||||
if modules.get("llm", None) is not None:
|
||||
|
|
|
|||
Loading…
Reference in a new issue