update:优化私有配置加载

This commit is contained in:
hrz 2025-04-11 23:12:23 +08:00
parent 667b453a8c
commit c5ea1da95b
19 changed files with 248 additions and 118 deletions

View file

@ -17,4 +17,12 @@ public interface AgentTemplateService extends IService<AgentTemplateEntity> {
* @return 默认模板实体 * @return 默认模板实体
*/ */
AgentTemplateEntity getDefaultTemplate(); AgentTemplateEntity getDefaultTemplate();
/**
* 更新默认模板中的模型ID
*
* @param modelType 模型类型
* @param modelId 模型ID
*/
void updateDefaultTemplateModelId(String modelType, String modelId);
} }

View file

@ -29,4 +29,39 @@ public class AgentTemplateServiceImpl extends ServiceImpl<AgentTemplateDao, Agen
.last("LIMIT 1"); .last("LIMIT 1");
return this.getOne(wrapper); return this.getOne(wrapper);
} }
/**
* 更新默认模板中的模型ID
*
* @param modelType 模型类型
* @param modelId 模型ID
*/
@Override
public void updateDefaultTemplateModelId(String modelType, String modelId) {
modelType = modelType.toUpperCase();
AgentTemplateEntity defaultTemplate = getDefaultTemplate();
if (defaultTemplate != null) {
switch (modelType) {
case "ASR":
defaultTemplate.setAsrModelId(modelId);
break;
case "VAD":
defaultTemplate.setVadModelId(modelId);
break;
case "LLM":
defaultTemplate.setLlmModelId(modelId);
break;
case "TTS":
defaultTemplate.setTtsModelId(modelId);
break;
case "Memory":
defaultTemplate.setMemModelId(modelId);
break;
case "Intent":
defaultTemplate.setIntentModelId(modelId);
break;
}
this.updateById(defaultTemplate);
}
}
} }

View file

@ -64,7 +64,8 @@ public class ConfigServiceImpl implements ConfigService {
agent.getTtsModelId(), agent.getTtsModelId(),
agent.getMemModelId(), agent.getMemModelId(),
agent.getIntentModelId(), agent.getIntentModelId(),
result); result,
isCache);
// 将配置存入Redis // 将配置存入Redis
redisUtils.set(RedisKeys.getServerConfigKey(), result); redisUtils.set(RedisKeys.getServerConfigKey(), result);
@ -96,7 +97,8 @@ public class ConfigServiceImpl implements ConfigService {
agent.getTtsModelId(), agent.getTtsModelId(),
agent.getMemModelId(), agent.getMemModelId(),
agent.getIntentModelId(), agent.getIntentModelId(),
result); result,
true);
return result; return result;
} }
@ -186,14 +188,15 @@ public class ConfigServiceImpl implements ConfigService {
String ttsModelId, String ttsModelId,
String memModelId, String memModelId,
String intentModelId, String intentModelId,
Map<String, Object> result) { Map<String, Object> result,
boolean isCache) {
Map<String, String> selectedModule = new HashMap<>(); Map<String, String> selectedModule = new HashMap<>();
String[] modelTypes = { "VAD", "ASR", "LLM", "TTS", "Memory", "Intent" }; String[] modelTypes = { "VAD", "ASR", "LLM", "TTS", "Memory", "Intent" };
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++) {
ModelConfigEntity model = modelConfigService.getModelById(modelIds[i]); 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()); typeConfig.put(model.getModelCode(), model.getConfigJson());
result.put(modelTypes[i], typeConfig); result.put(modelTypes[i], typeConfig);

View file

@ -19,6 +19,8 @@ import lombok.AllArgsConstructor;
import xiaozhi.common.page.PageData; import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.ConvertUtils; import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.common.utils.Result; import xiaozhi.common.utils.Result;
import xiaozhi.modules.agent.service.AgentTemplateService;
import xiaozhi.modules.config.service.ConfigService;
import xiaozhi.modules.model.dto.ModelBasicInfoDTO; import xiaozhi.modules.model.dto.ModelBasicInfoDTO;
import xiaozhi.modules.model.dto.ModelConfigBodyDTO; import xiaozhi.modules.model.dto.ModelConfigBodyDTO;
import xiaozhi.modules.model.dto.ModelConfigDTO; import xiaozhi.modules.model.dto.ModelConfigDTO;
@ -38,6 +40,8 @@ public class ModelController {
private final ModelProviderService modelProviderService; private final ModelProviderService modelProviderService;
private final TimbreService timbreService; private final TimbreService timbreService;
private final ModelConfigService modelConfigService; private final ModelConfigService modelConfigService;
private final ConfigService configService;
private final AgentTemplateService agentTemplateService;
@GetMapping("/names") @GetMapping("/names")
@Operation(summary = "获取所有模型名称") @Operation(summary = "获取所有模型名称")
@ -75,6 +79,7 @@ public class ModelController {
@PathVariable String provideCode, @PathVariable String provideCode,
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) { @RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO); ModelConfigDTO modelConfigDTO = modelConfigService.add(modelType, provideCode, modelConfigBodyDTO);
configService.getConfig(false);
return new Result<ModelConfigDTO>().ok(modelConfigDTO); return new Result<ModelConfigDTO>().ok(modelConfigDTO);
} }
@ -86,6 +91,7 @@ public class ModelController {
@PathVariable String id, @PathVariable String id,
@RequestBody ModelConfigBodyDTO modelConfigBodyDTO) { @RequestBody ModelConfigBodyDTO modelConfigBodyDTO) {
ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO); ModelConfigDTO modelConfigDTO = modelConfigService.edit(modelType, provideCode, id, modelConfigBodyDTO);
configService.getConfig(false);
return new Result<ModelConfigDTO>().ok(modelConfigDTO); return new Result<ModelConfigDTO>().ok(modelConfigDTO);
} }
@ -131,6 +137,11 @@ public class ModelController {
modelConfigService.setDefaultModel(entity.getModelType(), 0); modelConfigService.setDefaultModel(entity.getModelType(), 0);
entity.setIsDefault(1); entity.setIsDefault(1);
modelConfigService.updateById(entity); modelConfigService.updateById(entity);
// 更新模板表中对应的模型ID
agentTemplateService.updateDefaultTemplateModelId(entity.getModelType(), entity.getId());
configService.getConfig(false);
return new Result<Void>(); return new Result<Void>();
} }

View file

@ -33,9 +33,10 @@ public interface ModelConfigService extends BaseService<ModelConfigEntity> {
* 根据ID获取模型配置 * 根据ID获取模型配置
* *
* @param id 模型ID * @param id 模型ID
* @param isCache 是否缓存
* @return 模型配置实体 * @return 模型配置实体
*/ */
ModelConfigEntity getModelById(String id); ModelConfigEntity getModelById(String id, boolean isCache);
/** /**
* 设置默认模型 * 设置默认模型

View file

@ -127,14 +127,16 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
} }
@Override @Override
public ModelConfigEntity getModelById(String id) { public ModelConfigEntity getModelById(String id, boolean isCache) {
if (StringUtils.isBlank(id)) { if (StringUtils.isBlank(id)) {
return null; return null;
} }
if (isCache) {
ModelConfigEntity cachedConfig = (ModelConfigEntity) redisUtils.get(RedisKeys.getModelConfigById(id)); ModelConfigEntity cachedConfig = (ModelConfigEntity) redisUtils.get(RedisKeys.getModelConfigById(id));
if (cachedConfig != null) { if (cachedConfig != null) {
return ConvertUtils.sourceToTarget(cachedConfig, ModelConfigEntity.class); return ConvertUtils.sourceToTarget(cachedConfig, ModelConfigEntity.class);
} }
}
ModelConfigEntity entity = modelConfigDao.selectById(id); ModelConfigEntity entity = modelConfigDao.selectById(id);
if (entity != null) { if (entity != null) {
redisUtils.set(RedisKeys.getModelConfigById(id), entity); redisUtils.set(RedisKeys.getModelConfigById(id), entity);

View file

@ -10,18 +10,19 @@ INSERT INTO `ai_model_config` VALUES ('VAD_SileroVAD', 'VAD', 'SileroVAD', '语
INSERT INTO `ai_model_config` VALUES ('ASR_FunASR', 'ASR', 'FunASR', 'FunASR语音识别', 1, 1, '{\"type\": \"fun_local\", \"model_dir\": \"models/SenseVoiceSmall\", \"output_dir\": \"tmp/\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('ASR_FunASR', 'ASR', 'FunASR', 'FunASR语音识别', 1, 1, '{\"type\": \"fun_local\", \"model_dir\": \"models/SenseVoiceSmall\", \"output_dir\": \"tmp/\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('ASR_SherpaASR', 'ASR', 'SherpaASR', 'Sherpa语音识别', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17\", \"output_dir\": \"tmp/\"}', NULL, NULL, 2, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('ASR_SherpaASR', 'ASR', 'SherpaASR', 'Sherpa语音识别', 0, 1, '{\"type\": \"sherpa_onnx_local\", \"model_dir\": \"models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17\", \"output_dir\": \"tmp/\"}', NULL, NULL, 2, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('ASR_DoubaoASR', 'ASR', 'DoubaoASR', '豆包语音识别', 0, 1, '{\"type\": \"doubao\", \"appid\": \"\", \"access_token\": \"\", \"cluster\": \"volcengine_input_common\", \"output_dir\": \"tmp/\"}', NULL, NULL, 3, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('ASR_DoubaoASR', 'ASR', 'DoubaoASR', '豆包语音识别', 0, 1, '{\"type\": \"doubao\", \"appid\": \"\", \"access_token\": \"\", \"cluster\": \"volcengine_input_common\", \"output_dir\": \"tmp/\"}', NULL, NULL, 3, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('ASR_TencentASR', 'ASR', 'TencentASR', '腾讯语音识别', 0, 1, '{\"type\": \"tencent\", \"appid\": \"\", \"secret_id\": \"\", \"secret_key\": \"你的secret_key\", \"output_dir\": \"tmp/\"}', NULL, NULL, 4, NULL, NULL, NULL, NULL);
-- LLM模型配置 -- LLM模型配置
INSERT INTO `ai_model_config` VALUES ('LLM_ChatGLMLLM', 'LLM', 'ChatGLMLLM', '智谱AI', 1, 1, '{\"type\": \"openai\", \"model_name\": \"glm-4-flash\", \"url\": \"https://open.bigmodel.cn/api/paas/v4/\", \"api_key\": \"\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_ChatGLMLLM', 'LLM', 'ChatGLMLLM', '智谱AI', 1, 1, '{\"type\": \"openai\", \"model_name\": \"glm-4-flash\", \"base_url\": \"https://open.bigmodel.cn/api/paas/v4/\", \"api_key\": \"你的api_key\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_OllamaLLM', 'LLM', 'OllamaLLM', 'Ollama本地模型', 0, 1, '{\"type\": \"ollama\", \"model_name\": \"qwen2.5\", \"base_url\": \"http://localhost:11434\"}', NULL, NULL, 2, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_OllamaLLM', 'LLM', 'OllamaLLM', 'Ollama本地模型', 0, 1, '{\"type\": \"ollama\", \"model_name\": \"qwen2.5\", \"base_url\": \"http://localhost:11434\"}', NULL, NULL, 2, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_AliLLM', 'LLM', 'AliLLM', '通义千问', 0, 1, '{\"type\": \"openai\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"model_name\": \"qwen-turbo\", \"api_key\": \"\", \"temperature\": 0.7, \"max_tokens\": 500, \"top_p\": 1, \"top_k\": 50, \"frequency_penalty\": 0}', NULL, NULL, 3, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_AliLLM', 'LLM', 'AliLLM', '通义千问', 0, 1, '{\"type\": \"openai\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"model_name\": \"qwen-turbo\", \"api_key\": \"你的api_key\", \"temperature\": 0.7, \"max_tokens\": 500, \"top_p\": 1, \"top_k\": 50, \"frequency_penalty\": 0}', NULL, NULL, 3, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_AliAppLLM', 'LLM', 'AliAppLLM', '通义百炼', 0, 1, '{\"type\": \"AliBL\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"app_id\": \"\", \"api_key\": \"\", \"is_no_prompt\": true, \"ali_memory_id\": false}', NULL, NULL, 4, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_AliAppLLM', 'LLM', 'AliAppLLM', '通义百炼', 0, 1, '{\"type\": \"AliBL\", \"base_url\": \"https://dashscope.aliyuncs.com/compatible-mode/v1\", \"app_id\": \"你的app_id\", \"api_key\": \"你的api_key\", \"is_no_prompt\": true, \"ali_memory_id\": false}', NULL, NULL, 4, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_DoubaoLLM', 'LLM', 'DoubaoLLM', '豆包大模型', 0, 1, '{\"type\": \"openai\", \"base_url\": \"https://ark.cn-beijing.volces.com/api/v3\", \"model_name\": \"doubao-pro-32k-functioncall-241028\", \"api_key\": \"\"}', NULL, NULL, 5, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_DoubaoLLM', 'LLM', 'DoubaoLLM', '豆包大模型', 0, 1, '{\"type\": \"openai\", \"base_url\": \"https://ark.cn-beijing.volces.com/api/v3\", \"model_name\": \"doubao-pro-32k-functioncall-241028\", \"api_key\": \"你的api_key\"}', NULL, NULL, 5, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_DeepSeekLLM', 'LLM', 'DeepSeekLLM', 'DeepSeek', 0, 1, '{\"type\": \"openai\", \"model_name\": \"deepseek-chat\", \"url\": \"https://api.deepseek.com\", \"api_key\": \"\"}', NULL, NULL, 6, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_DeepSeekLLM', 'LLM', 'DeepSeekLLM', 'DeepSeek', 0, 1, '{\"type\": \"openai\", \"model_name\": \"deepseek-chat\", \"base_url\": \"https://api.deepseek.com\", \"api_key\": \"你的api_key\"}', NULL, NULL, 6, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_DifyLLM', 'LLM', 'DifyLLM', 'Dify', 0, 1, '{\"type\": \"dify\", \"base_url\": \"https://api.dify.ai/v1\", \"api_key\": \"\", \"mode\": \"chat-messages\"}', NULL, NULL, 7, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_DifyLLM', 'LLM', 'DifyLLM', 'Dify', 0, 1, '{\"type\": \"dify\", \"base_url\": \"https://api.dify.ai/v1\", \"api_key\": \"你的api_key\", \"mode\": \"chat-messages\"}', NULL, NULL, 7, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_GeminiLLM', 'LLM', 'GeminiLLM', '谷歌Gemini', 0, 1, '{\"type\": \"gemini\", \"api_key\": \"\", \"model_name\": \"gemini-2.0-flash\", \"http_proxy\": \"\", \"https_proxy\": \"\"}', NULL, NULL, 8, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_GeminiLLM', 'LLM', 'GeminiLLM', '谷歌Gemini', 0, 1, '{\"type\": \"gemini\", \"api_key\": \"你的api_key\", \"model_name\": \"gemini-2.0-flash\", \"http_proxy\": \"\", \"https_proxy\": \"\"}', NULL, NULL, 8, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_CozeLLM', 'LLM', 'CozeLLM', 'Coze', 0, 1, '{\"type\": \"coze\", \"bot_id\": \"\", \"user_id\": \"\", \"personal_access_token\": \"\"}', NULL, NULL, 9, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_CozeLLM', 'LLM', 'CozeLLM', 'Coze', 0, 1, '{\"type\": \"coze\", \"bot_id\": \"你的bot_id\", \"user_id\": \"你的user_id\", \"personal_access_token\": \"你的personal_access_token\"}', NULL, NULL, 9, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_LMStudioLLM', 'LLM', 'LMStudioLLM', 'LM Studio', 0, 1, '{\"type\": \"openai\", \"model_name\": \"deepseek-r1-distill-llama-8b@q4_k_m\", \"url\": \"http://localhost:1234/v1\", \"api_key\": \"lm-studio\"}', NULL, NULL, 10, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_LMStudioLLM', 'LLM', 'LMStudioLLM', 'LM Studio', 0, 1, '{\"type\": \"openai\", \"model_name\": \"deepseek-r1-distill-llama-8b@q4_k_m\", \"base_url\": \"http://localhost:1234/v1\", \"api_key\": \"lm-studio\"}', NULL, NULL, 10, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_FastgptLLM', 'LLM', 'FastgptLLM', 'FastGPT', 0, 1, '{\"type\": \"fastgpt\", \"base_url\": \"https://host/api/v1\", \"api_key\": \"fastgpt-xxx\", \"variables\": {\"k\": \"v\", \"k2\": \"v2\"}}', NULL, NULL, 11, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_FastgptLLM', 'LLM', 'FastgptLLM', 'FastGPT', 0, 1, '{\"type\": \"fastgpt\", \"base_url\": \"https://host/api/v1\", \"api_key\": \"fastgpt-xxx\", \"variables\": {\"k\": \"v\", \"k2\": \"v2\"}}', NULL, NULL, 11, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceLLM', 'LLM', 'XinferenceLLM', 'Xinference大模型', 0, 1, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:72b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 12, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceLLM', 'LLM', 'XinferenceLLM', 'Xinference大模型', 0, 1, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:72b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 12, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceSmallLLM', 'LLM', 'XinferenceSmallLLM', 'Xinference小模型', 0, 1, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:3b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 13, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('LLM_XinferenceSmallLLM', 'LLM', 'XinferenceSmallLLM', 'Xinference小模型', 0, 1, '{\"type\": \"xinference\", \"model_name\": \"qwen2.5:3b-AWQ\", \"base_url\": \"http://localhost:9997\"}', NULL, NULL, 13, NULL, NULL, NULL, NULL);
@ -34,18 +35,19 @@ INSERT INTO `ai_model_config` VALUES ('TTS_CozeCnTTS', 'TTS', 'CozeCnTTS', 'Coze
INSERT INTO `ai_model_config` VALUES ('TTS_FishSpeech', 'TTS', 'FishSpeech', 'FishSpeech语音合成', 0, 1, '{\"type\": \"fishspeech\", \"output_dir\": \"tmp/\", \"response_format\": \"wav\", \"reference_id\": null, \"reference_audio\": [\"/tmp/test.wav\"], \"reference_text\": [\"你弄来这些吟词宴曲来看,还是这些混话来欺负我。\"], \"normalize\": true, \"max_new_tokens\": 1024, \"chunk_length\": 200, \"top_p\": 0.7, \"repetition_penalty\": 1.2, \"temperature\": 0.7, \"streaming\": false, \"use_memory_cache\": \"on\", \"seed\": null, \"channels\": 1, \"rate\": 44100, \"api_key\": \"\", \"api_url\": \"http://127.0.0.1:8080/v1/tts\"}', NULL, NULL, 5, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_FishSpeech', 'TTS', 'FishSpeech', 'FishSpeech语音合成', 0, 1, '{\"type\": \"fishspeech\", \"output_dir\": \"tmp/\", \"response_format\": \"wav\", \"reference_id\": null, \"reference_audio\": [\"/tmp/test.wav\"], \"reference_text\": [\"你弄来这些吟词宴曲来看,还是这些混话来欺负我。\"], \"normalize\": true, \"max_new_tokens\": 1024, \"chunk_length\": 200, \"top_p\": 0.7, \"repetition_penalty\": 1.2, \"temperature\": 0.7, \"streaming\": false, \"use_memory_cache\": \"on\", \"seed\": null, \"channels\": 1, \"rate\": 44100, \"api_key\": \"\", \"api_url\": \"http://127.0.0.1:8080/v1/tts\"}', NULL, NULL, 5, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V2', 'TTS', 'GPT_SOVITS_V2', 'GPT-SoVITS V2', 0, 1, '{\"type\": \"gpt_sovits_v2\", \"url\": \"http://127.0.0.1:9880/tts\", \"output_dir\": \"tmp/\", \"text_lang\": \"auto\", \"ref_audio_path\": \"caixukun.wav\", \"prompt_text\": \"\", \"prompt_lang\": \"zh\", \"top_k\": 5, \"top_p\": 1, \"temperature\": 1, \"text_split_method\": \"cut0\", \"batch_size\": 1, \"batch_threshold\": 0.75, \"split_bucket\": true, \"return_fragment\": false, \"speed_factor\": 1.0, \"streaming_mode\": false, \"seed\": -1, \"parallel_infer\": true, \"repetition_penalty\": 1.35, \"aux_ref_audio_paths\": []}', NULL, NULL, 6, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V2', 'TTS', 'GPT_SOVITS_V2', 'GPT-SoVITS V2', 0, 1, '{\"type\": \"gpt_sovits_v2\", \"url\": \"http://127.0.0.1:9880/tts\", \"output_dir\": \"tmp/\", \"text_lang\": \"auto\", \"ref_audio_path\": \"caixukun.wav\", \"prompt_text\": \"\", \"prompt_lang\": \"zh\", \"top_k\": 5, \"top_p\": 1, \"temperature\": 1, \"text_split_method\": \"cut0\", \"batch_size\": 1, \"batch_threshold\": 0.75, \"split_bucket\": true, \"return_fragment\": false, \"speed_factor\": 1.0, \"streaming_mode\": false, \"seed\": -1, \"parallel_infer\": true, \"repetition_penalty\": 1.35, \"aux_ref_audio_paths\": []}', NULL, NULL, 6, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V3', 'TTS', 'GPT_SOVITS_V3', 'GPT-SoVITS V3', 0, 1, '{\"type\": \"gpt_sovits_v3\", \"url\": \"http://127.0.0.1:9880\", \"output_dir\": \"tmp/\", \"text_language\": \"auto\", \"refer_wav_path\": \"caixukun.wav\", \"prompt_language\": \"zh\", \"prompt_text\": \"\", \"top_k\": 15, \"top_p\": 1.0, \"temperature\": 1.0, \"cut_punc\": \"\", \"speed\": 1.0, \"inp_refs\": [], \"sample_steps\": 32, \"if_sr\": false}', NULL, NULL, 7, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_GPT_SOVITS_V3', 'TTS', 'GPT_SOVITS_V3', 'GPT-SoVITS V3', 0, 1, '{\"type\": \"gpt_sovits_v3\", \"url\": \"http://127.0.0.1:9880\", \"output_dir\": \"tmp/\", \"text_language\": \"auto\", \"refer_wav_path\": \"caixukun.wav\", \"prompt_language\": \"zh\", \"prompt_text\": \"\", \"top_k\": 15, \"top_p\": 1.0, \"temperature\": 1.0, \"cut_punc\": \"\", \"speed\": 1.0, \"inp_refs\": [], \"sample_steps\": 32, \"if_sr\": false}', NULL, NULL, 7, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_MinimaxTTS', 'TTS', 'MinimaxTTS', 'MiniMax语音合成', 0, 1, '{\"type\": \"minimax\", \"output_dir\": \"tmp/\", \"group_id\": \"\", \"api_key\": \"\", \"model\": \"speech-01-turbo\", \"voice_id\": \"female-shaonv\"}', NULL, NULL, 8, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_MinimaxTTS', 'TTS', 'MinimaxTTS', 'MiniMax语音合成', 0, 1, '{\"type\": \"minimax\", \"output_dir\": \"tmp/\", \"group_id\": \"\", \"api_key\": \"你的api_key\", \"model\": \"speech-01-turbo\", \"voice_id\": \"female-shaonv\"}', NULL, NULL, 8, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_AliyunTTS', 'TTS', 'AliyunTTS', '阿里云语音合成', 0, 1, '{\"type\": \"aliyun\", \"output_dir\": \"tmp/\", \"appkey\": \"\", \"token\": \"\", \"voice\": \"xiaoyun\", \"access_key_id\": \"\", \"access_key_secret\": \"\"}', NULL, NULL, 9, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_AliyunTTS', 'TTS', 'AliyunTTS', '阿里云语音合成', 0, 1, '{\"type\": \"aliyun\", \"output_dir\": \"tmp/\", \"appkey\": \"\", \"token\": \"\", \"voice\": \"xiaoyun\", \"access_key_id\": \"\", \"access_key_secret\": \"\"}', NULL, NULL, 9, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_TTS302AI', 'TTS', 'TTS302AI', '302AI语音合成', 0, 1, '{\"type\": \"doubao\", \"api_url\": \"https://api.302ai.cn/doubao/tts_hd\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 10, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_TTS302AI', 'TTS', 'TTS302AI', '302AI语音合成', 0, 1, '{\"type\": \"doubao\", \"api_url\": \"https://api.302ai.cn/doubao/tts_hd\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 10, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_GizwitsTTS', 'TTS', 'GizwitsTTS', '机智云语音合成', 0, 1, '{\"type\": \"doubao\", \"api_url\": \"https://bytedance.gizwitsapi.com/api/v1/tts\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 11, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_GizwitsTTS', 'TTS', 'GizwitsTTS', '机智云语音合成', 0, 1, '{\"type\": \"doubao\", \"api_url\": \"https://bytedance.gizwitsapi.com/api/v1/tts\", \"authorization\": \"Bearer \", \"voice\": \"zh_female_wanwanxiaohe_moon_bigtts\", \"output_dir\": \"tmp/\", \"access_token\": \"\"}', NULL, NULL, 11, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_ACGNTTS', 'TTS', 'ACGNTTS', 'ACGN语音合成', 0, 1, '{\"type\": \"ttson\", \"token\": \"\", \"voice_id\": 1695, \"speed_factor\": 1, \"pitch_factor\": 0, \"volume_change_dB\": 0, \"to_lang\": \"ZH\", \"url\": \"https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=\", \"format\": \"mp3\", \"output_dir\": \"tmp/\", \"emotion\": 1}', NULL, NULL, 12, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_ACGNTTS', 'TTS', 'ACGNTTS', 'ACGN语音合成', 0, 1, '{\"type\": \"ttson\", \"token\": \"\", \"voice_id\": 1695, \"speed_factor\": 1, \"pitch_factor\": 0, \"volume_change_dB\": 0, \"to_lang\": \"ZH\", \"url\": \"https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=\", \"format\": \"mp3\", \"output_dir\": \"tmp/\", \"emotion\": 1}', NULL, NULL, 12, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_OpenAITTS', 'TTS', 'OpenAITTS', 'OpenAI语音合成', 0, 1, '{\"type\": \"openai\", \"api_key\": \"\", \"api_url\": \"https://api.openai.com/v1/audio/speech\", \"model\": \"tts-1\", \"voice\": \"onyx\", \"speed\": 1, \"output_dir\": \"tmp/\"}', NULL, NULL, 13, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_OpenAITTS', 'TTS', 'OpenAITTS', 'OpenAI语音合成', 0, 1, '{\"type\": \"openai\", \"api_key\": \"你的api_key\", \"api_url\": \"https://api.openai.com/v1/audio/speech\", \"model\": \"tts-1\", \"voice\": \"onyx\", \"speed\": 1, \"output_dir\": \"tmp/\"}', NULL, NULL, 13, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_CustomTTS', 'TTS', 'CustomTTS', '自定义语音合成', 0, 1, '{\"type\": \"custom\", \"url\": \"http://127.0.0.1:9880/tts\", \"params\": {}, \"headers\": {}, \"format\": \"wav\", \"output_dir\": \"tmp/\"}', NULL, NULL, 14, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('TTS_CustomTTS', 'TTS', 'CustomTTS', '自定义语音合成', 0, 1, '{\"type\": \"custom\", \"url\": \"http://127.0.0.1:9880/tts\", \"params\": {}, \"headers\": {}, \"format\": \"wav\", \"output_dir\": \"tmp/\"}', NULL, NULL, 14, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('TTS_TencentTTS', 'TTS', 'TencentTTS', '腾讯语音合成', 0, 1, '{\"type\": \"tencent\", \"appid\": \"\", \"secret_id\": \"\", \"secret_key\": \"\", \"region\": \"ap-guangzhou\", \"voice\": \"101001\", \"output_dir\": \"tmp/\"}', NULL, NULL, 3, NULL, NULL, NULL, NULL);
-- Memory模型配置 -- Memory模型配置
INSERT INTO `ai_model_config` VALUES ('Memory_nomem', 'Memory', 'nomem', '无记忆', 1, 1, '{\"type\": \"nomem\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('Memory_nomem', 'Memory', 'nomem', '无记忆', 1, 1, '{\"type\": \"nomem\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('Memory_mem_local_short', 'Memory', 'mem_local_short', '本地短期记忆', 0, 1, '{\"type\": \"mem_local_short\"}', NULL, NULL, 2, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('Memory_mem_local_short', 'Memory', 'mem_local_short', '本地短期记忆', 0, 1, '{\"type\": \"mem_local_short\"}', NULL, NULL, 2, NULL, NULL, NULL, NULL);
INSERT INTO `ai_model_config` VALUES ('Memory_mem0ai', 'Memory', 'mem0ai', 'Mem0AI记忆', 0, 1, '{\"type\": \"mem0ai\", \"api_key\": \"\"}', NULL, NULL, 3, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('Memory_mem0ai', 'Memory', 'mem0ai', 'Mem0AI记忆', 0, 1, '{\"type\": \"mem0ai\", \"api_key\": \"你的api_key\"}', NULL, NULL, 3, NULL, NULL, NULL, NULL);
-- Intent模型配置 -- Intent模型配置
INSERT INTO `ai_model_config` VALUES ('Intent_nointent', 'Intent', 'nointent', '无意图识别', 1, 0, '{\"type\": \"nointent\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL); INSERT INTO `ai_model_config` VALUES ('Intent_nointent', 'Intent', 'nointent', '无意图识别', 1, 0, '{\"type\": \"nointent\"}', NULL, NULL, 1, NULL, NULL, NULL, NULL);

View file

@ -23,7 +23,7 @@ create table sys_params
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (100, 'server.ip', '0.0.0.0', 'string', 1, '服务器监听IP地址'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (100, 'server.ip', '0.0.0.0', 'string', 1, '服务器监听IP地址');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (101, 'server.port', '8000', 'number', 1, '服务器监听端口'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (101, 'server.port', '8000', 'number', 1, '服务器监听端口');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (102, 'server.secret', 'null', 'string', 1, '服务器密钥'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (102, 'server.secret', 'null', 'string', 1, '服务器密钥');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (201, 'log.log_format', '<green>{time:YYMMDD HH:mm:ss}</green>[{version}_{selected_module}][<light-blue>{extra[tag]}</light-blue>]-<level>{level}</level>-<light-green>{message}</light-green>', 'string', 1, '控制台日志格式'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (201, 'log.log_format', '<green>{time:YYMMDD HH:mm:ss}</green>[<light-blue>{version}-{selected_module}</light-blue>][<light-blue>{extra[tag]}</light-blue>]-<level>{level}</level>-<light-green>{message}</light-green>', 'string', 1, '控制台日志格式');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (202, 'log.log_format_file', '{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}', 'string', 1, '文件日志格式'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (202, 'log.log_format_file', '{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}', 'string', 1, '文件日志格式');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (203, 'log.log_level', 'INFO', 'string', 1, '日志级别'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (203, 'log.log_level', 'INFO', 'string', 1, '日志级别');
INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (204, 'log.log_dir', 'tmp', 'string', 1, '日志目录'); INSERT INTO `sys_params` (id, param_code, param_value, value_type, param_type, remark) VALUES (204, 'log.log_dir', 'tmp', 'string', 1, '日志目录');

View file

@ -38,16 +38,16 @@ databaseChangeLog:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202504092335.sql path: classpath:db/changelog/202504092335.sql
- changeSet: - changeSet:
id: 202504101506 id: 202504112044
author: John author: John
changes: changes:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202504101506.sql path: classpath:db/changelog/202504112044.sql
- changeSet: - changeSet:
id: 202504110910 id: 202504112057
author: John author: John
changes: changes:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202504110910.sql path: classpath:db/changelog/202504112057.sql

View file

@ -117,7 +117,7 @@ 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, "device_id": device_id, "client_id": client_id}, {"secret": secret, "macAddress": device_id, "clientId": client_id},
) )

View file

@ -27,6 +27,7 @@ from core.handle.functionHandler import FunctionHandler
from plugins_func.register import Action, ActionResponse from plugins_func.register import Action, ActionResponse
from core.auth import AuthMiddleware, AuthenticationError from core.auth import AuthMiddleware, AuthenticationError
from core.mcp.manager import MCPManager from core.mcp.manager import MCPManager
from config.config_loader import get_private_config_from_api
TAG = __name__ TAG = __name__
@ -186,7 +187,7 @@ class ConnectionHandler:
"""加载意图识别""" """加载意图识别"""
self._initialize_intent() self._initialize_intent()
"""加载位置信息""" """加载位置信息"""
self.client_ip_info = get_ip_info(self.client_ip) self.client_ip_info = get_ip_info(self.client_ip, self.logger)
if self.client_ip_info is not None and "city" in self.client_ip_info: if self.client_ip_info is not None and "city" in self.client_ip_info:
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}") self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}" self.prompt = self.prompt + f"\nuser location:{self.client_ip_info}"
@ -198,9 +199,48 @@ class ConnectionHandler:
"""如果是从配置文件获取,则进行二次实例化""" """如果是从配置文件获取,则进行二次实例化"""
if not read_config_from_api: if not read_config_from_api:
return return
"""从接口获取和默认模型差异化配置进行二次实例化""" """从接口获取差异化的配置进行二次实例化,非全量重新实例化"""
try:
private_config = get_private_config_from_api(
self.config,
self.headers.get("device-id", None),
self.headers.get("client-id", None),
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
private_config = {}
modules = initialize_modules(self.config) init_vad, init_asr, init_llm, init_tts, init_memory, init_intent = (
False,
False,
False,
False,
False,
False,
)
if private_config.get("vad", None) is not None:
init_vad = True
if private_config.get("asr", None) is not None:
init_asr = True
if private_config.get("llm", None) is not None:
init_llm = True
if private_config.get("tts", None) is not None:
init_tts = True
if private_config.get("memory", None) is not None:
init_memory = True
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,
)
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:

View file

@ -4,15 +4,17 @@ from core.providers.llm.base import LLMProviderBase
from config.logger import setup_logging from config.logger import setup_logging
import requests import requests
import json import json
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class LLMProvider(LLMProviderBase): class LLMProvider(LLMProviderBase):
def __init__(self, config): def __init__(self, config):
"""初始化Gemini LLM Provider""" """初始化Gemini LLM Provider"""
self.model_name = config.get("model_name", "gemini-1.5-pro") self.model_name = config.get("model_name", "gemini-1.5-pro")
self.api_key = config.get("api_key") self.api_key = config.get("api_key")
self.http_proxy=config.get("http_proxy") self.http_proxy = config.get("http_proxy")
self.https_proxy = config.get("https_proxy") self.https_proxy = config.get("https_proxy")
have_key = check_model_key("LLM", self.api_key) have_key = check_model_key("LLM", self.api_key)
@ -22,7 +24,7 @@ class LLMProvider(LLMProviderBase):
try: try:
# 初始化Gemini客户端 # 初始化Gemini客户端
# 配置代理(如果提供了代理配置) # 配置代理(如果提供了代理配置)
self.proxies=None self.proxies = None
if self.http_proxy is not "" or self.https_proxy is not "": if self.http_proxy is not "" or self.https_proxy is not "":
self.proxies = { self.proxies = {
@ -62,19 +64,16 @@ class LLMProvider(LLMProviderBase):
role = "model" if msg["role"] == "assistant" else "user" role = "model" if msg["role"] == "assistant" else "user"
content = msg["content"].strip() content = msg["content"].strip()
if content: if content:
chat_history.append({ chat_history.append({"role": role, "parts": [{"text": content}]})
"role": role,
"parts": [{"text":content}]
})
# 获取当前消息 # 获取当前消息
current_msg = dialogue[-1]["content"] current_msg = dialogue[-1]["content"]
# 构建请求体 # 构建请求体
request_body = { request_body = {
"contents": chat_history + [{"role": "user", "parts": [{"text":current_msg}]}], "contents": chat_history
"generationConfig": self.generation_config + [{"role": "user", "parts": [{"text": current_msg}]}],
"generationConfig": self.generation_config,
} }
# 构建请求URL # 构建请求URL
@ -87,11 +86,17 @@ class LLMProvider(LLMProviderBase):
# 发送POST请求,经测试手动 request 无法使用 stream 模式 # 发送POST请求,经测试手动 request 无法使用 stream 模式
if self.proxies: if self.proxies:
response = requests.post(url, headers=headers, json=request_body, stream=False, proxies=self.proxies) response = requests.post(
url,
headers=headers,
json=request_body,
stream=False,
proxies=self.proxies,
)
try: try:
data = response.json() # 直接解析JSON data = response.json() # 直接解析JSON
if 'candidates' in data and data['candidates']: if "candidates" in data and data["candidates"]:
yield data['candidates'][0]['content']['parts'][0]['text'] yield data["candidates"][0]["content"]["parts"][0]["text"]
else: else:
yield "未找到候选回复。" yield "未找到候选回复。"
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
@ -104,13 +109,11 @@ class LLMProvider(LLMProviderBase):
# 发送消息并获取流式响应 # 发送消息并获取流式响应
response = chat.send_message( response = chat.send_message(
current_msg, current_msg, stream=True, generation_config=self.generation_config
stream=True,
generation_config=self.generation_config
) )
# 处理流式响应 # 处理流式响应
for chunk in response: for chunk in response:
if hasattr(chunk, 'text') and chunk.text: if hasattr(chunk, "text") and chunk.text:
yield chunk.text yield chunk.text
except Exception as e: except Exception as e:
@ -125,9 +128,6 @@ class LLMProvider(LLMProviderBase):
else: else:
yield f"【Gemini服务响应异常: {error_msg}】" yield f"【Gemini服务响应异常: {error_msg}】"
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
yield f"请求失败:{e}" yield f"请求失败:{e}"
except json.JSONDecodeError as e: except json.JSONDecodeError as e:

View file

@ -11,7 +11,7 @@ class LLMProvider(LLMProviderBase):
def __init__(self, config): def __init__(self, config):
self.model_name = config.get("model_name") self.model_name = config.get("model_name")
self.api_key = config.get("api_key") self.api_key = config.get("api_key")
if 'base_url' in config: if "base_url" in config:
self.base_url = config.get("base_url") self.base_url = config.get("base_url")
else: else:
self.base_url = config.get("url") self.base_url = config.get("url")
@ -33,18 +33,22 @@ class LLMProvider(LLMProviderBase):
for chunk in responses: for chunk in responses:
try: try:
# 检查是否存在有效的choice且content不为空 # 检查是否存在有效的choice且content不为空
delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None delta = (
content = delta.content if hasattr(delta, 'content') else '' chunk.choices[0].delta
if getattr(chunk, "choices", None)
else None
)
content = delta.content if hasattr(delta, "content") else ""
except IndexError: except IndexError:
content = '' content = ""
if content: if content:
# 处理标签跨多个chunk的情况 # 处理标签跨多个chunk的情况
if '<think>' in content: if "<think>" in content:
is_active = False is_active = False
content = content.split('<think>')[0] content = content.split("<think>")[0]
if '</think>' in content: if "</think>" in content:
is_active = True is_active = True
content = content.split('</think>')[-1] content = content.split("</think>")[-1]
if is_active: if is_active:
yield content yield content
@ -54,10 +58,7 @@ class LLMProvider(LLMProviderBase):
def response_with_functions(self, session_id, dialogue, functions=None): def response_with_functions(self, session_id, dialogue, functions=None):
try: try:
stream = self.client.chat.completions.create( stream = self.client.chat.completions.create(
model=self.model_name, model=self.model_name, messages=dialogue, stream=True, tools=functions
messages=dialogue,
stream=True,
tools=functions
) )
for chunk in stream: for chunk in stream:

View file

@ -6,13 +6,14 @@ from core.utils.util import check_model_key
TAG = __name__ TAG = __name__
class MemoryProvider(MemoryProviderBase): class MemoryProvider(MemoryProviderBase):
def __init__(self, config): def __init__(self, config):
super().__init__(config) super().__init__(config)
self.api_key = config.get("api_key", "") self.api_key = config.get("api_key", "")
self.api_version = config.get("api_version", "v1.1") self.api_version = config.get("api_version", "v1.1")
have_key = check_model_key("Mem0ai", self.api_key) have_key = check_model_key("Mem0ai", self.api_key)
if not have_key : if not have_key:
self.use_mem0 = False self.use_mem0 = False
return return
else: else:
@ -35,38 +36,39 @@ class MemoryProvider(MemoryProviderBase):
# Format the content as a message list for mem0 # Format the content as a message list for mem0
messages = [ messages = [
{"role": message.role, "content": message.content} {"role": message.role, "content": message.content}
for message in msgs if message.role != "system" for message in msgs
if message.role != "system"
] ]
result = self.client.add(messages, user_id=self.role_id, output_format=self.api_version) result = self.client.add(
messages, user_id=self.role_id, output_format=self.api_version
)
logger.bind(tag=TAG).debug(f"Save memory result: {result}") logger.bind(tag=TAG).debug(f"Save memory result: {result}")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
return None return None
async def query_memory(self, query: str)-> str: async def query_memory(self, query: str) -> str:
if not self.use_mem0: if not self.use_mem0:
return "" return ""
try: try:
results = self.client.search( results = self.client.search(
query, query, user_id=self.role_id, output_format=self.api_version
user_id=self.role_id,
output_format=self.api_version
) )
if not results or 'results' not in results: if not results or "results" not in results:
return "" return ""
# Format each memory entry with its update time up to minutes # Format each memory entry with its update time up to minutes
memories = [] memories = []
for entry in results['results']: for entry in results["results"]:
timestamp = entry.get('updated_at', '') timestamp = entry.get("updated_at", "")
if timestamp: if timestamp:
try: try:
# Parse and reformat the timestamp # Parse and reformat the timestamp
dt = timestamp.split('.')[0] # Remove milliseconds dt = timestamp.split(".")[0] # Remove milliseconds
formatted_time = dt.replace('T', ' ') formatted_time = dt.replace("T", " ")
except: except:
formatted_time = timestamp formatted_time = timestamp
memory = entry.get('memory', '') memory = entry.get("memory", "")
if timestamp and memory: if timestamp and memory:
# Store tuple of (timestamp, formatted_string) for sorting # Store tuple of (timestamp, formatted_string) for sorting
memories.append((timestamp, f"[{formatted_time}] {memory}")) memories.append((timestamp, f"[{formatted_time}] {memory}"))

View file

@ -6,6 +6,10 @@ import requests
from datetime import datetime from datetime import datetime
from core.utils.util import check_model_key from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase): class TTSProvider(TTSProviderBase):
@ -21,18 +25,19 @@ class TTSProvider(TTSProviderBase):
check_model_key("TTS", self.access_token) check_model_key("TTS", self.access_token)
def generate_filename(self, extension=".wav"): def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") 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): async def text_to_speak(self, text, output_file):
request_json = { request_json = {
"app": { "app": {
"appid": f"{self.appid}", "appid": f"{self.appid}",
"token": "access_token", "token": "access_token",
"cluster": self.cluster "cluster": self.cluster,
},
"user": {
"uid": "1"
}, },
"user": {"uid": "1"},
"audio": { "audio": {
"voice_type": self.voice, "voice_type": self.voice,
"encoding": "wav", "encoding": "wav",
@ -46,17 +51,21 @@ class TTSProvider(TTSProviderBase):
"text_type": "plain", "text_type": "plain",
"operation": "query", "operation": "query",
"with_frontend": 1, "with_frontend": 1,
"frontend_type": "unitTson" "frontend_type": "unitTson",
} },
} }
try: 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 "data" in resp.json(): if "data" in resp.json():
data = resp.json()["data"] data = resp.json()["data"]
file_to_save = open(output_file, "wb") file_to_save = open(output_file, "wb")
file_to_save.write(base64.b64decode(data)) file_to_save.write(base64.b64decode(data))
else: 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: except Exception as e:
raise Exception(f"{__name__} error: {e}") raise Exception(f"{__name__} error: {e}")

View file

@ -107,7 +107,10 @@ class TTSProvider(TTSProviderBase):
self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts") self.api_url = config.get("api_url", "http://127.0.0.1:8080/v1/tts")
def generate_filename(self, extension=".wav"): def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") 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): async def text_to_speak(self, text, output_file):
# Prepare reference data # Prepare reference data
@ -117,9 +120,7 @@ class TTSProvider(TTSProviderBase):
data = { data = {
"text": text, "text": text,
"references": [ "references": [
ServeReferenceAudio( ServeReferenceAudio(audio=audio if audio else b"", text=text)
audio=audio if audio else b"", text=text
)
for text, audio in zip(ref_texts, byte_audios) for text, audio in zip(ref_texts, byte_audios)
], ],
"reference_id": self.reference_id, "reference_id": self.reference_id,
@ -139,7 +140,9 @@ class TTSProvider(TTSProviderBase):
response = requests.post( response = requests.post(
self.api_url, self.api_url,
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC), data=ormsgpack.packb(
pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC
),
headers={ headers={
"Authorization": f"Bearer {self.api_key}", "Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/msgpack", "Content-Type": "application/msgpack",
@ -152,8 +155,6 @@ class TTSProvider(TTSProviderBase):
with open(output_file, "wb") as audio_file: with open(output_file, "wb") as audio_file:
audio_file.write(audio_content) audio_file.write(audio_content)
else: else:
print(f"Request failed with status code {response.status_code}") print(f"Request failed with status code {response.status_code}")
print(response.json()) print(response.json())

View file

@ -4,6 +4,11 @@ import requests
from datetime import datetime from datetime import datetime
from core.utils.util import check_model_key from core.utils.util import check_model_key
from core.providers.tts.base import TTSProviderBase from core.providers.tts.base import TTSProviderBase
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
class TTSProvider(TTSProviderBase): class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file): def __init__(self, config, delete_audio_file):
@ -18,23 +23,28 @@ class TTSProvider(TTSProviderBase):
check_model_key("TTS", self.api_key) check_model_key("TTS", self.api_key)
def generate_filename(self, extension=".wav"): def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}") 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): async def text_to_speak(self, text, output_file):
headers = { headers = {
"Authorization": f"Bearer {self.api_key}", "Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json" "Content-Type": "application/json",
} }
data = { data = {
"model": self.model, "model": self.model,
"input": text, "input": text,
"voice": self.voice, "voice": self.voice,
"response_format": "wav", "response_format": "wav",
"speed": self.speed "speed": self.speed,
} }
response = requests.post(self.api_url, json=data, headers=headers) response = requests.post(self.api_url, json=data, headers=headers)
if response.status_code == 200: if response.status_code == 200:
with open(output_file, "wb") as audio_file: with open(output_file, "wb") as audio_file:
audio_file.write(response.content) audio_file.write(response.content)
else: else:
raise Exception(f"OpenAI TTS请求失败: {response.status_code} - {response.text}") raise Exception(
f"OpenAI TTS请求失败: {response.status_code} - {response.text}"
)

View file

@ -1,13 +1,13 @@
import os
import json import json
import socket import socket
import subprocess import subprocess
import logging
import re import re
import requests import requests
from typing import Dict, Any from typing import Dict, Any
from core.utils import tts, llm, intent, memory, vad, asr from core.utils import tts, llm, intent, memory, vad, asr
TAG = __name__
def get_local_ip(): def get_local_ip():
try: try:
@ -65,7 +65,7 @@ def is_private_ip(ip_addr):
return False # IP address format error or insufficient segments return False # IP address format error or insufficient segments
def get_ip_info(ip_addr): def get_ip_info(ip_addr, logger):
try: try:
if is_private_ip(ip_addr): if is_private_ip(ip_addr):
ip_addr = "" ip_addr = ""
@ -74,7 +74,7 @@ def get_ip_info(ip_addr):
ip_info = {"city": resp.get("city")} ip_info = {"city": resp.get("city")}
return ip_info return ip_info
except Exception as e: except Exception as e:
logging.error(f"Error getting client ip info: {e}") logger.bind(tag=TAG).error(f"Error getting client ip info: {e}")
return {} return {}
@ -156,10 +156,8 @@ def remove_punctuation_and_length(text):
def check_model_key(modelType, modelKey): def check_model_key(modelType, modelKey):
if "你" in modelKey: if "你" in modelKey:
logging.error( raise ValueError(
"你还没配置" "你还没配置" + modelType + "的密钥,请检查一下所使用的LLM是否配置了密钥"
+ modelType
+ "的密钥,请在配置文件中配置密钥,否则无法正常工作"
) )
return False return False
return True return True
@ -202,13 +200,14 @@ def extract_json_from_string(input_string):
def initialize_modules( def initialize_modules(
logger,
config: Dict[str, Any], config: Dict[str, Any],
init_vad=True, init_vad=False,
init_asr=True, init_asr=False,
init_llm=True, init_llm=False,
init_tts=True, init_tts=False,
init_memory=True, init_memory=False,
init_intent=True, init_intent=False,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
""" """
初始化所有模块组件 初始化所有模块组件
@ -233,6 +232,7 @@ def initialize_modules(
config["TTS"][config["selected_module"]["TTS"]], config["TTS"][config["selected_module"]["TTS"]],
config["delete_audio"], config["delete_audio"],
) )
logger.bind(tag=TAG).info(f"初始化组件: tts成功")
# 初始化LLM模块 # 初始化LLM模块
if init_llm: if init_llm:
@ -245,6 +245,7 @@ def initialize_modules(
llm_type, llm_type,
config["LLM"][config["selected_module"]["LLM"]], config["LLM"][config["selected_module"]["LLM"]],
) )
logger.bind(tag=TAG).info(f"初始化组件: llm成功")
# 初始化Intent模块 # 初始化Intent模块
if init_intent: if init_intent:
@ -257,7 +258,7 @@ def initialize_modules(
intent_type, intent_type,
config["Intent"][config["selected_module"]["Intent"]], config["Intent"][config["selected_module"]["Intent"]],
) )
logger.bind(tag=TAG).info(f"初始化组件: intent成功")
# 初始化Memory模块 # 初始化Memory模块
if init_memory: if init_memory:
memory_type = ( memory_type = (
@ -269,6 +270,7 @@ def initialize_modules(
memory_type, memory_type,
config["Memory"][config["selected_module"]["Memory"]], config["Memory"][config["selected_module"]["Memory"]],
) )
logger.bind(tag=TAG).info(f"初始化组件: memory成功")
# 初始化VAD模块 # 初始化VAD模块
if init_vad: if init_vad:
@ -281,7 +283,7 @@ def initialize_modules(
vad_type, vad_type,
config["VAD"][config["selected_module"]["VAD"]], config["VAD"][config["selected_module"]["VAD"]],
) )
logger.bind(tag=TAG).info(f"初始化组件: vad成功")
# 初始化ASR模块 # 初始化ASR模块
if init_asr: if init_asr:
asr_type = ( asr_type = (
@ -294,5 +296,6 @@ def initialize_modules(
config["ASR"][config["selected_module"]["ASR"]], config["ASR"][config["selected_module"]["ASR"]],
config["delete_audio"], config["delete_audio"],
) )
logger.bind(tag=TAG).info(f"初始化组件: asr成功")
return modules return modules

View file

@ -11,7 +11,9 @@ class WebSocketServer:
def __init__(self, config: dict): def __init__(self, config: dict):
self.config = config self.config = config
self.logger = setup_logging() self.logger = setup_logging()
modules = initialize_modules(self.config) modules = initialize_modules(
self.logger, self.config, True, True, True, True, True, True
)
self._vad = modules["vad"] self._vad = modules["vad"]
self._asr = modules["asr"] self._asr = modules["asr"]
self._tts = modules["tts"] self._tts = modules["tts"]