feat: 模型管理独立页与会话级选模型

This commit is contained in:
2026-09-20 15:42:25 +08:00
parent ffb8d5f7dc
commit aac3424911
24 changed files with 845 additions and 523 deletions
@@ -0,0 +1,16 @@
-- 一级菜单「模型管理」;智能助手菜单仅保留 agent:chat
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14081, NULL, 0, 'AgentLlmSettings', '模型管理', '/agent/llm-settings', '/agent/llm-settings/index', '', 'lucide:brain-circuit', 'menu', 1, 1, 0, 15
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14081 OR `route_name` = 'AgentLlmSettings');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id
FROM `sys_menu` m
JOIN `sys_permission` p ON p.code = 'agent:llm-settings'
WHERE m.route_name = 'AgentLlmSettings';
-- 助手菜单去掉模型配置权限绑定(有配置权才看得到新一级菜单)
DELETE mp FROM `sys_menu_permission` mp
INNER JOIN `sys_menu` m ON m.id = mp.menu_id AND m.route_name = 'AgentAssistant'
INNER JOIN `sys_permission` p ON p.id = mp.permission_id AND p.code = 'agent:llm-settings';
@@ -12,36 +12,44 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
/**
* 公司模型 API 配置(浏览器 JWT):凭证 + 多模型勾选。
* 公司模型 API 配置(浏览器 JWT)。
*/
@RestController
@RequestMapping("/api/company/agent-llm-settings")
@RequestMapping("/api/company")
@RequiredArgsConstructor
public class AgentCompanyLlmSettingsController {
private final AgentCompanyLlmSettingsService settingsService;
@GetMapping
@GetMapping("/agent-llm-settings")
@RequirePermission(value = "agent:llm-settings", description = "查看模型配置", allowSuper = true)
public ApiResponse<AgentLlmSettingsVO> get() {
return ApiResponse.success(settingsService.getForCurrentCompany());
}
@PutMapping
@PutMapping("/agent-llm-settings")
@RequirePermission(value = "agent:llm-settings", description = "更新模型配置", allowSuper = true)
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto));
}
@PostMapping("/probe-models")
@PostMapping("/agent-llm-settings/probe-models")
@RequirePermission(value = "agent:llm-settings", description = "探测模型列表", allowSuper = true)
public ApiResponse<AgentLlmProbeModelsResultVO> probeModels(
@RequestBody ProbeAgentLlmModelsDTO dto) {
return ApiResponse.success(settingsService.probeModels(dto));
}
/** 聊天选模型:仅启用列表,无 Key */
@GetMapping("/agent-llm-models")
@RequirePermission(value = "agent:chat", description = "查看可用模型", allowSuper = true)
public ApiResponse<AgentLlmEnabledModelsVO> listEnabledModels() {
return ApiResponse.success(settingsService.listEnabledModelsForChat());
}
}
@@ -30,12 +30,13 @@ public class AgentInternalLlmController {
@GetMapping("/llm-runtime")
public ApiResponse<AgentLlmRuntimeVO> runtime(
@RequestParam("companyId") Long companyId,
@RequestParam(value = "model", required = false) String model,
HttpServletRequest request) {
assertAgentBearer(request);
if (companyId == null) {
throw new BusinessException("companyId 不能为空");
}
return ApiResponse.success(settingsService.getRuntime(companyId));
return ApiResponse.success(settingsService.getRuntime(companyId, model));
}
private void assertAgentBearer(HttpServletRequest request) {
@@ -0,0 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class AgentLlmEnabledModelsVO {
private List<AgentLlmModelVO> items = new ArrayList<>();
}
@@ -2,6 +2,7 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
@@ -17,6 +18,13 @@ public interface AgentCompanyLlmSettingsService {
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
/** Agent 内部:按公司取默认模型运行时明文 */
AgentLlmRuntimeVO getRuntime(Long companyId);
/** 聊天用:启用模型列表(无 Key) */
AgentLlmEnabledModelsVO listEnabledModelsForChat();
/**
* Agent 内部:运行时明文。
*
* @param model 空则默认模型;非空须在启用列表中
*/
AgentLlmRuntimeVO getRuntime(Long companyId, String model);
}
@@ -18,6 +18,7 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModels
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmProviderPO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmModelVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO;
@@ -26,7 +27,6 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe;
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.Duration;
@@ -39,7 +39,7 @@ import java.util.Map;
import java.util.Set;
/**
* 公司模型 API:MySQL 存密文与启用模型;Redis 缓存默认模型明文供 Agent。
* 公司模型 API:MySQL 存密文与启用模型;Redis 按模型缓存明文供 Agent。
*/
@Slf4j
@Service
@@ -53,7 +53,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
private final AgentLlmCrypto crypto;
private final AgentLlmProperties llmProperties;
private final CurrentUserContext currentUserContext;
private final CompanyMemberService companyMemberService;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
private final OpenAiCompatibleModelsProbe modelsProbe;
@@ -61,9 +60,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
@Override
public AgentLlmSettingsVO getForCurrentCompany() {
Long companyId = currentUserContext.getCurrentCompanyId();
AgentCompanyLlmProviderPO provider = findProvider(companyId);
List<AgentCompanyLlmModelPO> models = listModels(companyId);
return toPublicVo(provider, models);
return toPublicVo(findProvider(companyId), listModels(companyId));
}
@Override
@@ -71,7 +68,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
requireOwner(companyId, userId);
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
List<AgentLlmModelItemDTO> modelItems = normalizeModelItems(dto.getModels());
@@ -113,7 +109,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
providerMapper.updateById(existing);
}
// 全量覆盖模型:先删后插
modelMapper.delete(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId));
for (AgentLlmModelItemDTO item : modelItems) {
@@ -131,7 +126,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
List<AgentCompanyLlmModelPO> savedModels = listModels(companyId);
evictRuntimeCache(companyId);
try {
cacheRuntime(companyId, buildRuntime(existing, savedModels));
for (AgentCompanyLlmModelPO m : savedModels) {
cacheRuntime(companyId, buildRuntimeForModel(existing, m));
}
} catch (Exception e) {
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e);
}
@@ -141,9 +138,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
@Override
public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
Long userId = currentUserContext.getCurrentUserId();
requireOwner(companyId, userId);
if (dto == null || !StringUtils.hasText(dto.getBaseUrl())) {
throw new BusinessException("baseUrl 不能为空");
}
@@ -161,21 +155,28 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥");
}
List<AgentLlmProbedModelVO> items = modelsProbe.listModels(baseUrl, apiKey);
AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO();
vo.setItems(modelsProbe.listModels(baseUrl, apiKey));
return vo;
}
@Override
public AgentLlmEnabledModelsVO listEnabledModelsForChat() {
Long companyId = currentUserContext.getCurrentCompanyId();
AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO();
List<AgentLlmModelVO> items = new ArrayList<>();
for (AgentCompanyLlmModelPO m : listModels(companyId)) {
items.add(toModelVo(m));
}
vo.setItems(items);
return vo;
}
@Override
public AgentLlmRuntimeVO getRuntime(Long companyId) {
public AgentLlmRuntimeVO getRuntime(Long companyId, String model) {
if (companyId == null) {
throw new BusinessException("companyId 不能为空");
}
AgentLlmRuntimeVO cached = readRuntimeCache(companyId);
if (cached != null) {
return cached;
}
AgentCompanyLlmProviderPO provider = findProvider(companyId);
if (provider == null) {
throw new BusinessException("公司尚未配置模型 API");
@@ -184,18 +185,30 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
if (models.isEmpty()) {
throw new BusinessException("公司尚未启用任何模型");
}
AgentLlmRuntimeVO runtime = buildRuntime(provider, models);
AgentCompanyLlmModelPO selected;
if (StringUtils.hasText(model)) {
String want = model.trim();
selected = models.stream()
.filter(m -> want.equals(m.getModel()))
.findFirst()
.orElseThrow(() -> new BusinessException("模型未启用或不存在: " + want));
} else {
selected = models.stream()
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
.findFirst()
.orElse(models.get(0));
}
AgentLlmRuntimeVO cached = readRuntimeCache(companyId, selected.getModel());
if (cached != null) {
return cached;
}
AgentLlmRuntimeVO runtime = buildRuntimeForModel(provider, selected);
cacheRuntime(companyId, runtime);
return runtime;
}
private void requireOwner(Long companyId, Long userId) {
if (!currentUserContext.isCurrentUserSuper()
&& !companyMemberService.isOwner(userId, companyId)) {
throw new BusinessException("仅公司拥有者可配置模型 API");
}
}
private List<AgentLlmModelItemDTO> normalizeModelItems(List<AgentLlmModelItemDTO> raw) {
if (raw == null || raw.isEmpty()) {
throw new BusinessException("至少启用一个模型");
@@ -203,8 +216,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
Set<String> seen = new HashSet<>();
List<AgentLlmModelItemDTO> out = new ArrayList<>();
int defaultIdx = -1;
for (int i = 0; i < raw.size(); i++) {
AgentLlmModelItemDTO item = raw.get(i);
for (AgentLlmModelItemDTO item : raw) {
if (item == null || !StringUtils.hasText(item.getModel())) {
continue;
}
@@ -235,17 +247,13 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
return out;
}
private AgentLlmRuntimeVO buildRuntime(
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
AgentCompanyLlmModelPO def = models.stream()
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
.findFirst()
.orElse(models.get(0));
private AgentLlmRuntimeVO buildRuntimeForModel(
AgentCompanyLlmProviderPO provider, AgentCompanyLlmModelPO model) {
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
vo.setBaseUrl(provider.getBaseUrl());
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
vo.setModel(def.getModel());
vo.setContextWindow(def.getContextWindow());
vo.setModel(model.getModel());
vo.setContextWindow(model.getContextWindow());
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
return vo;
}
@@ -290,6 +298,15 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
.orderByAsc(AgentCompanyLlmModelPO::getId));
}
private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m) {
AgentLlmModelVO mv = new AgentLlmModelVO();
mv.setModel(m.getModel());
mv.setLabel(m.getLabel());
mv.setContextWindow(m.getContextWindow());
mv.setDefault(Boolean.TRUE.equals(m.getIsDefault()));
return mv;
}
private AgentLlmSettingsVO toPublicVo(
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
@@ -306,19 +323,14 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
}
List<AgentLlmModelVO> modelVos = new ArrayList<>();
for (AgentCompanyLlmModelPO m : models) {
AgentLlmModelVO mv = new AgentLlmModelVO();
mv.setModel(m.getModel());
mv.setLabel(m.getLabel());
mv.setContextWindow(m.getContextWindow());
mv.setDefault(Boolean.TRUE.equals(m.getIsDefault()));
modelVos.add(mv);
modelVos.add(toModelVo(m));
}
vo.setModels(modelVos);
return vo;
}
private static String redisKey(Long companyId) {
return "agent:llm:rt:" + companyId;
private static String redisKey(Long companyId, String model) {
return "agent:llm:rt:" + companyId + ":" + model;
}
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
@@ -331,7 +343,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
payload.put("extra_headers",
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
stringRedisTemplate.opsForValue().set(
redisKey(companyId),
redisKey(companyId, runtime.getModel()),
objectMapper.writeValueAsString(payload),
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
} catch (Exception e) {
@@ -339,9 +351,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
}
}
private AgentLlmRuntimeVO readRuntimeCache(Long companyId) {
private AgentLlmRuntimeVO readRuntimeCache(Long companyId, String model) {
try {
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId));
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, model));
if (!StringUtils.hasText(raw)) {
return null;
}
@@ -379,6 +391,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
}
private void evictRuntimeCache(Long companyId) {
stringRedisTemplate.delete(redisKey(companyId));
Set<String> keys = stringRedisTemplate.keys("agent:llm:rt:" + companyId + "*");
if (keys != null && !keys.isEmpty()) {
stringRedisTemplate.delete(keys);
}
}
}
@@ -950,5 +950,12 @@ SELECT 4802, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), '
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4802 OR `code` = 'agent:llm-settings');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('agent:chat', 'agent:llm-settings') WHERE m.route_name = 'AgentAssistant';
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:chat' WHERE m.route_name = 'AgentAssistant';
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
SELECT 14081, NULL, 0, 'AgentLlmSettings', '模型管理', '/agent/llm-settings', '/agent/llm-settings/index', '', 'lucide:brain-circuit', 'menu', 1, 1, 0, 15
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14081 OR `route_name` = 'AgentLlmSettings');
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:llm-settings' WHERE m.route_name = 'AgentLlmSettings';