mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
refactor: 模型管理改为表格与弹窗交互
This commit is contained in:
@@ -185,7 +185,7 @@ apps/agent/
|
||||
| 表 | 说明 |
|
||||
|----|------|
|
||||
| `agent_company_llm_provider` | 公司多套 `base_url` + 加密 Key |
|
||||
| `agent_company_llm_model` | 挂 `provider_id`;`UNIQUE(provider_id, model)`;公司级全局一条 `is_default=1` |
|
||||
| `agent_company_llm_model` | 挂 `provider_id`;`UNIQUE(provider_id, model)`;`enabled` 启停;公司级全局一条 `is_default=1`(须启用) |
|
||||
|
||||
浏览器:
|
||||
- `GET/POST /api/company/agent-llm-providers`;`GET/PUT/DELETE .../providers/{id}`;`PUT .../providers/{id}/models`(增量 upsert)
|
||||
|
||||
@@ -33,7 +33,8 @@ CREATE TABLE IF NOT EXISTS `agent_company_llm_model` (
|
||||
`model` varchar(200) NOT NULL COMMENT '提供商模型 id',
|
||||
`label` varchar(200) NULL COMMENT '展示名',
|
||||
`context_window` int UNSIGNED NULL COMMENT '上下文窗口 token,空则 Agent 估计',
|
||||
`is_default` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否公司默认聊天模型(全局唯一)',
|
||||
`is_default` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否公司默认聊天模型(全局唯一,且须 enabled=1)',
|
||||
`enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用:1启用 0禁用',
|
||||
`create_by` bigint UNSIGNED NULL,
|
||||
`update_by` bigint UNSIGNED NULL,
|
||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
@@ -41,6 +42,7 @@ CREATE TABLE IF NOT EXISTS `agent_company_llm_model` (
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_agent_llm_model_provider_model` (`provider_id`, `model`),
|
||||
KEY `idx_agent_llm_model_company_default` (`company_id`, `is_default`),
|
||||
KEY `idx_agent_llm_model_company_enabled` (`company_id`, `enabled`),
|
||||
KEY `idx_agent_llm_model_provider` (`provider_id`),
|
||||
CONSTRAINT `fk_agent_llm_model_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE,
|
||||
CONSTRAINT `fk_agent_llm_model_provider` FOREIGN KEY (`provider_id`) REFERENCES `agent_company_llm_provider` (`id`) ON DELETE CASCADE
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 模型启用/禁用状态:enabled=1 可用,0 禁用(仍保留配置,不删行)
|
||||
|
||||
ALTER TABLE `agent_company_llm_model`
|
||||
ADD COLUMN `enabled` tinyint(1) NOT NULL DEFAULT 1 COMMENT '是否启用:1启用 0禁用' AFTER `is_default`,
|
||||
ADD KEY `idx_agent_llm_model_company_enabled` (`company_id`, `enabled`);
|
||||
+9
@@ -14,6 +14,7 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.SetAgentLlmModelEnabledDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
@@ -73,6 +74,14 @@ public class AgentCompanyLlmSettingsController {
|
||||
return ApiResponse.success("保存成功", settingsService.upsertProviderModels(id, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/agent-llm-providers/{id}/models/enabled")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "启用或禁用模型", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderVO> setModelEnabled(
|
||||
@PathVariable("id") Long id,
|
||||
@Valid @RequestBody SetAgentLlmModelEnabledDTO dto) {
|
||||
return ApiResponse.success("已更新", settingsService.setModelEnabled(id, dto));
|
||||
}
|
||||
|
||||
@PostMapping("/agent-llm-settings/probe-models")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "探测模型列表", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProbeModelsResultVO> probeModels(
|
||||
|
||||
+3
@@ -18,4 +18,7 @@ public class AgentLlmModelItemDTO {
|
||||
private Integer contextWindow;
|
||||
|
||||
private Boolean isDefault;
|
||||
|
||||
/** 是否启用;缺省 true */
|
||||
private Boolean enabled;
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 切换模型启用状态。
|
||||
*/
|
||||
@Data
|
||||
public class SetAgentLlmModelEnabledDTO {
|
||||
|
||||
@NotBlank(message = "model 不能为空")
|
||||
private String model;
|
||||
|
||||
@NotNull(message = "enabled 不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
+4
@@ -36,6 +36,10 @@ public class AgentCompanyLlmModelPO {
|
||||
@TableField("is_default")
|
||||
private Boolean isDefault;
|
||||
|
||||
/** 是否启用:true 可聊天选用 */
|
||||
@TableField("enabled")
|
||||
private Boolean enabled;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
|
||||
+4
@@ -8,6 +8,7 @@ import lombok.Data;
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmModelVO {
|
||||
private Long id;
|
||||
private Long providerId;
|
||||
private String providerDisplayName;
|
||||
private String model;
|
||||
@@ -16,4 +17,7 @@ public class AgentLlmModelVO {
|
||||
|
||||
@JsonProperty("isDefault")
|
||||
private boolean isDefault;
|
||||
|
||||
/** 是否启用(聊天仅可选启用的) */
|
||||
private boolean enabled;
|
||||
}
|
||||
|
||||
+4
@@ -2,6 +2,7 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.SetAgentLlmModelEnabledDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
@@ -28,6 +29,9 @@ public interface AgentCompanyLlmSettingsService {
|
||||
/** 按 (provider_id, model) 增量 upsert,不删再建仍保留的行 */
|
||||
AgentLlmProviderVO upsertProviderModels(Long providerId, UpsertAgentLlmProviderModelsDTO dto);
|
||||
|
||||
/** 启用/禁用某模型(禁用若为默认则自动改派) */
|
||||
AgentLlmProviderVO setModelEnabled(Long providerId, SetAgentLlmModelEnabledDTO dto);
|
||||
|
||||
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
|
||||
|
||||
/** 聊天用:启用模型列表(无 Key,含 providerId) */
|
||||
|
||||
+64
-6
@@ -17,6 +17,7 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmProvide
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.AgentLlmModelItemDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.SetAgentLlmModelEnabledDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
|
||||
@@ -163,6 +164,10 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
for (AgentLlmModelItemDTO item : items) {
|
||||
String modelId = item.getModel().trim();
|
||||
keep.add(modelId);
|
||||
boolean enabled = item.getEnabled() == null || Boolean.TRUE.equals(item.getEnabled());
|
||||
if (Boolean.TRUE.equals(item.getIsDefault()) && !enabled) {
|
||||
throw new BusinessException("禁用的模型不能设为公司默认: " + modelId);
|
||||
}
|
||||
AgentCompanyLlmModelPO row = existingByModel.get(modelId);
|
||||
if (row == null) {
|
||||
row = new AgentCompanyLlmModelPO();
|
||||
@@ -172,12 +177,14 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
row.setLabel(trimToNull(item.getLabel()));
|
||||
row.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||
row.setIsDefault(false);
|
||||
row.setEnabled(enabled);
|
||||
row.setCreateBy(userId);
|
||||
row.setUpdateBy(userId);
|
||||
modelMapper.insert(row);
|
||||
} else {
|
||||
row.setLabel(trimToNull(item.getLabel()));
|
||||
row.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||
row.setEnabled(enabled);
|
||||
row.setUpdateBy(userId);
|
||||
modelMapper.updateById(row);
|
||||
}
|
||||
@@ -208,6 +215,35 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
return toProviderVo(provider, saved);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AgentLlmProviderVO setModelEnabled(Long providerId, SetAgentLlmModelEnabledDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, providerId);
|
||||
String modelId = dto.getModel().trim();
|
||||
boolean enabled = Boolean.TRUE.equals(dto.getEnabled());
|
||||
|
||||
AgentCompanyLlmModelPO row = modelMapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getProviderId, providerId)
|
||||
.eq(AgentCompanyLlmModelPO::getModel, modelId)
|
||||
.last("LIMIT 1"));
|
||||
if (row == null) {
|
||||
throw new BusinessException("模型不存在: " + modelId);
|
||||
}
|
||||
row.setEnabled(enabled);
|
||||
row.setUpdateBy(userId);
|
||||
if (!enabled && Boolean.TRUE.equals(row.getIsDefault())) {
|
||||
row.setIsDefault(false);
|
||||
}
|
||||
modelMapper.updateById(row);
|
||||
ensureCompanyHasDefault(companyId, userId);
|
||||
evictRuntimeCache(companyId);
|
||||
warmCacheForProvider(provider);
|
||||
return toProviderVo(provider, listModelsByProvider(companyId, providerId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
@@ -249,7 +285,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
.collect(Collectors.toMap(AgentCompanyLlmProviderPO::getId, p -> p));
|
||||
AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO();
|
||||
List<AgentLlmModelVO> items = new ArrayList<>();
|
||||
for (AgentCompanyLlmModelPO m : listModels(companyId)) {
|
||||
for (AgentCompanyLlmModelPO m : listEnabledModels(companyId)) {
|
||||
items.add(toModelVo(m, providers.get(m.getProviderId())));
|
||||
}
|
||||
vo.setItems(items);
|
||||
@@ -261,7 +297,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
||||
List<AgentCompanyLlmModelPO> models = listEnabledModels(companyId);
|
||||
if (models.isEmpty()) {
|
||||
throw new BusinessException("公司尚未启用任何模型");
|
||||
}
|
||||
@@ -343,6 +379,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
copy.setLabel(item.getLabel());
|
||||
copy.setContextWindow(item.getContextWindow());
|
||||
copy.setIsDefault(Boolean.TRUE.equals(item.getIsDefault()));
|
||||
copy.setEnabled(item.getEnabled() == null || Boolean.TRUE.equals(item.getEnabled()));
|
||||
if (Boolean.TRUE.equals(copy.getIsDefault())) {
|
||||
defaultIdx = out.size();
|
||||
}
|
||||
@@ -355,6 +392,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
for (int i = 0; i < out.size(); i++) {
|
||||
out.get(i).setIsDefault(i == defaultIdx);
|
||||
}
|
||||
// 默认必须启用
|
||||
out.get(defaultIdx).setEnabled(true);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -367,15 +406,18 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
|
||||
private void ensureCompanyHasDefault(Long companyId, Long userId) {
|
||||
List<AgentCompanyLlmModelPO> all = listModels(companyId);
|
||||
if (all.isEmpty()) {
|
||||
List<AgentCompanyLlmModelPO> enabled = listEnabledModels(companyId);
|
||||
if (enabled.isEmpty()) {
|
||||
// 无可用模型则清掉所有默认标记
|
||||
clearCompanyDefaults(companyId);
|
||||
return;
|
||||
}
|
||||
boolean has = all.stream().anyMatch(m -> Boolean.TRUE.equals(m.getIsDefault()));
|
||||
boolean has = enabled.stream().anyMatch(m -> Boolean.TRUE.equals(m.getIsDefault()));
|
||||
if (has) {
|
||||
return;
|
||||
}
|
||||
AgentCompanyLlmModelPO first = all.get(0);
|
||||
AgentCompanyLlmModelPO first = enabled.get(0);
|
||||
clearCompanyDefaults(companyId);
|
||||
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getId, first.getId())
|
||||
.set(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||
@@ -397,6 +439,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
private void warmCacheForProvider(AgentCompanyLlmProviderPO provider) {
|
||||
try {
|
||||
for (AgentCompanyLlmModelPO m : listModelsByProvider(provider.getCompanyId(), provider.getId())) {
|
||||
if (!Boolean.TRUE.equals(m.getEnabled())) {
|
||||
continue;
|
||||
}
|
||||
cacheRuntime(provider.getCompanyId(), buildRuntimeForModel(provider, m));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -457,16 +502,28 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
/** 聊天/runtime:仅启用中的模型 */
|
||||
private List<AgentCompanyLlmModelPO> listEnabledModels(Long companyId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getEnabled, true)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getProviderId)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
private List<AgentCompanyLlmModelPO> listModelsByProvider(Long companyId, Long providerId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getProviderId, providerId)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getEnabled)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m, AgentCompanyLlmProviderPO provider) {
|
||||
AgentLlmModelVO mv = new AgentLlmModelVO();
|
||||
mv.setId(m.getId());
|
||||
mv.setProviderId(m.getProviderId());
|
||||
if (provider != null) {
|
||||
mv.setProviderDisplayName(
|
||||
@@ -478,6 +535,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
mv.setLabel(m.getLabel());
|
||||
mv.setContextWindow(m.getContextWindow());
|
||||
mv.setDefault(Boolean.TRUE.equals(m.getIsDefault()));
|
||||
mv.setEnabled(m.getEnabled() == null || Boolean.TRUE.equals(m.getEnabled()));
|
||||
return mv;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,12 +25,14 @@ export namespace AgentVO {
|
||||
}
|
||||
|
||||
export interface LlmModelItem {
|
||||
id?: number;
|
||||
providerId: number;
|
||||
providerDisplayName?: string | null;
|
||||
model: string;
|
||||
label?: string | null;
|
||||
contextWindow?: number | null;
|
||||
isDefault?: boolean;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface LlmProvider {
|
||||
@@ -104,6 +106,12 @@ export async function listAgentLlmProvidersApi() {
|
||||
);
|
||||
}
|
||||
|
||||
export async function getAgentLlmProviderApi(providerId: number) {
|
||||
return requestClient.get<AgentVO.LlmProvider>(
|
||||
`/company/agent-llm-providers/${providerId}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createAgentLlmProviderApi(body: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
@@ -138,6 +146,7 @@ export async function upsertAgentLlmProviderModelsApi(
|
||||
label?: string;
|
||||
contextWindow?: number | null;
|
||||
isDefault?: boolean;
|
||||
enabled?: boolean;
|
||||
}>,
|
||||
) {
|
||||
return requestClient.put<AgentVO.LlmProvider>(
|
||||
@@ -146,6 +155,16 @@ export async function upsertAgentLlmProviderModelsApi(
|
||||
);
|
||||
}
|
||||
|
||||
export async function setAgentLlmModelEnabledApi(
|
||||
providerId: number,
|
||||
body: { model: string; enabled: boolean },
|
||||
) {
|
||||
return requestClient.put<AgentVO.LlmProvider>(
|
||||
`/company/agent-llm-providers/${providerId}/models/enabled`,
|
||||
body,
|
||||
);
|
||||
}
|
||||
|
||||
/** 聊天选模型:已启用列表,不含 Key */
|
||||
export async function listAgentEnabledLlmModelsApi() {
|
||||
return requestClient.get<{ items: AgentVO.LlmModelItem[] }>(
|
||||
|
||||
@@ -4,6 +4,7 @@ export {
|
||||
createAgentSessionApi,
|
||||
deleteAgentLlmProviderApi,
|
||||
deleteAgentMemoryApi,
|
||||
getAgentLlmProviderApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentLlmProvidersApi,
|
||||
listAgentMemoriesApi,
|
||||
@@ -11,6 +12,7 @@ export {
|
||||
listAgentSessionsApi,
|
||||
patchAgentSessionApi,
|
||||
probeAgentLlmModelsApi,
|
||||
setAgentLlmModelEnabledApi,
|
||||
streamAgentChat,
|
||||
updateAgentLlmProviderApi,
|
||||
upsertAgentLlmProviderModelsApi,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
<script lang="ts" setup>
|
||||
import type { AgentVO } from '#/api/agent';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Form,
|
||||
FormItem,
|
||||
Input,
|
||||
InputPassword,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createAgentLlmProviderApi,
|
||||
updateAgentLlmProviderApi,
|
||||
} from '#/api/agent';
|
||||
|
||||
defineOptions({ name: 'ProviderFormModal' });
|
||||
|
||||
const emit = defineEmits<{ success: [] }>();
|
||||
|
||||
const editing = ref<AgentVO.LlmProvider | null>(null);
|
||||
const saving = ref(false);
|
||||
const form = ref({
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
displayName: '',
|
||||
});
|
||||
|
||||
const isEdit = computed(() => !!editing.value);
|
||||
const modalTitle = computed(() =>
|
||||
isEdit.value ? '编辑提供商' : '添加提供商',
|
||||
);
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[520px]',
|
||||
onCancel() {
|
||||
modalApi.close();
|
||||
},
|
||||
async onConfirm() {
|
||||
await handleSubmit();
|
||||
},
|
||||
});
|
||||
|
||||
function open(row?: AgentVO.LlmProvider) {
|
||||
editing.value = row ?? null;
|
||||
form.value = {
|
||||
baseUrl: row?.baseUrl || '',
|
||||
apiKey: '',
|
||||
displayName: row?.displayName || '',
|
||||
};
|
||||
modalApi.setState({ title: modalTitle.value });
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!form.value.baseUrl.trim()) {
|
||||
message.warning('请填写 Base URL');
|
||||
return;
|
||||
}
|
||||
if (!isEdit.value && !form.value.apiKey.trim()) {
|
||||
message.warning('请填写 API Key');
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
modalApi.setState({ confirming: true });
|
||||
try {
|
||||
if (isEdit.value && editing.value) {
|
||||
await updateAgentLlmProviderApi(editing.value.id, {
|
||||
baseUrl: form.value.baseUrl.trim(),
|
||||
apiKey: form.value.apiKey.trim() || undefined,
|
||||
displayName: form.value.displayName.trim(),
|
||||
});
|
||||
message.success('已保存');
|
||||
} else {
|
||||
await createAgentLlmProviderApi({
|
||||
baseUrl: form.value.baseUrl.trim(),
|
||||
apiKey: form.value.apiKey.trim(),
|
||||
displayName: form.value.displayName.trim() || undefined,
|
||||
});
|
||||
message.success('已创建');
|
||||
}
|
||||
modalApi.close();
|
||||
emit('success');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
modalApi.setState({ confirming: false });
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :title="modalTitle">
|
||||
<Form layout="vertical" class="pt-2">
|
||||
<FormItem label="Base URL" required>
|
||||
<Input
|
||||
v-model:value="form.baseUrl"
|
||||
placeholder="https://api.deepseek.com/v1"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem
|
||||
:label="
|
||||
isEdit && editing?.apiKeyMasked
|
||||
? `API Key(已配置 ${editing.apiKeyMasked},留空不改)`
|
||||
: 'API Key'
|
||||
"
|
||||
:required="!isEdit"
|
||||
>
|
||||
<InputPassword v-model:value="form.apiKey" placeholder="sk-..." />
|
||||
</FormItem>
|
||||
<FormItem label="备注(可选)">
|
||||
<Input v-model:value="form.displayName" placeholder="如 DeepSeek" />
|
||||
</FormItem>
|
||||
</Form>
|
||||
</Modal>
|
||||
</template>
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
<script lang="ts" setup>
|
||||
import type { AgentVO } from '#/api/agent';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Input,
|
||||
InputNumber,
|
||||
Radio,
|
||||
Switch,
|
||||
Tag,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
getAgentLlmProviderApi,
|
||||
probeAgentLlmModelsApi,
|
||||
setAgentLlmModelEnabledApi,
|
||||
upsertAgentLlmProviderModelsApi,
|
||||
} from '#/api/agent';
|
||||
|
||||
defineOptions({ name: 'ProviderModelsModal' });
|
||||
|
||||
const emit = defineEmits<{ success: [] }>();
|
||||
|
||||
type ModelRow = {
|
||||
model: string;
|
||||
contextWindow: number | null;
|
||||
isDefault: boolean;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
const provider = ref<AgentVO.LlmProvider | null>(null);
|
||||
const modelRows = ref<ModelRow[]>([]);
|
||||
const probedModels = ref<AgentVO.ProbedLlmModel[]>([]);
|
||||
const manualModelId = ref('');
|
||||
const probing = ref(false);
|
||||
const saving = ref(false);
|
||||
const togglingModel = ref<string | null>(null);
|
||||
|
||||
const modalTitle = computed(
|
||||
() =>
|
||||
`模型管理 — ${provider.value?.displayName || provider.value?.baseUrl || ''}`,
|
||||
);
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
draggable: true,
|
||||
class: 'w-[720px]',
|
||||
onCancel() {
|
||||
modalApi.close();
|
||||
},
|
||||
async onConfirm() {
|
||||
await handleSave();
|
||||
},
|
||||
});
|
||||
|
||||
function applyProviderModels(detail: AgentVO.LlmProvider) {
|
||||
provider.value = detail;
|
||||
modelRows.value = (detail.models || []).map((m) => ({
|
||||
model: m.model,
|
||||
contextWindow:
|
||||
m.contextWindow != null && m.contextWindow > 0 ? m.contextWindow : null,
|
||||
isDefault: !!m.isDefault,
|
||||
enabled: m.enabled !== false,
|
||||
}));
|
||||
}
|
||||
|
||||
async function open(row: AgentVO.LlmProvider) {
|
||||
provider.value = row;
|
||||
probedModels.value = [];
|
||||
manualModelId.value = '';
|
||||
try {
|
||||
let detail = row;
|
||||
try {
|
||||
detail = await getAgentLlmProviderApi(row.id);
|
||||
} catch {
|
||||
/* 列表数据足够时回退 */
|
||||
}
|
||||
applyProviderModels(detail);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载模型失败');
|
||||
return;
|
||||
}
|
||||
modalApi.setState({ title: modalTitle.value });
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
function isInList(id: string) {
|
||||
return modelRows.value.some((m) => m.model === id);
|
||||
}
|
||||
|
||||
function toggleProbed(p: AgentVO.ProbedLlmModel, checked: boolean) {
|
||||
if (checked) {
|
||||
if (isInList(p.id)) return;
|
||||
modelRows.value.push({
|
||||
model: p.id,
|
||||
contextWindow:
|
||||
p.contextWindow != null && p.contextWindow > 0
|
||||
? p.contextWindow
|
||||
: null,
|
||||
isDefault: false,
|
||||
enabled: true,
|
||||
});
|
||||
} else {
|
||||
modelRows.value = modelRows.value.filter((m) => m.model !== p.id);
|
||||
}
|
||||
}
|
||||
|
||||
function setDefault(modelId: string) {
|
||||
const row = modelRows.value.find((m) => m.model === modelId);
|
||||
if (!row?.enabled) {
|
||||
message.warning('请先启用该模型再设为默认');
|
||||
return;
|
||||
}
|
||||
modelRows.value = modelRows.value.map((m) => ({
|
||||
...m,
|
||||
isDefault: m.model === modelId,
|
||||
}));
|
||||
}
|
||||
|
||||
function removeModel(modelId: string) {
|
||||
const wasDefault = modelRows.value.find((m) => m.model === modelId)?.isDefault;
|
||||
modelRows.value = modelRows.value.filter((m) => m.model !== modelId);
|
||||
if (wasDefault) {
|
||||
const firstEnabled = modelRows.value.find((m) => m.enabled);
|
||||
if (firstEnabled) firstEnabled.isDefault = true;
|
||||
}
|
||||
}
|
||||
|
||||
function addManual() {
|
||||
const id = manualModelId.value.trim();
|
||||
if (!id) {
|
||||
message.warning('请输入模型 id');
|
||||
return;
|
||||
}
|
||||
if (isInList(id)) {
|
||||
message.warning('该模型已在列表中');
|
||||
return;
|
||||
}
|
||||
modelRows.value.push({
|
||||
model: id,
|
||||
contextWindow: null,
|
||||
isDefault: false,
|
||||
enabled: true,
|
||||
});
|
||||
manualModelId.value = '';
|
||||
}
|
||||
|
||||
async function toggleEnabled(row: ModelRow, enabled: boolean) {
|
||||
if (!provider.value) return;
|
||||
if (!enabled && row.isDefault) {
|
||||
// 本地先清默认,保存/接口都会改派
|
||||
row.isDefault = false;
|
||||
}
|
||||
if (enabled === false && modelRows.value.filter((m) => m.enabled && m.model !== row.model).length === 0) {
|
||||
// 允许全部禁用,服务端会清默认
|
||||
}
|
||||
togglingModel.value = row.model;
|
||||
try {
|
||||
// 未落库的新行仅改本地;已在库中的立刻调接口
|
||||
const existsOnServer = (provider.value.models || []).some(
|
||||
(m) => m.model === row.model,
|
||||
);
|
||||
row.enabled = enabled;
|
||||
if (enabled && !modelRows.value.some((m) => m.isDefault)) {
|
||||
row.isDefault = true;
|
||||
}
|
||||
if (existsOnServer) {
|
||||
const p = await setAgentLlmModelEnabledApi(provider.value.id, {
|
||||
model: row.model,
|
||||
enabled,
|
||||
});
|
||||
applyProviderModels(p);
|
||||
emit('success');
|
||||
message.success(enabled ? '已启用' : '已禁用');
|
||||
}
|
||||
} catch (e: any) {
|
||||
row.enabled = !enabled;
|
||||
message.error(e?.message || '更新状态失败');
|
||||
} finally {
|
||||
togglingModel.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function probe() {
|
||||
if (!provider.value) return;
|
||||
probing.value = true;
|
||||
try {
|
||||
const res = await probeAgentLlmModelsApi({
|
||||
useStoredKey: true,
|
||||
providerId: provider.value.id,
|
||||
});
|
||||
probedModels.value = res.items || [];
|
||||
if (probedModels.value.length === 0) {
|
||||
message.warning('未返回模型,可手动添加');
|
||||
} else {
|
||||
message.success(`已加载 ${probedModels.value.length} 个模型`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载模型列表失败');
|
||||
} finally {
|
||||
probing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (!provider.value) return;
|
||||
if (modelRows.value.length === 0) {
|
||||
message.warning('请至少保留一个模型');
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
modalApi.setState({ confirming: true });
|
||||
try {
|
||||
const models = modelRows.value.map((m) => ({
|
||||
model: m.model,
|
||||
contextWindow:
|
||||
m.contextWindow == null || m.contextWindow <= 0
|
||||
? 0
|
||||
: Math.floor(m.contextWindow),
|
||||
isDefault: m.isDefault,
|
||||
enabled: m.enabled,
|
||||
}));
|
||||
const p = await upsertAgentLlmProviderModelsApi(provider.value.id, models);
|
||||
applyProviderModels(p);
|
||||
message.success('模型配置已保存');
|
||||
modalApi.close();
|
||||
emit('success');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
modalApi.setState({ confirming: false });
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal :title="modalTitle">
|
||||
<p class="text-muted-foreground mb-3 text-sm">
|
||||
勾选或手动添加后保存。禁用后聊天不可选;禁用默认模型会自动改派。上下文窗口留空表示自动估计。
|
||||
</p>
|
||||
<div class="mb-3 flex flex-wrap gap-2">
|
||||
<Button type="primary" ghost :loading="probing" @click="probe">
|
||||
加载模型列表
|
||||
</Button>
|
||||
</div>
|
||||
<div
|
||||
v-if="probedModels.length > 0"
|
||||
class="mb-3 max-h-40 space-y-1 overflow-y-auto rounded-md border border-border p-2"
|
||||
>
|
||||
<label
|
||||
v-for="p in probedModels"
|
||||
:key="p.id"
|
||||
class="flex cursor-pointer items-center gap-2 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
:checked="isInList(p.id)"
|
||||
@update:checked="(v: boolean) => toggleProbed(p, v)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ p.id }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="mb-3 flex gap-2">
|
||||
<Input
|
||||
v-model:value="manualModelId"
|
||||
class="flex-1"
|
||||
placeholder="手动添加模型 id"
|
||||
@press-enter="addManual"
|
||||
/>
|
||||
<Button @click="addManual">添加</Button>
|
||||
</div>
|
||||
<div v-if="modelRows.length === 0" class="text-muted-foreground text-sm">
|
||||
暂无模型
|
||||
</div>
|
||||
<div v-else class="overflow-hidden rounded-md border border-border">
|
||||
<div
|
||||
class="text-muted-foreground bg-muted/40 grid grid-cols-[56px_minmax(0,1fr)_140px_64px_48px] items-center gap-2 border-b border-border px-3 py-2 text-xs"
|
||||
>
|
||||
<span>默认</span>
|
||||
<span>模型</span>
|
||||
<span>上下文窗口</span>
|
||||
<span>启用</span>
|
||||
<span class="text-right">操作</span>
|
||||
</div>
|
||||
<div class="max-h-72 overflow-y-auto">
|
||||
<div
|
||||
v-for="m in modelRows"
|
||||
:key="m.model"
|
||||
class="grid grid-cols-[56px_minmax(0,1fr)_140px_64px_48px] items-center gap-2 border-b border-border px-3 py-2 text-sm last:border-b-0"
|
||||
:class="{ 'opacity-60': !m.enabled }"
|
||||
>
|
||||
<Radio
|
||||
:checked="m.isDefault"
|
||||
:disabled="!m.enabled"
|
||||
@change="setDefault(m.model)"
|
||||
/>
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-medium" :title="m.model">{{ m.model }}</div>
|
||||
<Tag
|
||||
v-if="!m.enabled"
|
||||
color="default"
|
||||
class="mt-0.5 !text-[10px] !leading-4"
|
||||
>
|
||||
已禁用
|
||||
</Tag>
|
||||
</div>
|
||||
<InputNumber
|
||||
v-model:value="m.contextWindow"
|
||||
class="w-full"
|
||||
size="small"
|
||||
:min="1"
|
||||
:controls="false"
|
||||
placeholder="自动"
|
||||
addon-after="token"
|
||||
/>
|
||||
<div class="flex items-center justify-start">
|
||||
<Switch
|
||||
size="small"
|
||||
class="llm-model-enable-switch"
|
||||
:checked="m.enabled"
|
||||
:loading="togglingModel === m.model"
|
||||
@change="(v) => toggleEnabled(m, !!v)"
|
||||
/>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
danger
|
||||
class="!px-0"
|
||||
@click="removeModel(m.model)"
|
||||
>
|
||||
移除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 避免被表格/全局 button 样式拉满列宽 */
|
||||
.llm-model-enable-switch {
|
||||
width: 28px !important;
|
||||
min-width: 28px !important;
|
||||
flex: none;
|
||||
}
|
||||
</style>
|
||||
@@ -1,489 +1,220 @@
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, ref } from 'vue';
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { AgentVO } from '#/api/agent';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Checkbox,
|
||||
Form,
|
||||
FormItem,
|
||||
Input,
|
||||
InputPassword,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Radio,
|
||||
Spin,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
import { Button, Popconfirm, Space, Tag, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
createAgentLlmProviderApi,
|
||||
deleteAgentLlmProviderApi,
|
||||
listAgentLlmProvidersApi,
|
||||
probeAgentLlmModelsApi,
|
||||
type AgentVO,
|
||||
updateAgentLlmProviderApi,
|
||||
upsertAgentLlmProviderModelsApi,
|
||||
} from '#/api/agent';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import {
|
||||
syncVxeGridColumns,
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
|
||||
import ProviderFormModal from './components/ProviderFormModal.vue';
|
||||
import ProviderModelsModal from './components/ProviderModelsModal.vue';
|
||||
|
||||
defineOptions({ name: 'AgentLlmSettings' });
|
||||
|
||||
type EnabledModelRow = {
|
||||
model: string;
|
||||
contextWindow: string;
|
||||
isDefault: boolean;
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const loading = ref(false);
|
||||
const formModalRef = ref<InstanceType<typeof ProviderFormModal>>();
|
||||
const modelsModalRef = ref<InstanceType<typeof ProviderModelsModal>>();
|
||||
|
||||
const actionCodes = ['agent:llm-settings'];
|
||||
const showActionColumn = useActionColumnVisible(actionCodes);
|
||||
|
||||
type ProviderRow = AgentVO.LlmProvider & {
|
||||
modelCount: number;
|
||||
enabledCount: number;
|
||||
defaultModelLabel: string;
|
||||
};
|
||||
|
||||
type ProviderDraft = {
|
||||
id: number;
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
apiKeyMasked: string | null;
|
||||
displayName: string;
|
||||
enabledModels: EnabledModelRow[];
|
||||
probedModels: AgentVO.ProbedLlmModel[];
|
||||
manualModelId: string;
|
||||
probing: boolean;
|
||||
savingCreds: boolean;
|
||||
savingModels: boolean;
|
||||
};
|
||||
|
||||
const loading = ref(true);
|
||||
const providers = ref<ProviderDraft[]>([]);
|
||||
const createOpen = ref(false);
|
||||
const creating = ref(false);
|
||||
const createForm = ref({
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
displayName: '',
|
||||
});
|
||||
|
||||
function toDraft(p: AgentVO.LlmProvider): ProviderDraft {
|
||||
function toRow(p: AgentVO.LlmProvider): ProviderRow {
|
||||
const models = p.models || [];
|
||||
const enabled = models.filter((m) => m.enabled !== false);
|
||||
const def = enabled.find((m) => m.isDefault) || models.find((m) => m.isDefault);
|
||||
return {
|
||||
id: p.id,
|
||||
baseUrl: p.baseUrl || '',
|
||||
apiKey: '',
|
||||
apiKeyMasked: p.apiKeyMasked || null,
|
||||
displayName: p.displayName || '',
|
||||
enabledModels: (p.models || []).map((m) => ({
|
||||
model: m.model,
|
||||
contextWindow:
|
||||
m.contextWindow != null && m.contextWindow > 0
|
||||
? String(m.contextWindow)
|
||||
: '',
|
||||
isDefault: !!m.isDefault,
|
||||
})),
|
||||
probedModels: [],
|
||||
manualModelId: '',
|
||||
probing: false,
|
||||
savingCreds: false,
|
||||
savingModels: false,
|
||||
...p,
|
||||
modelCount: models.length,
|
||||
enabledCount: enabled.length,
|
||||
defaultModelLabel: def?.model || '-',
|
||||
};
|
||||
}
|
||||
|
||||
async function loadAll() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await listAgentLlmProvidersApi();
|
||||
providers.value = (res.items || []).map(toDraft);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载提供商失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
const baseColumns: VxeGridProps<ProviderRow>['columns'] = [
|
||||
{ type: 'seq', title: '序号', minWidth: 60 },
|
||||
{
|
||||
field: 'displayName',
|
||||
title: '名称',
|
||||
minWidth: 140,
|
||||
formatter: ({ row }) => row.displayName || '-',
|
||||
},
|
||||
{
|
||||
field: 'baseUrl',
|
||||
title: 'Base URL',
|
||||
minWidth: 220,
|
||||
showOverflow: 'tooltip',
|
||||
},
|
||||
{
|
||||
field: 'apiKeyMasked',
|
||||
title: 'API Key',
|
||||
minWidth: 120,
|
||||
formatter: ({ row }) => row.apiKeyMasked || '-',
|
||||
},
|
||||
{
|
||||
field: 'enabledCount',
|
||||
title: '模型',
|
||||
minWidth: 120,
|
||||
slots: { default: 'modelCount' },
|
||||
},
|
||||
{
|
||||
field: 'defaultModelLabel',
|
||||
title: '公司默认',
|
||||
minWidth: 160,
|
||||
showOverflow: 'tooltip',
|
||||
},
|
||||
{
|
||||
field: 'updateTime',
|
||||
title: '更新时间',
|
||||
minWidth: 160,
|
||||
},
|
||||
];
|
||||
|
||||
function isModelEnabled(d: ProviderDraft, id: string) {
|
||||
return d.enabledModels.some((m) => m.model === id);
|
||||
}
|
||||
const actionColumn: NonNullable<VxeGridProps<ProviderRow>['columns']>[number] = {
|
||||
title: '操作',
|
||||
width: 240,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
};
|
||||
|
||||
function toggleProbedModel(
|
||||
d: ProviderDraft,
|
||||
p: AgentVO.ProbedLlmModel,
|
||||
checked: boolean,
|
||||
) {
|
||||
if (checked) {
|
||||
if (isModelEnabled(d, p.id)) return;
|
||||
d.enabledModels.push({
|
||||
model: p.id,
|
||||
contextWindow:
|
||||
p.contextWindow != null && p.contextWindow > 0
|
||||
? String(p.contextWindow)
|
||||
: '',
|
||||
isDefault: false,
|
||||
});
|
||||
} else {
|
||||
d.enabledModels = d.enabledModels.filter((m) => m.model !== p.id);
|
||||
}
|
||||
}
|
||||
const tableColumns = computed(() =>
|
||||
showActionColumn.value
|
||||
? [...(baseColumns ?? []), actionColumn]
|
||||
: (baseColumns ?? []),
|
||||
);
|
||||
|
||||
function setDefaultModel(d: ProviderDraft, modelId: string) {
|
||||
for (const draft of providers.value) {
|
||||
draft.enabledModels = draft.enabledModels.map((m) => ({
|
||||
...m,
|
||||
isDefault: draft.id === d.id && m.model === modelId,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function removeEnabledModel(d: ProviderDraft, modelId: string) {
|
||||
const wasDefault = d.enabledModels.find((m) => m.model === modelId)?.isDefault;
|
||||
d.enabledModels = d.enabledModels.filter((m) => m.model !== modelId);
|
||||
if (!wasDefault) return;
|
||||
for (const draft of providers.value) {
|
||||
for (const m of draft.enabledModels) {
|
||||
m.isDefault = false;
|
||||
}
|
||||
}
|
||||
for (const draft of providers.value) {
|
||||
if (draft.enabledModels.length > 0) {
|
||||
draft.enabledModels[0]!.isDefault = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addManualModel(d: ProviderDraft) {
|
||||
const id = d.manualModelId.trim();
|
||||
if (!id) {
|
||||
message.warning('请输入模型 id');
|
||||
return;
|
||||
}
|
||||
if (isModelEnabled(d, id)) {
|
||||
message.warning('该模型已在启用列表中');
|
||||
return;
|
||||
}
|
||||
d.enabledModels.push({
|
||||
model: id,
|
||||
contextWindow: '',
|
||||
isDefault: false,
|
||||
});
|
||||
d.manualModelId = '';
|
||||
}
|
||||
|
||||
async function probeModels(d: ProviderDraft) {
|
||||
if (!d.baseUrl.trim()) {
|
||||
message.warning('请先填写 Base URL');
|
||||
return;
|
||||
}
|
||||
const useStored =
|
||||
!!d.apiKeyMasked &&
|
||||
(!d.apiKey.trim() || d.apiKey.trim().startsWith('****'));
|
||||
if (!useStored && !d.apiKey.trim()) {
|
||||
message.warning('请填写 API Key,或先保存密钥后再用已存密钥探测');
|
||||
return;
|
||||
}
|
||||
d.probing = true;
|
||||
try {
|
||||
const res = await probeAgentLlmModelsApi({
|
||||
baseUrl: d.baseUrl.trim(),
|
||||
apiKey: useStored ? undefined : d.apiKey.trim(),
|
||||
useStoredKey: useStored,
|
||||
providerId: useStored ? d.id : undefined,
|
||||
});
|
||||
d.probedModels = res.items || [];
|
||||
if (d.probedModels.length === 0) {
|
||||
message.warning('未返回模型,可手动添加模型 id');
|
||||
} else {
|
||||
message.success(`已加载 ${d.probedModels.length} 个模型`);
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载模型列表失败');
|
||||
} finally {
|
||||
d.probing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCredentials(d: ProviderDraft) {
|
||||
if (!d.baseUrl.trim()) {
|
||||
message.warning('请填写 Base URL');
|
||||
return;
|
||||
}
|
||||
d.savingCreds = true;
|
||||
try {
|
||||
const p = await updateAgentLlmProviderApi(d.id, {
|
||||
baseUrl: d.baseUrl.trim(),
|
||||
apiKey: d.apiKey.trim() || undefined,
|
||||
displayName: d.displayName.trim(),
|
||||
});
|
||||
d.apiKeyMasked = p.apiKeyMasked || null;
|
||||
d.apiKey = '';
|
||||
d.baseUrl = p.baseUrl || d.baseUrl;
|
||||
d.displayName = p.displayName || '';
|
||||
message.success('凭证已保存');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存凭证失败');
|
||||
} finally {
|
||||
d.savingCreds = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveModels(d: ProviderDraft) {
|
||||
if (d.enabledModels.length === 0) {
|
||||
message.warning('请至少启用一个模型');
|
||||
return;
|
||||
}
|
||||
d.savingModels = true;
|
||||
try {
|
||||
const models = d.enabledModels.map((m) => {
|
||||
const cw = m.contextWindow.trim();
|
||||
let contextWindow: number | null | undefined;
|
||||
if (cw === '') {
|
||||
contextWindow = 0;
|
||||
} else {
|
||||
const n = Number(cw);
|
||||
if (!Number.isFinite(n) || n < 0) {
|
||||
throw new Error(`模型 ${m.model} 的上下文窗口无效`);
|
||||
const gridOptions: VxeGridProps<ProviderRow> = {
|
||||
columns: tableColumns.value,
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
size: 'small',
|
||||
pagerConfig: { enabled: false },
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await listAgentLlmProvidersApi();
|
||||
const items = (res.items || []).map(toRow);
|
||||
return { items, total: items.length };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
contextWindow = Math.floor(n);
|
||||
}
|
||||
return {
|
||||
model: m.model,
|
||||
contextWindow,
|
||||
isDefault: m.isDefault,
|
||||
};
|
||||
});
|
||||
const p = await upsertAgentLlmProviderModelsApi(d.id, models);
|
||||
// 刷新全部,保证公司级默认只剩一条
|
||||
await loadAll();
|
||||
message.success(`「${p.displayName || p.baseUrl}」模型列表已保存`);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存模型失败');
|
||||
} finally {
|
||||
d.savingModels = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });
|
||||
syncVxeGridColumns(gridApi, tableColumns);
|
||||
|
||||
function openCreate() {
|
||||
formModalRef.value?.open();
|
||||
}
|
||||
|
||||
async function removeProvider(id: number) {
|
||||
function openEdit(row: ProviderRow) {
|
||||
formModalRef.value?.open(row);
|
||||
}
|
||||
|
||||
function openModels(row: ProviderRow) {
|
||||
modelsModalRef.value?.open(row);
|
||||
}
|
||||
|
||||
async function handleDelete(row: ProviderRow) {
|
||||
try {
|
||||
await deleteAgentLlmProviderApi(id);
|
||||
providers.value = providers.value.filter((p) => p.id !== id);
|
||||
message.success('已删除提供商');
|
||||
await deleteAgentLlmProviderApi(row.id);
|
||||
message.success('已删除');
|
||||
gridApi.reload();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
if (!createForm.value.baseUrl.trim()) {
|
||||
message.warning('请填写 Base URL');
|
||||
return;
|
||||
}
|
||||
if (!createForm.value.apiKey.trim()) {
|
||||
message.warning('请填写 API Key');
|
||||
return;
|
||||
}
|
||||
creating.value = true;
|
||||
try {
|
||||
const p = await createAgentLlmProviderApi({
|
||||
baseUrl: createForm.value.baseUrl.trim(),
|
||||
apiKey: createForm.value.apiKey.trim(),
|
||||
displayName: createForm.value.displayName.trim() || undefined,
|
||||
});
|
||||
providers.value.push(toDraft(p));
|
||||
createOpen.value = false;
|
||||
createForm.value = { baseUrl: '', apiKey: '', displayName: '' };
|
||||
message.success('提供商已创建,请继续勾选启用模型');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '创建失败');
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
function onSaved() {
|
||||
gridApi.reload();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadAll();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height>
|
||||
<div class="relative mx-auto max-w-3xl space-y-4 pb-8">
|
||||
<div
|
||||
v-if="loading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
||||
>
|
||||
<Spin />
|
||||
</div>
|
||||
<p class="text-muted-foreground mb-3 text-sm">
|
||||
可配置多个 OpenAI Compatible 提供商;跨提供商允许同名模型。公司全局仅一个默认模型。
|
||||
</p>
|
||||
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-base font-medium">模型提供商</div>
|
||||
<p class="text-muted-foreground mt-1 text-sm">
|
||||
可配置多个 OpenAI Compatible 提供商;跨提供商允许同名模型。公司全局仅一个默认模型。
|
||||
</p>
|
||||
</div>
|
||||
<Button type="primary" @click="createOpen = true">添加提供商</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!loading && providers.length === 0"
|
||||
class="text-muted-foreground rounded-lg border border-dashed border-border px-4 py-10 text-center text-sm"
|
||||
>
|
||||
尚未配置提供商,点击右上角添加。
|
||||
</div>
|
||||
|
||||
<Card
|
||||
v-for="d in providers"
|
||||
:key="d.id"
|
||||
:title="d.displayName || d.baseUrl || `提供商 #${d.id}`"
|
||||
:bordered="false"
|
||||
>
|
||||
<template #extra>
|
||||
<Popconfirm
|
||||
title="删除该提供商及其启用模型?"
|
||||
ok-text="删除"
|
||||
cancel-text="取消"
|
||||
@confirm="removeProvider(d.id)"
|
||||
>
|
||||
<Button type="link" danger size="small">删除</Button>
|
||||
</Popconfirm>
|
||||
</template>
|
||||
|
||||
<Form layout="vertical">
|
||||
<FormItem label="Base URL" required>
|
||||
<Input
|
||||
v-model:value="d.baseUrl"
|
||||
placeholder="https://api.deepseek.com/v1"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem
|
||||
:label="
|
||||
d.apiKeyMasked
|
||||
? `API Key(已配置 ${d.apiKeyMasked},留空不改)`
|
||||
: 'API Key'
|
||||
"
|
||||
>
|
||||
<InputPassword v-model:value="d.apiKey" placeholder="sk-..." />
|
||||
</FormItem>
|
||||
<FormItem label="提供商备注(可选)">
|
||||
<Input v-model:value="d.displayName" placeholder="如 DeepSeek" />
|
||||
</FormItem>
|
||||
<Button
|
||||
type="default"
|
||||
class="mb-4"
|
||||
:loading="d.savingCreds"
|
||||
@click="saveCredentials(d)"
|
||||
>
|
||||
保存凭证
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<PermissionGate code="agent:llm-settings">
|
||||
<Button type="primary" @click="openCreate">
|
||||
<PlusIcon class="size-4" />
|
||||
添加提供商
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</template>
|
||||
|
||||
<FormItem label="模型列表">
|
||||
<div class="mb-2 flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="primary"
|
||||
ghost
|
||||
:loading="d.probing"
|
||||
@click="probeModels(d)"
|
||||
>
|
||||
加载模型列表
|
||||
</Button>
|
||||
</div>
|
||||
<div
|
||||
v-if="d.probedModels.length > 0"
|
||||
class="mb-3 max-h-40 space-y-1 overflow-y-auto rounded-md border border-border p-2"
|
||||
>
|
||||
<label
|
||||
v-for="p in d.probedModels"
|
||||
:key="p.id"
|
||||
class="flex cursor-pointer items-center gap-2 text-sm"
|
||||
>
|
||||
<Checkbox
|
||||
:checked="isModelEnabled(d, p.id)"
|
||||
@update:checked="(v: boolean) => toggleProbedModel(d, p, v)"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ p.id }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="mb-2 flex gap-2">
|
||||
<Input
|
||||
v-model:value="d.manualModelId"
|
||||
class="flex-1"
|
||||
placeholder="手动添加模型 id"
|
||||
@press-enter="addManualModel(d)"
|
||||
/>
|
||||
<Button @click="addManualModel(d)">添加</Button>
|
||||
</div>
|
||||
<div
|
||||
v-if="d.enabledModels.length === 0"
|
||||
class="text-muted-foreground text-xs"
|
||||
>
|
||||
尚未启用模型。勾选或手动添加后保存。
|
||||
</div>
|
||||
<div v-else class="space-y-2">
|
||||
<div
|
||||
v-for="m in d.enabledModels"
|
||||
:key="m.model"
|
||||
class="rounded-md border border-border px-2 py-2 text-sm"
|
||||
>
|
||||
<div class="mb-1 flex items-center gap-2">
|
||||
<Radio
|
||||
:checked="m.isDefault"
|
||||
@change="setDefaultModel(d, m.model)"
|
||||
>
|
||||
公司默认
|
||||
</Radio>
|
||||
<span class="min-w-0 flex-1 truncate font-medium">{{
|
||||
m.model
|
||||
}}</span>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
danger
|
||||
@click="removeEnabledModel(d, m.model)"
|
||||
>
|
||||
移除
|
||||
</Button>
|
||||
</div>
|
||||
<Input
|
||||
v-model:value="m.contextWindow"
|
||||
size="small"
|
||||
placeholder="上下文窗口 token,留空=自动估计"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</FormItem>
|
||||
<Button
|
||||
type="primary"
|
||||
:loading="d.savingModels"
|
||||
@click="saveModels(d)"
|
||||
<template #modelCount="{ row }">
|
||||
<span v-if="row.modelCount > 0">
|
||||
<Tag color="blue">{{ row.enabledCount }} 启用</Tag>
|
||||
<span
|
||||
v-if="row.enabledCount < row.modelCount"
|
||||
class="text-muted-foreground ml-1 text-xs"
|
||||
>
|
||||
保存启用模型
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
/ {{ row.modelCount }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-else class="text-muted-foreground">0</span>
|
||||
</template>
|
||||
|
||||
<Modal
|
||||
v-model:open="createOpen"
|
||||
title="添加提供商"
|
||||
:confirm-loading="creating"
|
||||
ok-text="创建"
|
||||
destroy-on-close
|
||||
@ok="submitCreate"
|
||||
>
|
||||
<Form layout="vertical" class="mt-2">
|
||||
<FormItem label="Base URL" required>
|
||||
<Input
|
||||
v-model:value="createForm.baseUrl"
|
||||
placeholder="https://api.deepseek.com/v1"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="API Key" required>
|
||||
<InputPassword
|
||||
v-model:value="createForm.apiKey"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="备注(可选)">
|
||||
<Input
|
||||
v-model:value="createForm.displayName"
|
||||
placeholder="如 DeepSeek"
|
||||
/>
|
||||
</FormItem>
|
||||
</Form>
|
||||
</Modal>
|
||||
<template v-if="showActionColumn" #action="{ row }">
|
||||
<Space>
|
||||
<PermissionGate code="agent:llm-settings">
|
||||
<Button type="link" size="small" @click="openModels(row)">
|
||||
模型
|
||||
</Button>
|
||||
<Button type="link" size="small" @click="openEdit(row)">
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="删除该提供商及其启用模型?"
|
||||
ok-text="删除"
|
||||
cancel-text="取消"
|
||||
@confirm="handleDelete(row)"
|
||||
>
|
||||
<Button type="link" danger size="small">删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<ProviderFormModal ref="formModalRef" @success="onSaved" />
|
||||
<ProviderModelsModal ref="modelsModalRef" @success="onSaved" />
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
Reference in New Issue
Block a user