mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 04:29:21 +08:00
feat: 公司 LLM 改为提供商凭证加多模型勾选并支持探测目录
This commit is contained in:
+11
-1
@@ -3,18 +3,21 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
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.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")
|
||||
@@ -34,4 +37,11 @@ public class AgentCompanyLlmSettingsController {
|
||||
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
||||
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto));
|
||||
}
|
||||
|
||||
@PostMapping("/probe-models")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "探测模型列表", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProbeModelsResultVO> probeModels(
|
||||
@RequestBody ProbeAgentLlmModelsDTO dto) {
|
||||
return ApiResponse.success(settingsService.probeModels(dto));
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
|
||||
|
||||
@Mapper
|
||||
public interface AgentCompanyLlmModelMapper extends BaseMapper<AgentCompanyLlmModelPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmProviderPO;
|
||||
|
||||
@Mapper
|
||||
public interface AgentCompanyLlmProviderMapper extends BaseMapper<AgentCompanyLlmProviderPO> {
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 启用模型条目。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmModelItemDTO {
|
||||
|
||||
@NotBlank(message = "model 不能为空")
|
||||
private String model;
|
||||
|
||||
private String label;
|
||||
|
||||
/** 正整数;空/0 表示自动估计 */
|
||||
private Integer contextWindow;
|
||||
|
||||
private Boolean isDefault;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 探测提供商 /v1/models;可用已存 Key 或临时 Key。
|
||||
*/
|
||||
@Data
|
||||
public class ProbeAgentLlmModelsDTO {
|
||||
|
||||
/** 必填;探测用的 Base URL */
|
||||
private String baseUrl;
|
||||
|
||||
/**
|
||||
* 临时 Key;与 useStoredKey 二选一。
|
||||
* 留空且 useStoredKey=true 时用库中密钥。
|
||||
*/
|
||||
private String apiKey;
|
||||
|
||||
/** 为 true 时使用已保存的 apiKey(须已配置) */
|
||||
private Boolean useStoredKey;
|
||||
}
|
||||
+10
-9
@@ -1,10 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 更新公司模型 API 配置。
|
||||
* 更新公司 LLM:凭证 + 启用模型列表(全量覆盖模型)。
|
||||
*/
|
||||
@Data
|
||||
public class UpsertAgentLlmSettingsDTO {
|
||||
@@ -12,15 +16,12 @@ public class UpsertAgentLlmSettingsDTO {
|
||||
@NotBlank(message = "baseUrl 不能为空")
|
||||
private String baseUrl;
|
||||
|
||||
@NotBlank(message = "model 不能为空")
|
||||
private String model;
|
||||
|
||||
/** 首次必填;后续留空表示不改 Key */
|
||||
private String apiKey;
|
||||
|
||||
/**
|
||||
* 模型上下文窗口(token)。空/不传表示不改(更新时)或由 Agent 估计(新建)。
|
||||
* 传正整数则写入;部分前端可用 0 表示清空为「自动估计」。
|
||||
*/
|
||||
private Integer contextWindow;
|
||||
private String displayName;
|
||||
|
||||
@NotEmpty(message = "至少启用一个模型")
|
||||
@Valid
|
||||
private List<AgentLlmModelItemDTO> models;
|
||||
}
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司已启用的 LLM 模型。
|
||||
*/
|
||||
@Data
|
||||
@TableName("agent_company_llm_model")
|
||||
public class AgentCompanyLlmModelPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("model")
|
||||
private String model;
|
||||
|
||||
@TableField("label")
|
||||
private String label;
|
||||
|
||||
@TableField("context_window")
|
||||
private Integer contextWindow;
|
||||
|
||||
@TableField("is_default")
|
||||
private Boolean isDefault;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司 Agent LLM 提供商凭证(一套 base_url + api_key)。
|
||||
*/
|
||||
@Data
|
||||
@TableName("agent_company_llm_provider")
|
||||
public class AgentCompanyLlmProviderPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("base_url")
|
||||
private String baseUrl;
|
||||
|
||||
@TableField("api_key_encrypted")
|
||||
private String apiKeyEncrypted;
|
||||
|
||||
@TableField("api_key_suffix")
|
||||
private String apiKeySuffix;
|
||||
|
||||
@TableField("display_name")
|
||||
private String displayName;
|
||||
|
||||
@TableField("extra_headers_json")
|
||||
private String extraHeadersJson;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 已启用模型条目(对外)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmModelVO {
|
||||
private String model;
|
||||
private String label;
|
||||
private Integer contextWindow;
|
||||
|
||||
@JsonProperty("isDefault")
|
||||
private boolean isDefault;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AgentLlmProbeModelsResultVO {
|
||||
private List<AgentLlmProbedModelVO> items;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 探测到的提供商模型(不落库)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmProbedModelVO {
|
||||
private String id;
|
||||
/** 厂商扩展字段解析;多数为 null */
|
||||
private Integer contextWindow;
|
||||
}
|
||||
+5
-3
@@ -2,6 +2,9 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 对公司管理员可见的模型配置(Key 仅掩码)。
|
||||
*/
|
||||
@@ -9,9 +12,8 @@ import lombok.Data;
|
||||
public class AgentLlmSettingsVO {
|
||||
private boolean configured;
|
||||
private String baseUrl;
|
||||
private String model;
|
||||
/** 上下文窗口 token;null 表示未配置、由 Agent 估计 */
|
||||
private Integer contextWindow;
|
||||
private String displayName;
|
||||
private String apiKeyMasked;
|
||||
private String updateTime;
|
||||
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||
}
|
||||
|
||||
+6
-2
@@ -1,11 +1,13 @@
|
||||
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.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||
|
||||
/**
|
||||
* 公司模型 API 配置。
|
||||
* 公司模型 API:凭证 + 多模型勾选。
|
||||
*/
|
||||
public interface AgentCompanyLlmSettingsService {
|
||||
|
||||
@@ -13,6 +15,8 @@ public interface AgentCompanyLlmSettingsService {
|
||||
|
||||
AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto);
|
||||
|
||||
/** Agent 内部:按公司取运行时明文配置 */
|
||||
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
|
||||
|
||||
/** Agent 内部:按公司取默认模型运行时明文 */
|
||||
AgentLlmRuntimeVO getRuntime(Long companyId);
|
||||
}
|
||||
|
||||
+179
-45
@@ -11,23 +11,35 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmSettingsMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmModelMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmProviderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.AgentLlmModelItemDTO;
|
||||
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.po.AgentCompanyLlmSettingsPO;
|
||||
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.AgentLlmModelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
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;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 公司模型 API:MySQL 存密文,Redis 缓存运行时明文供 Agent 注入。
|
||||
* 公司模型 API:MySQL 存密文与启用模型;Redis 缓存默认模型明文供 Agent。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -36,19 +48,22 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
|
||||
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
||||
|
||||
private final AgentCompanyLlmSettingsMapper mapper;
|
||||
private final AgentCompanyLlmProviderMapper providerMapper;
|
||||
private final AgentCompanyLlmModelMapper modelMapper;
|
||||
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;
|
||||
|
||||
@Override
|
||||
public AgentLlmSettingsVO getForCurrentCompany() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
||||
return toPublicVo(po);
|
||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
||||
return toPublicVo(provider, models);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -56,15 +71,12 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
if (!currentUserContext.isCurrentUserSuper()
|
||||
&& !companyMemberService.isOwner(userId, companyId)) {
|
||||
throw new BusinessException("仅公司拥有者可配置模型 API");
|
||||
}
|
||||
requireOwner(companyId, userId);
|
||||
|
||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||
String model = dto.getModel().trim();
|
||||
AgentCompanyLlmSettingsPO existing = findByCompany(companyId);
|
||||
List<AgentLlmModelItemDTO> modelItems = normalizeModelItems(dto.getModels());
|
||||
|
||||
AgentCompanyLlmProviderPO existing = findProvider(companyId);
|
||||
String encrypted;
|
||||
String suffix;
|
||||
String apiKey = dto.getApiKey();
|
||||
@@ -80,37 +92,79 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
|
||||
if (existing == null) {
|
||||
AgentCompanyLlmSettingsPO po = new AgentCompanyLlmSettingsPO();
|
||||
AgentCompanyLlmProviderPO po = new AgentCompanyLlmProviderPO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setBaseUrl(baseUrl);
|
||||
po.setApiKeyEncrypted(encrypted);
|
||||
po.setApiKeySuffix(suffix);
|
||||
po.setModel(model);
|
||||
po.setContextWindow(normalizeContextWindow(dto.getContextWindow()));
|
||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
mapper.insert(po);
|
||||
providerMapper.insert(po);
|
||||
existing = po;
|
||||
} else {
|
||||
existing.setBaseUrl(baseUrl);
|
||||
existing.setApiKeyEncrypted(encrypted);
|
||||
existing.setApiKeySuffix(suffix);
|
||||
existing.setModel(model);
|
||||
if (dto.getContextWindow() != null) {
|
||||
existing.setContextWindow(normalizeContextWindow(dto.getContextWindow()));
|
||||
if (dto.getDisplayName() != null) {
|
||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
}
|
||||
existing.setUpdateBy(userId);
|
||||
mapper.updateById(existing);
|
||||
providerMapper.updateById(existing);
|
||||
}
|
||||
|
||||
// 全量覆盖模型:先删后插
|
||||
modelMapper.delete(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId));
|
||||
for (AgentLlmModelItemDTO item : modelItems) {
|
||||
AgentCompanyLlmModelPO m = new AgentCompanyLlmModelPO();
|
||||
m.setCompanyId(companyId);
|
||||
m.setModel(item.getModel().trim());
|
||||
m.setLabel(trimToNull(item.getLabel()));
|
||||
m.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||
m.setIsDefault(Boolean.TRUE.equals(item.getIsDefault()));
|
||||
m.setCreateBy(userId);
|
||||
m.setUpdateBy(userId);
|
||||
modelMapper.insert(m);
|
||||
}
|
||||
|
||||
List<AgentCompanyLlmModelPO> savedModels = listModels(companyId);
|
||||
evictRuntimeCache(companyId);
|
||||
// 预热缓存,降低 Agent 首包延迟
|
||||
try {
|
||||
cacheRuntime(companyId, buildRuntime(existing));
|
||||
cacheRuntime(companyId, buildRuntime(existing, savedModels));
|
||||
} catch (Exception e) {
|
||||
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e);
|
||||
}
|
||||
return toPublicVo(existing);
|
||||
return toPublicVo(existing, savedModels);
|
||||
}
|
||||
|
||||
@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 不能为空");
|
||||
}
|
||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||
String apiKey;
|
||||
if (Boolean.TRUE.equals(dto.getUseStoredKey())) {
|
||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||
if (provider == null) {
|
||||
throw new BusinessException("尚未保存 API Key,请先填写密钥或关闭「使用已存密钥」");
|
||||
}
|
||||
apiKey = crypto.decrypt(provider.getApiKeyEncrypted());
|
||||
} else if (StringUtils.hasText(dto.getApiKey()) && !dto.getApiKey().trim().startsWith("****")) {
|
||||
apiKey = dto.getApiKey().trim();
|
||||
} else {
|
||||
throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥");
|
||||
}
|
||||
|
||||
List<AgentLlmProbedModelVO> items = modelsProbe.listModels(baseUrl, apiKey);
|
||||
AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO();
|
||||
vo.setItems(items);
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -122,26 +176,80 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
||||
if (po == null) {
|
||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||
if (provider == null) {
|
||||
throw new BusinessException("公司尚未配置模型 API");
|
||||
}
|
||||
AgentLlmRuntimeVO runtime = buildRuntime(po);
|
||||
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
||||
if (models.isEmpty()) {
|
||||
throw new BusinessException("公司尚未启用任何模型");
|
||||
}
|
||||
AgentLlmRuntimeVO runtime = buildRuntime(provider, models);
|
||||
cacheRuntime(companyId, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO buildRuntime(AgentCompanyLlmSettingsPO po) {
|
||||
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("至少启用一个模型");
|
||||
}
|
||||
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);
|
||||
if (item == null || !StringUtils.hasText(item.getModel())) {
|
||||
continue;
|
||||
}
|
||||
String id = item.getModel().trim();
|
||||
if (!seen.add(id)) {
|
||||
continue;
|
||||
}
|
||||
AgentLlmModelItemDTO copy = new AgentLlmModelItemDTO();
|
||||
copy.setModel(id);
|
||||
copy.setLabel(item.getLabel());
|
||||
copy.setContextWindow(item.getContextWindow());
|
||||
copy.setIsDefault(Boolean.TRUE.equals(item.getIsDefault()));
|
||||
if (Boolean.TRUE.equals(copy.getIsDefault())) {
|
||||
defaultIdx = out.size();
|
||||
}
|
||||
out.add(copy);
|
||||
}
|
||||
if (out.isEmpty()) {
|
||||
throw new BusinessException("至少启用一个模型");
|
||||
}
|
||||
if (defaultIdx < 0) {
|
||||
out.get(0).setIsDefault(true);
|
||||
} else {
|
||||
for (int i = 0; i < out.size(); i++) {
|
||||
out.get(i).setIsDefault(i == defaultIdx);
|
||||
}
|
||||
}
|
||||
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));
|
||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||
vo.setBaseUrl(po.getBaseUrl());
|
||||
vo.setApiKey(crypto.decrypt(po.getApiKeyEncrypted()));
|
||||
vo.setModel(po.getModel());
|
||||
vo.setContextWindow(po.getContextWindow());
|
||||
vo.setExtraHeaders(parseHeaders(po.getExtraHeadersJson()));
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||
vo.setModel(def.getModel());
|
||||
vo.setContextWindow(def.getContextWindow());
|
||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 0 或负数视为清空(自动估计);正整数写入。 */
|
||||
private static Integer normalizeContextWindow(Integer raw) {
|
||||
if (raw == null || raw <= 0) {
|
||||
return null;
|
||||
@@ -149,6 +257,14 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static String trimToNull(String s) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
return null;
|
||||
}
|
||||
String t = s.trim();
|
||||
return t.isEmpty() ? null : t;
|
||||
}
|
||||
|
||||
private Map<String, String> parseHeaders(String json) {
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return Map.of();
|
||||
@@ -161,26 +277,43 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
}
|
||||
|
||||
private AgentCompanyLlmSettingsPO findByCompany(Long companyId) {
|
||||
return mapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmSettingsPO>()
|
||||
.eq(AgentCompanyLlmSettingsPO::getCompanyId, companyId)
|
||||
private AgentCompanyLlmProviderPO findProvider(Long companyId) {
|
||||
return providerMapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmProviderPO>()
|
||||
.eq(AgentCompanyLlmProviderPO::getCompanyId, companyId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private AgentLlmSettingsVO toPublicVo(AgentCompanyLlmSettingsPO po) {
|
||||
private List<AgentCompanyLlmModelPO> listModels(Long companyId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
private AgentLlmSettingsVO toPublicVo(
|
||||
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
|
||||
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
|
||||
if (po == null) {
|
||||
if (provider == null) {
|
||||
vo.setConfigured(false);
|
||||
return vo;
|
||||
}
|
||||
vo.setConfigured(true);
|
||||
vo.setBaseUrl(po.getBaseUrl());
|
||||
vo.setModel(po.getModel());
|
||||
vo.setContextWindow(po.getContextWindow());
|
||||
vo.setApiKeyMasked("****" + (po.getApiKeySuffix() == null ? "" : po.getApiKeySuffix()));
|
||||
if (po.getUpdateTime() != null) {
|
||||
vo.setUpdateTime(po.getUpdateTime().format(ISO));
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setDisplayName(provider.getDisplayName());
|
||||
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||
if (provider.getUpdateTime() != null) {
|
||||
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||
}
|
||||
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);
|
||||
}
|
||||
vo.setModels(modelVos);
|
||||
return vo;
|
||||
}
|
||||
|
||||
@@ -195,7 +328,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
payload.put("api_key", runtime.getApiKey());
|
||||
payload.put("model", runtime.getModel());
|
||||
payload.put("context_window", runtime.getContextWindow());
|
||||
payload.put("extra_headers", runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
payload.put("extra_headers",
|
||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
redisKey(companyId),
|
||||
objectMapper.writeValueAsString(payload),
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 出站探测 OpenAI Compatible GET /models(不落库、不打明文 Key 日志)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OpenAiCompatibleModelsProbe {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
public List<AgentLlmProbedModelVO> listModels(String baseUrl, String apiKey) {
|
||||
if (!StringUtils.hasText(baseUrl) || !StringUtils.hasText(apiKey)) {
|
||||
throw new BusinessException("探测模型需要 baseUrl 与 apiKey");
|
||||
}
|
||||
String root = baseUrl.trim().replaceAll("/+$", "");
|
||||
String url = root.endsWith("/v1") ? root + "/models" : root + "/v1/models";
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(apiKey.trim());
|
||||
headers.set(HttpHeaders.ACCEPT, "application/json");
|
||||
try {
|
||||
ResponseEntity<String> resp = restTemplate.exchange(
|
||||
url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
|
||||
if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
|
||||
throw new BusinessException("提供商返回异常 HTTP " + resp.getStatusCode().value());
|
||||
}
|
||||
return parse(resp.getBody());
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (RestClientException e) {
|
||||
log.warn("探测 /models 失败: {}", e.getMessage());
|
||||
throw new BusinessException("无法加载模型列表:" + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.warn("解析 /models 失败: {}", e.getMessage());
|
||||
throw new BusinessException("解析模型列表失败");
|
||||
}
|
||||
}
|
||||
|
||||
private List<AgentLlmProbedModelVO> parse(String body) throws Exception {
|
||||
JsonNode root = objectMapper.readTree(body);
|
||||
JsonNode data = root.get("data");
|
||||
if (data == null || !data.isArray()) {
|
||||
// 少数网关直接返回数组
|
||||
data = root.isArray() ? root : null;
|
||||
}
|
||||
if (data == null || !data.isArray()) {
|
||||
throw new BusinessException("模型列表格式无法识别");
|
||||
}
|
||||
List<AgentLlmProbedModelVO> out = new ArrayList<>();
|
||||
for (JsonNode node : data) {
|
||||
String id = text(node, "id");
|
||||
if (!StringUtils.hasText(id)) {
|
||||
continue;
|
||||
}
|
||||
AgentLlmProbedModelVO vo = new AgentLlmProbedModelVO();
|
||||
vo.setId(id);
|
||||
vo.setContextWindow(extractContextWindow(node));
|
||||
out.add(vo);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Integer extractContextWindow(JsonNode node) {
|
||||
Integer n = intOrNull(node, "context_window");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
n = intOrNull(node, "context_length");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
n = intOrNull(node, "max_model_len");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
n = intOrNull(node, "max_tokens");
|
||||
if (n != null && n >= 4096) {
|
||||
return n;
|
||||
}
|
||||
// 嵌套 meta
|
||||
JsonNode meta = node.get("meta");
|
||||
if (meta != null && meta.isObject()) {
|
||||
n = intOrNull(meta, "context_length");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
return v == null || v.isNull() ? null : v.asText();
|
||||
}
|
||||
|
||||
private static Integer intOrNull(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
if (v == null || v.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (v.isNumber()) {
|
||||
int n = v.asInt();
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
if (v.isTextual()) {
|
||||
try {
|
||||
int n = Integer.parseInt(v.asText().trim());
|
||||
return n > 0 ? n : null;
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user