Enhance model configuration and feature management

- Updated model type query to use uppercase "LLM" for consistency.
- Improved JSON handling in model configuration retrieval.
- Added SQL migration to enable specific AI models and update their configurations.
- Introduced tests for provider policy to validate western role configurations and block Chinese provider seeds.
- Modified feature manager to enable VAD and ASR features by default and added a refresh method for feature configuration.
This commit is contained in:
lapy 2026-06-13 13:33:54 +01:00
parent a215ccf7fa
commit c30b3e024e
8 changed files with 186 additions and 14 deletions

View file

@ -67,7 +67,7 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
public List<LlmModelBasicInfoDTO> getLlmModelCodeList(String modelName) { public List<LlmModelBasicInfoDTO> getLlmModelCodeList(String modelName) {
List<ModelConfigEntity> entities = modelConfigDao.selectList( List<ModelConfigEntity> entities = modelConfigDao.selectList(
new QueryWrapper<ModelConfigEntity>() new QueryWrapper<ModelConfigEntity>()
.eq("model_type", "llm") .eq("model_type", "LLM")
.eq("is_enabled", 1) .eq("is_enabled", 1)
.like(StringUtils.isNotBlank(modelName), "model_name", modelName) .like(StringUtils.isNotBlank(modelName), "model_name", modelName)
.select("id", "model_name", "config_json")); .select("id", "model_name", "config_json"));
@ -78,7 +78,8 @@ public class ModelConfigServiceImpl extends BaseServiceImpl<ModelConfigDao, Mode
LlmModelBasicInfoDTO dto = new LlmModelBasicInfoDTO(); LlmModelBasicInfoDTO dto = new LlmModelBasicInfoDTO();
dto.setId(item.getId()); dto.setId(item.getId());
dto.setModelName(item.getModelName()); dto.setModelName(item.getModelName());
String type = item.getConfigJson().getOrDefault("type", "").toString(); JSONObject configJson = item.getConfigJson();
String type = configJson != null ? configJson.getOrDefault("type", "").toString() : "";
dto.setType(type); dto.setType(type);
return dto; return dto;
}) })

View file

@ -0,0 +1,33 @@
-- Ensure role-config dropdowns have selectable western models after westernization.
-- Re-enable core defaults when they exist but were left disabled, and turn on
-- VAD/ASR menu flags so the role-config page shows those selectors.
UPDATE `ai_model_config`
SET `is_enabled` = 1
WHERE `id` IN (
'LLM_OpenAILLM',
'TTS_EdgeTTS',
'VAD_SileroVAD',
'ASR_VoskASR',
'ASR_GroqASR',
'ASR_OpenaiASR',
'Intent_function_call',
'Memory_nomem',
'VLLM_OpenAILLMVLLM'
)
AND `is_enabled` = 0;
UPDATE `ai_model_config`
SET `config_json` = JSON_SET(CAST(`config_json` AS JSON), '$.llm', 'LLM_OpenAILLM')
WHERE `id` = 'Memory_mem_local_short'
AND JSON_UNQUOTE(JSON_EXTRACT(CAST(`config_json` AS JSON), '$.llm')) = 'LLM_ChatGLMLLM';
UPDATE `sys_params`
SET `param_value` = CAST(
JSON_SET(
CAST(`param_value` AS JSON),
'$.features.vad.enabled', TRUE,
'$.features.asr.enabled', TRUE
) AS CHAR
)
WHERE `param_code` = 'system-web.menu';

View file

@ -746,3 +746,10 @@ databaseChangeLog:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202606131400.sql path: classpath:db/changelog/202606131400.sql
- changeSet:
id: 202606131500
author: codex
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202606131500.sql

View file

@ -0,0 +1,66 @@
package xiaozhi.modules.model.support;
import cn.hutool.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import xiaozhi.modules.model.entity.ModelConfigEntity;
class ProviderPolicyTest {
@Test
void allowsWesternRoleConfigDefaults() {
Assertions.assertTrue(ProviderPolicy.isAllowedModelConfig(model("LLM_OpenAILLM", "OpenAILLM", "OpenAI GPT", openAiConfig())));
Assertions.assertTrue(ProviderPolicy.isAllowedModelConfig(model("TTS_EdgeTTS", "EdgeTTS", "Edge TTS", edgeConfig())));
Assertions.assertTrue(ProviderPolicy.isAllowedModelConfig(model("VAD_SileroVAD", "SileroVAD", "Voice Activity Detection", sileroConfig())));
Assertions.assertTrue(ProviderPolicy.isAllowedModelConfig(model("ASR_VoskASR", "VoskASR", "VOSK Offline Speech Recognition", voskConfig())));
}
@Test
void blocksChineseProviderSeeds() {
Assertions.assertFalse(ProviderPolicy.isAllowedModelConfig(model("LLM_DoubaoLLM", "DoubaoLLM", "Doubao", openAiConfig())));
Assertions.assertFalse(ProviderPolicy.isAllowedModelConfig(model("ASR_FunASR", "FunASR", "FunASR", voskConfig())));
Assertions.assertFalse(ProviderPolicy.isAllowedModelConfig(model("LLM_DeepSeekLLM", "DeepSeekLLM", "DeepSeek", deepSeekConfig())));
}
private static ModelConfigEntity model(String id, String modelCode, String modelName, JSONObject configJson) {
ModelConfigEntity entity = new ModelConfigEntity();
entity.setId(id);
entity.setModelCode(modelCode);
entity.setModelName(modelName);
entity.setConfigJson(configJson);
return entity;
}
private static JSONObject openAiConfig() {
JSONObject config = new JSONObject();
config.set("type", "openai");
config.set("model_name", "gpt-4o-mini");
return config;
}
private static JSONObject edgeConfig() {
JSONObject config = new JSONObject();
config.set("voice", "en-US-AriaNeural");
return config;
}
private static JSONObject sileroConfig() {
JSONObject config = new JSONObject();
config.set("type", "silero");
return config;
}
private static JSONObject voskConfig() {
JSONObject config = new JSONObject();
config.set("type", "vosk");
return config;
}
private static JSONObject deepSeekConfig() {
JSONObject config = new JSONObject();
config.set("type", "openai");
config.set("model_name", "deepseek-chat");
config.set("base_url", "https://api.deepseek.com");
return config;
}
}

View file

@ -208,6 +208,37 @@ SET param_value = JSON_SET(
'["voiceprintRecognition","voiceClone","knowledgeBase","mcpAccessPoint","addressBook"]' '["voiceprintRecognition","voiceClone","knowledgeBase","mcpAccessPoint","addressBook"]'
) )
WHERE param_code = 'system-web.menu'; WHERE param_code = 'system-web.menu';
""";
}
if ("202606131500.sql".equals(fileName)) {
return """
UPDATE ai_model_config
SET is_enabled = 1
WHERE id IN (
'LLM_OpenAILLM',
'TTS_EdgeTTS',
'VAD_SileroVAD',
'ASR_VoskASR',
'ASR_GroqASR',
'ASR_OpenaiASR',
'Intent_function_call',
'Memory_nomem',
'VLLM_OpenAILLMVLLM'
)
AND is_enabled = 0;
UPDATE ai_model_config
SET config_json = JSON_SET(CAST(config_json AS VARCHAR), '$.llm', 'LLM_OpenAILLM')
WHERE id = 'Memory_mem_local_short'
AND JSON_UNQUOTE(JSON_EXTRACT(CAST(config_json AS VARCHAR), '$.llm')) = 'LLM_ChatGLMLLM';
UPDATE sys_params
SET param_value = JSON_SET(
CAST(param_value AS VARCHAR),
'$.features.vad.enabled', 'true',
'$.features.asr.enabled', 'true'
)
WHERE param_code = 'system-web.menu';
"""; """;
} }
if ("202601141645.sql".equals(fileName)) { if ("202601141645.sql".equals(fileName)) {
@ -495,11 +526,15 @@ WHERE r.sort = 0;
private void assertLatestChangeSetApplied(Connection connection) throws SQLException { private void assertLatestChangeSetApplied(Connection connection) throws SQLException {
String latestId = scalar(connection, "SELECT MAX(ID) FROM DATABASECHANGELOG"); String latestId = scalar(connection, "SELECT MAX(ID) FROM DATABASECHANGELOG");
Assertions.assertEquals("202606131400", latestId, "latest downstream cleanup migration should be applied"); Assertions.assertEquals("202606131500", latestId, "latest downstream cleanup migration should be applied");
} }
private void assertRequiredSeedCoverage(Connection connection) throws SQLException { private void assertRequiredSeedCoverage(Connection connection) throws SQLException {
assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'server.name' AND param_value = 'xiaozhi-esp32-server'"); assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'server.name' AND param_value = 'xiaozhi-esp32-server'");
assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'LLM_OpenAILLM' AND is_enabled = 1");
assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'TTS_EdgeTTS' AND is_enabled = 1");
assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'VAD_SileroVAD' AND is_enabled = 1");
assertExists(connection, "SELECT 1 FROM ai_model_config WHERE id = 'ASR_VoskASR' AND is_enabled = 1");
assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'exit_commands' AND param_value = 'exit;close'"); assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'exit_commands' AND param_value = 'exit;close'");
assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.get_weather.default_location' AND param_value = 'New York'"); assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.get_weather.default_location' AND param_value = 'New York'");
assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.get_news.default_rss_url' AND param_value = 'https://feeds.reuters.com/reuters/worldNews'"); assertExists(connection, "SELECT 1 FROM sys_params WHERE param_code = 'plugins.get_news.default_rss_url' AND param_value = 'https://feeds.reuters.com/reuters/worldNews'");

View file

@ -92,10 +92,13 @@ export default {
}, },
// Get model name list // Get model name list
getModelNames(modelType, modelName, callback) { getModelNames(modelType, modelName, callback) {
const queryParams = new URLSearchParams({
modelType,
modelName: modelName || ''
}).toString();
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/names`) .url(`${getServiceUrl()}/models/names?${queryParams}`)
.method('GET') .method('GET')
.data({ modelType, modelName })
.success((res) => { .success((res) => {
RequestService.clearRequestTime(); RequestService.clearRequestTime();
callback(res); callback(res);
@ -108,10 +111,12 @@ export default {
}, },
// Get LLM model name list // Get LLM model name list
getLlmModelCodeList(modelName, callback) { getLlmModelCodeList(modelName, callback) {
const queryParams = new URLSearchParams({
modelName: modelName || ''
}).toString();
RequestService.sendRequest() RequestService.sendRequest()
.url(`${getServiceUrl()}/models/llm/names`) .url(`${getServiceUrl()}/models/llm/names?${queryParams}`)
.method('GET') .method('GET')
.data({ modelName })
.success((res) => { .success((res) => {
RequestService.clearRequestTime(); RequestService.clearRequestTime();
callback(res); callback(res);

View file

@ -27,12 +27,12 @@ class FeatureManager {
}, },
vad: { vad: {
name: 'feature.vad.name', name: 'feature.vad.name',
enabled: false, enabled: true,
description: 'feature.vad.description' description: 'feature.vad.description'
}, },
asr: { asr: {
name: 'feature.asr.name', name: 'feature.asr.name',
enabled: false, enabled: true,
description: 'feature.asr.description' description: 'feature.asr.description'
}, },
addressBook: { addressBook: {
@ -57,6 +57,15 @@ class FeatureManager {
return this.initialized; return this.initialized;
} }
/**
* Reload feature configuration from pub-config (e.g. after login).
*/
async refresh() {
this.initPromise = this.init();
await this.initPromise;
return this.currentFeatures;
}
/** /**
* Initialize feature configuration. * Initialize feature configuration.
*/ */

View file

@ -774,10 +774,11 @@ export default {
if (model.type != "LLM") { if (model.type != "LLM") {
Api.model.getModelNames(model.type, "", ({ data }) => { Api.model.getModelNames(model.type, "", ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
const models = Array.isArray(data.data) ? data.data : [];
this.$set( this.$set(
this.modelOptions, this.modelOptions,
model.type, model.type,
data.data.map((item) => ({ models.map((item) => ({
value: item.id, value: item.id,
label: item.modelName, label: item.modelName,
isHidden: false, isHidden: false,
@ -796,7 +797,8 @@ export default {
Api.model.getLlmModelCodeList("", ({ data }) => { Api.model.getLlmModelCodeList("", ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
let LLMdata = []; let LLMdata = [];
data.data.forEach((item) => { const models = Array.isArray(data.data) ? data.data : [];
models.forEach((item) => {
LLMdata.push({ LLMdata.push({
value: item.id, value: item.id,
label: item.modelName, label: item.modelName,
@ -1302,11 +1304,26 @@ export default {
this.form.chatHistoryConf = 0; this.form.chatHistoryConf = 0;
} }
}, },
hasModelOptionsLoaded() {
return Object.keys(this.modelOptions).length > 0;
},
scheduleModelOptionsLoad() {
const load = () => {
this.fetchModelOptions();
this.fetchTemplates();
};
load();
this.$nextTick(() => {
if (!this.hasModelOptionsLoaded()) {
load();
}
});
},
// 加载功能状态 // 加载功能状态
async loadFeatureStatus() { async loadFeatureStatus() {
try { try {
// 确保featureManager已初始化完成
await featureManager.waitForInitialization(); await featureManager.waitForInitialization();
await featureManager.refresh();
const config = featureManager.getConfig(); const config = featureManager.getConfig();
this.featureStatus.voiceprintRecognition = config.voiceprintRecognition || false; this.featureStatus.voiceprintRecognition = config.voiceprintRecognition || false;
this.featureStatus.vad = config.vad || false; this.featureStatus.vad = config.vad || false;
@ -1383,8 +1400,7 @@ export default {
this.getAgentTags(agentId); this.getAgentTags(agentId);
this.fetchAllFunctions(); this.fetchAllFunctions();
} }
this.fetchModelOptions(); this.scheduleModelOptionsLoad();
this.fetchTemplates();
// 加载功能状态,确保featureManager已初始化 // 加载功能状态,确保featureManager已初始化
await this.loadFeatureStatus(); await this.loadFeatureStatus();
}, },