update:加载私有模型配置

This commit is contained in:
hrz 2025-04-12 17:31:10 +08:00
parent c5ea1da95b
commit d9371fa185
10 changed files with 181 additions and 40 deletions

View file

@ -68,4 +68,11 @@ public class RedisKeys {
public static String getServerConfigKey() { public static String getServerConfigKey() {
return "server:config"; return "server:config";
} }
/**
* 获取音色详情缓存key
*/
public static String getTimbreDetailsKey(String id) {
return "timbre:details:" + id;
}
} }

View file

@ -47,7 +47,7 @@ public class ConfigController {
// 效验数据 // 效验数据
ValidatorUtils.validateEntity(dto); ValidatorUtils.validateEntity(dto);
checkSecret(dto.getSecret()); checkSecret(dto.getSecret());
Object models = configService.getAgentModels(dto.getMacAddress()); Object models = configService.getAgentModels(dto.getMacAddress(), dto.getSelectedModule());
return new Result<Object>().ok(models); return new Result<Object>().ok(models);
} }

View file

@ -1,7 +1,10 @@
package xiaozhi.modules.config.dto; package xiaozhi.modules.config.dto;
import java.util.Map;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data; import lombok.Data;
@Data @Data
@ -18,4 +21,8 @@ public class AgentModelsDTO {
@NotBlank(message = "客户端ID不能为空") @NotBlank(message = "客户端ID不能为空")
@Schema(description = "客户端ID") @Schema(description = "客户端ID")
private String clientId; private String clientId;
@NotNull(message = "客户端已实例化的模型不能为空")
@Schema(description = "客户端已实例化的模型")
private Map<String, String> selectedModule;
} }

View file

@ -14,8 +14,9 @@ public interface ConfigService {
/** /**
* 获取智能体模型配置 * 获取智能体模型配置
* *
* @param macAddress MAC地址 * @param macAddress MAC地址
* @param selectedModule 客户端已实例化的模型
* @return 模型配置信息 * @return 模型配置信息
*/ */
Map<String, Object> getAgentModels(String macAddress); Map<String, Object> getAgentModels(String macAddress, Map<String, String> selectedModule);
} }

View file

@ -24,6 +24,8 @@ import xiaozhi.modules.model.entity.ModelConfigEntity;
import xiaozhi.modules.model.service.ModelConfigService; import xiaozhi.modules.model.service.ModelConfigService;
import xiaozhi.modules.sys.dto.SysParamsDTO; import xiaozhi.modules.sys.dto.SysParamsDTO;
import xiaozhi.modules.sys.service.SysParamsService; import xiaozhi.modules.sys.service.SysParamsService;
import xiaozhi.modules.timbre.service.TimbreService;
import xiaozhi.modules.timbre.vo.TimbreDetailsVO;
@Service @Service
@AllArgsConstructor @AllArgsConstructor
@ -34,6 +36,7 @@ public class ConfigServiceImpl implements ConfigService {
private final AgentService agentService; private final AgentService agentService;
private final AgentTemplateService agentTemplateService; private final AgentTemplateService agentTemplateService;
private final RedisUtils redisUtils; private final RedisUtils redisUtils;
private final TimbreService timbreService;
@Override @Override
public Object getConfig(Boolean isCache) { public Object getConfig(Boolean isCache) {
@ -58,6 +61,7 @@ public class ConfigServiceImpl implements ConfigService {
// 构建模块配置 // 构建模块配置
buildModuleConfig( buildModuleConfig(
agent.getSystemPrompt(), agent.getSystemPrompt(),
null,
agent.getVadModelId(), agent.getVadModelId(),
agent.getAsrModelId(), agent.getAsrModelId(),
agent.getLlmModelId(), agent.getLlmModelId(),
@ -74,7 +78,7 @@ public class ConfigServiceImpl implements ConfigService {
} }
@Override @Override
public Map<String, Object> getAgentModels(String macAddress) { public Map<String, Object> getAgentModels(String macAddress, Map<String, String> selectedModule) {
// 根据MAC地址查找设备 // 根据MAC地址查找设备
DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress); DeviceEntity device = deviceService.getDeviceByMacAddress(macAddress);
if (device == null) { if (device == null) {
@ -85,12 +89,41 @@ public class ConfigServiceImpl implements ConfigService {
if (agent == null) { if (agent == null) {
throw new RenException("智能体未找到"); throw new RenException("智能体未找到");
} }
// 获取音色信息
String voice = null;
TimbreDetailsVO timbre = timbreService.get(agent.getTtsVoiceId());
if (timbre != null) {
voice = timbre.getTtsVoice();
}
// 构建返回数据 // 构建返回数据
Map<String, Object> result = new HashMap<>(); 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( buildModuleConfig(
agent.getSystemPrompt(), agent.getSystemPrompt(),
voice,
agent.getVadModelId(), agent.getVadModelId(),
agent.getAsrModelId(), agent.getAsrModelId(),
agent.getLlmModelId(), agent.getLlmModelId(),
@ -172,6 +205,8 @@ public class ConfigServiceImpl implements ConfigService {
/** /**
* 构建模块配置 * 构建模块配置
* *
* @param prompt 提示词
* @param voice 音色
* @param vadModelId VAD模型ID * @param vadModelId VAD模型ID
* @param asrModelId ASR模型ID * @param asrModelId ASR模型ID
* @param llmModelId LLM模型ID * @param llmModelId LLM模型ID
@ -182,6 +217,7 @@ public class ConfigServiceImpl implements ConfigService {
*/ */
private void buildModuleConfig( private void buildModuleConfig(
String prompt, String prompt,
String voice,
String vadModelId, String vadModelId,
String asrModelId, String asrModelId,
String llmModelId, String llmModelId,
@ -196,11 +232,20 @@ public class ConfigServiceImpl implements ConfigService {
String[] modelIds = { vadModelId, asrModelId, llmModelId, ttsModelId, memModelId, intentModelId }; String[] modelIds = { vadModelId, asrModelId, llmModelId, ttsModelId, memModelId, intentModelId };
for (int i = 0; i < modelIds.length; i++) { for (int i = 0; i < modelIds.length; i++) {
if (modelIds[i] == null) {
continue;
}
ModelConfigEntity model = modelConfigService.getModelById(modelIds[i], isCache); ModelConfigEntity model = modelConfigService.getModelById(modelIds[i], isCache);
Map<String, Object> typeConfig = new HashMap<>(); 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); result.put(modelTypes[i], typeConfig);
selectedModule.put(modelTypes[i], model.getModelCode()); selectedModule.put(modelTypes[i], model.getId());
} }
result.put("selected_module", selectedModule); result.put("selected_module", selectedModule);
result.put("prompt", prompt); result.put("prompt", prompt);

View file

@ -94,6 +94,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
modelConfigEntity.setId(id); modelConfigEntity.setId(id);
modelConfigEntity.setModelType(modelType); modelConfigEntity.setModelType(modelType);
modelConfigDao.updateById(modelConfigEntity); modelConfigDao.updateById(modelConfigEntity);
// 清除缓存
redisUtils.delete(RedisKeys.getModelConfigById(modelConfigEntity.getId()));
return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class); return ConvertUtils.sourceToTarget(modelConfigEntity, ModelConfigDTO.class);
} }

View file

@ -31,7 +31,7 @@ public interface TimbreService extends BaseService<TimbreEntity> {
* @param timbreId 音色表id * @param timbreId 音色表id
* @return 音色信息 * @return 音色信息
*/ */
TimbreDetailsVO get(Long timbreId); TimbreDetailsVO get(String timbreId);
/** /**
* 保存音色信息 * 保存音色信息

View file

@ -59,9 +59,33 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
} }
@Override @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); 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 @Override
@ -79,6 +103,8 @@ public class TimbreServiceImpl extends BaseServiceImpl<TimbreDao, TimbreEntity>
TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class); TimbreEntity timbreEntity = ConvertUtils.sourceToTarget(dto, TimbreEntity.class);
timbreEntity.setId(timbreId); timbreEntity.setId(timbreId);
baseDao.updateById(timbreEntity); baseDao.updateById(timbreEntity);
// 删除缓存
redisUtils.delete(RedisKeys.getTimbreDetailsKey(timbreId));
} }
@Override @Override

View file

@ -2,6 +2,7 @@ import os
import argparse import argparse
import requests import requests
import yaml import yaml
import time
# 添加全局配置缓存 # 添加全局配置缓存
_config_cache = None _config_cache = None
@ -74,22 +75,38 @@ def _make_api_request(api_url, secret, endpoint, json_data=None):
if "你" in secret: if "你" in secret:
raise Exception("请先配置manager-api的secret") raise Exception("请先配置manager-api的secret")
response = requests.post(f"{api_url}{endpoint}", json=json_data) max_retries = 10
if response.status_code != 200: retry_delay = 2 # 秒
error_msg = f"API请求失败,状态码: {response.status_code}"
for attempt in range(max_retries):
try: try:
error_data = response.json() response = requests.post(f"{api_url}{endpoint}", json=json_data)
if "msg" in error_data: if response.status_code == 200:
error_msg = f"{error_msg}, 错误信息: {error_data['msg']}" result = response.json()
except: if result.get("code") != 0:
error_msg = f"{error_msg}, 响应内容: {response.text}" raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
raise Exception(error_msg) return result.get("data")
result = response.json() error_msg = f"manager-api请求失败,状态码: {response.status_code}"
if result.get("code") != 0: try:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") 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): def get_config_from_api(config):
@ -117,7 +134,12 @@ def get_private_config_from_api(config, device_id, client_id):
api_url, api_url,
secret, secret,
"/config/agent-models", "/config/agent-models",
{"secret": secret, "macAddress": device_id, "clientId": client_id}, {
"secret": secret,
"macAddress": device_id,
"clientId": client_id,
"selectedModule": config["selected_module"],
},
) )

View file

@ -206,6 +206,8 @@ class ConnectionHandler:
self.headers.get("device-id", None), self.headers.get("device-id", None),
self.headers.get("client-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: except Exception as e:
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}") self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
private_config = {} private_config = {}
@ -218,29 +220,58 @@ class ConnectionHandler:
False, False,
False, False,
) )
if private_config.get("vad", None) is not None: if private_config.get("VAD", None) is not None:
init_vad = True 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 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 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 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 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 init_intent = True
self.config["intent"] = private_config["Intent"]
modules = initialize_modules( self.config["selected_module"]["Intent"] = private_config[
self.logger, "selected_module"
private_config, ]["Intent"]
init_vad, if private_config.get("prompt", None) is not None:
init_asr, self.config["prompt"] = private_config["prompt"]
init_llm, try:
init_tts, modules = initialize_modules(
init_memory, self.logger,
init_intent, 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: if modules.get("tts", None) is not None:
self.tts = modules["tts"] self.tts = modules["tts"]
if modules.get("llm", None) is not None: if modules.get("llm", None) is not None: