mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 00:29:19 +08:00
feat: 公司 LLM 改为提供商凭证加多模型勾选并支持探测目录
This commit is contained in:
+9
-12
@@ -141,8 +141,8 @@ apps/agent/
|
|||||||
|
|
||||||
上下文窗口来源(多数 OpenAI Compatible **不会**在 API 返回 context 大小):
|
上下文窗口来源(多数 OpenAI Compatible **不会**在 API 返回 context 大小):
|
||||||
|
|
||||||
1. 租户配置 `context_window`(设置页可填)
|
1. 启用模型上的 `context_window`(设置页可填;probe 若带回扩展字段可预填)
|
||||||
2. 否则按 `model` 名启发式(deepseek/gpt-4o/claude 等)
|
2. 否则按默认模型的 `model` 名启发式
|
||||||
3. 再否则默认 `128000`
|
3. 再否则默认 `128000`
|
||||||
|
|
||||||
预算:system + 本轮 user + 预留输出/tool 后,剩余给历史原文。
|
预算:system + 本轮 user + 预留输出/tool 后,剩余给历史原文。
|
||||||
@@ -174,17 +174,14 @@ apps/agent/
|
|||||||
|
|
||||||
### 4.2.1 公司模型配置(MySQL,不在 Mongo)
|
### 4.2.1 公司模型配置(MySQL,不在 Mongo)
|
||||||
|
|
||||||
见 `apps/server/sql/design/agent/agent_company_llm_settings_design.sql` 与迁移 `V20260919c__agent_company_llm_settings.sql`。
|
见 `apps/server/sql/design/agent/agent_company_llm_provider_models_design.sql` 与迁移 `V20260920b__agent_llm_provider_models.sql`(旧单表迁入后改名为 `_deprecated`)。
|
||||||
|
|
||||||
| 字段 | 说明 |
|
| 表 | 说明 |
|
||||||
|------|------|
|
|----|------|
|
||||||
| `company_id` | 唯一 |
|
| `agent_company_llm_provider` | 公司一套 `base_url` + 加密 Key(UNIQUE company) |
|
||||||
| `base_url` / `model` | OpenAI Compatible |
|
| `agent_company_llm_model` | 已启用模型多行;`is_default=1` 供 Agent 注入 |
|
||||||
| `context_window` | 可选;模型上下文 token 上限,空则 Agent 按模型名估计 |
|
|
||||||
| `api_key_encrypted` / `api_key_suffix` | 密文 + 掩码后缀 |
|
|
||||||
| `extra_headers_json` | 可选 |
|
|
||||||
|
|
||||||
浏览器:`/api/company/agent-llm-settings`;Agent 内部:`/api/internal/agent/llm-runtime`。
|
浏览器:`GET/PUT /api/company/agent-llm-settings`;`POST .../probe-models` 代理 `{baseUrl}/v1/models`(不落库)。Agent 内部:`/api/internal/agent/llm-runtime` 返回**默认模型**明文(含 `contextWindow`)。
|
||||||
|
|
||||||
### 4.3 与 LangGraph 的关系
|
### 4.3 与 LangGraph 的关系
|
||||||
|
|
||||||
@@ -224,7 +221,7 @@ apps/agent/
|
|||||||
|
|
||||||
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
|
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
|
||||||
|
|
||||||
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(不经 Agent)。
|
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型列表);`POST .../probe-models` 拉提供商模型目录(不经 Agent)。
|
||||||
|
|
||||||
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
|
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ uvicorn api.main:app --reload --host 0.0.0.0 --port 8200
|
|||||||
健康检查:`GET http://localhost:8200/health`
|
健康检查:`GET http://localhost:8200/health`
|
||||||
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/agent` 对齐)
|
||||||
|
|
||||||
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(MySQL 加密落库);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉明文注入。
|
**模型 API 配置不在本服务**:浏览器走 Java `GET/PUT /api/company/agent-llm-settings`(凭证 + 多模型勾选;`POST .../probe-models` 拉目录);Agent 经 Redis `agent:llm:rt:{companyId}` 或内部接口拉**默认模型**明文注入。
|
||||||
|
|
||||||
## 环境变量要点
|
## 环境变量要点
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
-- ========================================
|
||||||
|
-- Agent:公司 LLM 提供商凭证 + 已启用模型
|
||||||
|
-- 迁移:V20260920b__agent_llm_provider_models.sql
|
||||||
|
-- 旧表 agent_company_llm_settings → agent_company_llm_settings_deprecated
|
||||||
|
-- ========================================
|
||||||
|
-- 约定:
|
||||||
|
-- 1) 公司一套 base_url + api_key(provider 表 UNIQUE company_id)
|
||||||
|
-- 2) 多个已启用模型;同公司一条 is_default=1 供 Agent 注入
|
||||||
|
-- 3) Agent Redis agent:llm:rt:{companyId} 缓存默认模型明文
|
||||||
|
-- ========================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`base_url` varchar(500) NOT NULL COMMENT 'OpenAI Compatible Base URL',
|
||||||
|
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||||
|
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||||
|
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
||||||
|
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||||
|
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_agent_llm_provider_company` (`company_id`),
|
||||||
|
CONSTRAINT `fk_agent_llm_provider_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent LLM 提供商凭证';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_model` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`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 '是否默认聊天模型',
|
||||||
|
`create_by` bigint UNSIGNED NULL,
|
||||||
|
`update_by` bigint UNSIGNED NULL,
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_agent_llm_model_company_model` (`company_id`, `model`),
|
||||||
|
KEY `idx_agent_llm_model_company_default` (`company_id`, `is_default`),
|
||||||
|
CONSTRAINT `fk_agent_llm_model_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司已启用的 LLM 模型';
|
||||||
@@ -1,28 +1,5 @@
|
|||||||
-- ========================================
|
-- ========================================
|
||||||
-- Agent:公司模型 API 配置(OpenAI Compatible)
|
-- Agent:公司模型 API 配置(已拆分为 provider + model)
|
||||||
-- 表 agent_company_llm_settings
|
-- 见 agent_company_llm_provider_models_design.sql
|
||||||
-- 迁移:V20260919c__agent_company_llm_settings.sql
|
-- 迁移:V20260919c(旧单表)→ V20260920(context_window)→ V20260920b(拆表并 deprecated)
|
||||||
-- ========================================
|
-- ========================================
|
||||||
-- 约定:
|
|
||||||
-- 1) 按 company_id 一行;api_key 加密存储,接口只回掩码
|
|
||||||
-- 2) Agent 进程经内部接口取运行时明文,Redis 缓存 agent:llm:rt:{companyId}
|
|
||||||
-- 3) 与聊天会话 Mongo 分离:凭证归业务库(MySQL),对话归 Agent Mongo
|
|
||||||
-- ========================================
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `agent_company_llm_settings` (
|
|
||||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
|
||||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
|
||||||
`base_url` varchar(500) NOT NULL COMMENT 'OpenAI Compatible Base URL',
|
|
||||||
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
|
||||||
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
|
||||||
`model` varchar(200) NOT NULL COMMENT '默认模型名',
|
|
||||||
`context_window` int UNSIGNED NULL COMMENT '模型上下文窗口(token);空则 Agent 按模型名估计',
|
|
||||||
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
|
||||||
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
|
||||||
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
|
||||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
|
||||||
PRIMARY KEY (`id`),
|
|
||||||
UNIQUE KEY `uk_agent_llm_company` (`company_id`),
|
|
||||||
CONSTRAINT `fk_agent_llm_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent 模型 API 配置';
|
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
-- 公司 LLM:凭证(一套 base_url/key)+ 多模型勾选;从旧单表迁移
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`base_url` varchar(500) NOT NULL COMMENT 'OpenAI Compatible Base URL',
|
||||||
|
`api_key_encrypted` varchar(2000) NOT NULL COMMENT 'API Key 密文',
|
||||||
|
`api_key_suffix` varchar(16) NOT NULL DEFAULT '' COMMENT 'Key 末几位(展示掩码)',
|
||||||
|
`display_name` varchar(100) NULL COMMENT '展示名,如 DeepSeek',
|
||||||
|
`extra_headers_json` json NULL COMMENT '可选额外请求头',
|
||||||
|
`create_by` bigint UNSIGNED NULL COMMENT '创建人用户ID',
|
||||||
|
`update_by` bigint UNSIGNED NULL COMMENT '更新人用户ID',
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_agent_llm_provider_company` (`company_id`),
|
||||||
|
CONSTRAINT `fk_agent_llm_provider_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent LLM 提供商凭证';
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_model` (
|
||||||
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`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 '是否默认聊天模型',
|
||||||
|
`create_by` bigint UNSIGNED NULL,
|
||||||
|
`update_by` bigint UNSIGNED NULL,
|
||||||
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_agent_llm_model_company_model` (`company_id`, `model`),
|
||||||
|
KEY `idx_agent_llm_model_company_default` (`company_id`, `is_default`),
|
||||||
|
CONSTRAINT `fk_agent_llm_model_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司已启用的 LLM 模型';
|
||||||
|
|
||||||
|
INSERT INTO `agent_company_llm_provider` (
|
||||||
|
`company_id`, `base_url`, `api_key_encrypted`, `api_key_suffix`,
|
||||||
|
`extra_headers_json`, `create_by`, `update_by`, `create_time`, `update_time`
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
`company_id`, `base_url`, `api_key_encrypted`, `api_key_suffix`,
|
||||||
|
`extra_headers_json`, `create_by`, `update_by`, `create_time`, `update_time`
|
||||||
|
FROM `agent_company_llm_settings` s
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM `agent_company_llm_provider` p WHERE p.company_id = s.company_id
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 依赖 V20260920 已添加 context_window;若环境无该列请先执行 V20260920
|
||||||
|
INSERT INTO `agent_company_llm_model` (
|
||||||
|
`company_id`, `model`, `context_window`, `is_default`,
|
||||||
|
`create_by`, `update_by`, `create_time`, `update_time`
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
`company_id`, `model`, `context_window`, 1,
|
||||||
|
`create_by`, `update_by`, `create_time`, `update_time`
|
||||||
|
FROM `agent_company_llm_settings` s
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM `agent_company_llm_model` m
|
||||||
|
WHERE m.company_id = s.company_id AND m.model = s.model
|
||||||
|
);
|
||||||
|
|
||||||
|
RENAME TABLE `agent_company_llm_settings` TO `agent_company_llm_settings_deprecated`;
|
||||||
+11
-1
@@ -3,18 +3,21 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
|||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
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.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
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.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.model.vo.AgentLlmSettingsVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公司模型 API 配置(浏览器 JWT)。
|
* 公司模型 API 配置(浏览器 JWT):凭证 + 多模型勾选。
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/company/agent-llm-settings")
|
@RequestMapping("/api/company/agent-llm-settings")
|
||||||
@@ -34,4 +37,11 @@ public class AgentCompanyLlmSettingsController {
|
|||||||
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
||||||
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(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;
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 更新公司模型 API 配置。
|
* 更新公司 LLM:凭证 + 启用模型列表(全量覆盖模型)。
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class UpsertAgentLlmSettingsDTO {
|
public class UpsertAgentLlmSettingsDTO {
|
||||||
@@ -12,15 +16,12 @@ public class UpsertAgentLlmSettingsDTO {
|
|||||||
@NotBlank(message = "baseUrl 不能为空")
|
@NotBlank(message = "baseUrl 不能为空")
|
||||||
private String baseUrl;
|
private String baseUrl;
|
||||||
|
|
||||||
@NotBlank(message = "model 不能为空")
|
|
||||||
private String model;
|
|
||||||
|
|
||||||
/** 首次必填;后续留空表示不改 Key */
|
/** 首次必填;后续留空表示不改 Key */
|
||||||
private String apiKey;
|
private String apiKey;
|
||||||
|
|
||||||
/**
|
private String displayName;
|
||||||
* 模型上下文窗口(token)。空/不传表示不改(更新时)或由 Agent 估计(新建)。
|
|
||||||
* 传正整数则写入;部分前端可用 0 表示清空为「自动估计」。
|
@NotEmpty(message = "至少启用一个模型")
|
||||||
*/
|
@Valid
|
||||||
private Integer contextWindow;
|
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 lombok.Data;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对公司管理员可见的模型配置(Key 仅掩码)。
|
* 对公司管理员可见的模型配置(Key 仅掩码)。
|
||||||
*/
|
*/
|
||||||
@@ -9,9 +12,8 @@ import lombok.Data;
|
|||||||
public class AgentLlmSettingsVO {
|
public class AgentLlmSettingsVO {
|
||||||
private boolean configured;
|
private boolean configured;
|
||||||
private String baseUrl;
|
private String baseUrl;
|
||||||
private String model;
|
private String displayName;
|
||||||
/** 上下文窗口 token;null 表示未配置、由 Agent 估计 */
|
|
||||||
private Integer contextWindow;
|
|
||||||
private String apiKeyMasked;
|
private String apiKeyMasked;
|
||||||
private String updateTime;
|
private String updateTime;
|
||||||
|
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-2
@@ -1,11 +1,13 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
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.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.AgentLlmRuntimeVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公司模型 API 配置。
|
* 公司模型 API:凭证 + 多模型勾选。
|
||||||
*/
|
*/
|
||||||
public interface AgentCompanyLlmSettingsService {
|
public interface AgentCompanyLlmSettingsService {
|
||||||
|
|
||||||
@@ -13,6 +15,8 @@ public interface AgentCompanyLlmSettingsService {
|
|||||||
|
|
||||||
AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto);
|
AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto);
|
||||||
|
|
||||||
/** Agent 内部:按公司取运行时明文配置 */
|
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
|
||||||
|
|
||||||
|
/** Agent 内部:按公司取默认模型运行时明文 */
|
||||||
AgentLlmRuntimeVO getRuntime(Long companyId);
|
AgentLlmRuntimeVO getRuntime(Long companyId);
|
||||||
}
|
}
|
||||||
|
|||||||
+179
-45
@@ -11,23 +11,35 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
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.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.AgentLlmRuntimeVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
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.service.AgentCompanyLlmSettingsService;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
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.modules.org.company.member.service.CompanyMemberService;
|
||||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.format.DateTimeFormatter;
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公司模型 API:MySQL 存密文,Redis 缓存运行时明文供 Agent 注入。
|
* 公司模型 API:MySQL 存密文与启用模型;Redis 缓存默认模型明文供 Agent。
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -36,19 +48,22 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
|
|
||||||
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
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 AgentLlmCrypto crypto;
|
||||||
private final AgentLlmProperties llmProperties;
|
private final AgentLlmProperties llmProperties;
|
||||||
private final CurrentUserContext currentUserContext;
|
private final CurrentUserContext currentUserContext;
|
||||||
private final CompanyMemberService companyMemberService;
|
private final CompanyMemberService companyMemberService;
|
||||||
private final StringRedisTemplate stringRedisTemplate;
|
private final StringRedisTemplate stringRedisTemplate;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
private final OpenAiCompatibleModelsProbe modelsProbe;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public AgentLlmSettingsVO getForCurrentCompany() {
|
public AgentLlmSettingsVO getForCurrentCompany() {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||||
return toPublicVo(po);
|
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
||||||
|
return toPublicVo(provider, models);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -56,15 +71,12 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
Long userId = currentUserContext.getCurrentUserId();
|
Long userId = currentUserContext.getCurrentUserId();
|
||||||
if (!currentUserContext.isCurrentUserSuper()
|
requireOwner(companyId, userId);
|
||||||
&& !companyMemberService.isOwner(userId, companyId)) {
|
|
||||||
throw new BusinessException("仅公司拥有者可配置模型 API");
|
|
||||||
}
|
|
||||||
|
|
||||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||||
String model = dto.getModel().trim();
|
List<AgentLlmModelItemDTO> modelItems = normalizeModelItems(dto.getModels());
|
||||||
AgentCompanyLlmSettingsPO existing = findByCompany(companyId);
|
|
||||||
|
|
||||||
|
AgentCompanyLlmProviderPO existing = findProvider(companyId);
|
||||||
String encrypted;
|
String encrypted;
|
||||||
String suffix;
|
String suffix;
|
||||||
String apiKey = dto.getApiKey();
|
String apiKey = dto.getApiKey();
|
||||||
@@ -80,37 +92,79 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (existing == null) {
|
if (existing == null) {
|
||||||
AgentCompanyLlmSettingsPO po = new AgentCompanyLlmSettingsPO();
|
AgentCompanyLlmProviderPO po = new AgentCompanyLlmProviderPO();
|
||||||
po.setCompanyId(companyId);
|
po.setCompanyId(companyId);
|
||||||
po.setBaseUrl(baseUrl);
|
po.setBaseUrl(baseUrl);
|
||||||
po.setApiKeyEncrypted(encrypted);
|
po.setApiKeyEncrypted(encrypted);
|
||||||
po.setApiKeySuffix(suffix);
|
po.setApiKeySuffix(suffix);
|
||||||
po.setModel(model);
|
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
po.setContextWindow(normalizeContextWindow(dto.getContextWindow()));
|
|
||||||
po.setCreateBy(userId);
|
po.setCreateBy(userId);
|
||||||
po.setUpdateBy(userId);
|
po.setUpdateBy(userId);
|
||||||
mapper.insert(po);
|
providerMapper.insert(po);
|
||||||
existing = po;
|
existing = po;
|
||||||
} else {
|
} else {
|
||||||
existing.setBaseUrl(baseUrl);
|
existing.setBaseUrl(baseUrl);
|
||||||
existing.setApiKeyEncrypted(encrypted);
|
existing.setApiKeyEncrypted(encrypted);
|
||||||
existing.setApiKeySuffix(suffix);
|
existing.setApiKeySuffix(suffix);
|
||||||
existing.setModel(model);
|
if (dto.getDisplayName() != null) {
|
||||||
if (dto.getContextWindow() != null) {
|
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
existing.setContextWindow(normalizeContextWindow(dto.getContextWindow()));
|
|
||||||
}
|
}
|
||||||
existing.setUpdateBy(userId);
|
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);
|
evictRuntimeCache(companyId);
|
||||||
// 预热缓存,降低 Agent 首包延迟
|
|
||||||
try {
|
try {
|
||||||
cacheRuntime(companyId, buildRuntime(existing));
|
cacheRuntime(companyId, buildRuntime(existing, savedModels));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, 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
|
@Override
|
||||||
@@ -122,26 +176,80 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
if (cached != null) {
|
if (cached != null) {
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
AgentCompanyLlmSettingsPO po = findByCompany(companyId);
|
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||||
if (po == null) {
|
if (provider == null) {
|
||||||
throw new BusinessException("公司尚未配置模型 API");
|
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);
|
cacheRuntime(companyId, runtime);
|
||||||
return 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();
|
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||||
vo.setBaseUrl(po.getBaseUrl());
|
vo.setBaseUrl(provider.getBaseUrl());
|
||||||
vo.setApiKey(crypto.decrypt(po.getApiKeyEncrypted()));
|
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||||
vo.setModel(po.getModel());
|
vo.setModel(def.getModel());
|
||||||
vo.setContextWindow(po.getContextWindow());
|
vo.setContextWindow(def.getContextWindow());
|
||||||
vo.setExtraHeaders(parseHeaders(po.getExtraHeadersJson()));
|
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 0 或负数视为清空(自动估计);正整数写入。 */
|
|
||||||
private static Integer normalizeContextWindow(Integer raw) {
|
private static Integer normalizeContextWindow(Integer raw) {
|
||||||
if (raw == null || raw <= 0) {
|
if (raw == null || raw <= 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -149,6 +257,14 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
return raw;
|
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) {
|
private Map<String, String> parseHeaders(String json) {
|
||||||
if (!StringUtils.hasText(json)) {
|
if (!StringUtils.hasText(json)) {
|
||||||
return Map.of();
|
return Map.of();
|
||||||
@@ -161,26 +277,43 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private AgentCompanyLlmSettingsPO findByCompany(Long companyId) {
|
private AgentCompanyLlmProviderPO findProvider(Long companyId) {
|
||||||
return mapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmSettingsPO>()
|
return providerMapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmProviderPO>()
|
||||||
.eq(AgentCompanyLlmSettingsPO::getCompanyId, companyId)
|
.eq(AgentCompanyLlmProviderPO::getCompanyId, companyId)
|
||||||
.last("LIMIT 1"));
|
.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();
|
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
|
||||||
if (po == null) {
|
if (provider == null) {
|
||||||
vo.setConfigured(false);
|
vo.setConfigured(false);
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
vo.setConfigured(true);
|
vo.setConfigured(true);
|
||||||
vo.setBaseUrl(po.getBaseUrl());
|
vo.setBaseUrl(provider.getBaseUrl());
|
||||||
vo.setModel(po.getModel());
|
vo.setDisplayName(provider.getDisplayName());
|
||||||
vo.setContextWindow(po.getContextWindow());
|
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||||
vo.setApiKeyMasked("****" + (po.getApiKeySuffix() == null ? "" : po.getApiKeySuffix()));
|
if (provider.getUpdateTime() != null) {
|
||||||
if (po.getUpdateTime() != null) {
|
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||||
vo.setUpdateTime(po.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;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +328,8 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
payload.put("api_key", runtime.getApiKey());
|
payload.put("api_key", runtime.getApiKey());
|
||||||
payload.put("model", runtime.getModel());
|
payload.put("model", runtime.getModel());
|
||||||
payload.put("context_window", runtime.getContextWindow());
|
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(
|
stringRedisTemplate.opsForValue().set(
|
||||||
redisKey(companyId),
|
redisKey(companyId),
|
||||||
objectMapper.writeValueAsString(payload),
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,23 +22,34 @@ export namespace AgentVO {
|
|||||||
createdAt?: string;
|
createdAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LlmModelItem {
|
||||||
|
model: string;
|
||||||
|
label?: string | null;
|
||||||
|
contextWindow?: number | null;
|
||||||
|
isDefault?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface LlmSettings {
|
export interface LlmSettings {
|
||||||
configured: boolean;
|
configured: boolean;
|
||||||
baseUrl?: string | null;
|
baseUrl?: string | null;
|
||||||
model?: string | null;
|
displayName?: string | null;
|
||||||
/** 上下文窗口 token;未配置则由 Agent 按模型名估计 */
|
|
||||||
contextWindow?: number | null;
|
|
||||||
apiKeyMasked?: string | null;
|
apiKeyMasked?: string | null;
|
||||||
/** Server 字段;兼容旧 updatedAt */
|
models?: LlmModelItem[];
|
||||||
updateTime?: string;
|
updateTime?: string;
|
||||||
updatedAt?: string;
|
updatedAt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProbedLlmModel {
|
||||||
|
id: string;
|
||||||
|
contextWindow?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Memory {
|
export interface Memory {
|
||||||
id: string;
|
id: string;
|
||||||
kind: string;
|
kind: string;
|
||||||
key?: string | null;
|
key?: string | null;
|
||||||
text: string;
|
text: string;
|
||||||
|
summary?: string;
|
||||||
updatedAt?: string;
|
updatedAt?: string;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,10 +83,14 @@ export async function getAgentLlmSettingsApi() {
|
|||||||
|
|
||||||
export async function updateAgentLlmSettingsApi(body: {
|
export async function updateAgentLlmSettingsApi(body: {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
model: string;
|
|
||||||
apiKey?: string;
|
apiKey?: string;
|
||||||
/** 正整数写入;0 表示清空为自动估计 */
|
displayName?: string;
|
||||||
contextWindow?: number | null;
|
models: Array<{
|
||||||
|
model: string;
|
||||||
|
label?: string;
|
||||||
|
contextWindow?: number | null;
|
||||||
|
isDefault?: boolean;
|
||||||
|
}>;
|
||||||
}) {
|
}) {
|
||||||
return requestClient.put<AgentVO.LlmSettings>(
|
return requestClient.put<AgentVO.LlmSettings>(
|
||||||
'/company/agent-llm-settings',
|
'/company/agent-llm-settings',
|
||||||
@@ -83,6 +98,18 @@ export async function updateAgentLlmSettingsApi(body: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 服务端代理 GET /v1/models,不落库 */
|
||||||
|
export async function probeAgentLlmModelsApi(body: {
|
||||||
|
baseUrl: string;
|
||||||
|
apiKey?: string;
|
||||||
|
useStoredKey?: boolean;
|
||||||
|
}) {
|
||||||
|
return requestClient.post<{ items: AgentVO.ProbedLlmModel[] }>(
|
||||||
|
'/company/agent-llm-settings/probe-models',
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** SSE 流式发消息 */
|
/** SSE 流式发消息 */
|
||||||
export function streamAgentChat(options: {
|
export function streamAgentChat(options: {
|
||||||
threadId: string;
|
threadId: string;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export {
|
|||||||
listAgentMemoriesApi,
|
listAgentMemoriesApi,
|
||||||
listAgentMessagesApi,
|
listAgentMessagesApi,
|
||||||
listAgentSessionsApi,
|
listAgentSessionsApi,
|
||||||
|
probeAgentLlmModelsApi,
|
||||||
streamAgentChat,
|
streamAgentChat,
|
||||||
updateAgentLlmSettingsApi,
|
updateAgentLlmSettingsApi,
|
||||||
} from './apis';
|
} from './apis';
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import { PlusOutlined, SettingOutlined } from '@ant-design/icons-vue';
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
|
Checkbox,
|
||||||
Empty,
|
Empty,
|
||||||
Form,
|
Form,
|
||||||
FormItem,
|
FormItem,
|
||||||
Input,
|
Input,
|
||||||
InputPassword,
|
InputPassword,
|
||||||
Modal,
|
Modal,
|
||||||
|
Radio,
|
||||||
Spin,
|
Spin,
|
||||||
message,
|
message,
|
||||||
} from 'ant-design-vue';
|
} from 'ant-design-vue';
|
||||||
@@ -26,6 +28,7 @@ import {
|
|||||||
listAgentMemoriesApi,
|
listAgentMemoriesApi,
|
||||||
listAgentMessagesApi,
|
listAgentMessagesApi,
|
||||||
listAgentSessionsApi,
|
listAgentSessionsApi,
|
||||||
|
probeAgentLlmModelsApi,
|
||||||
streamAgentChat,
|
streamAgentChat,
|
||||||
type AgentVO,
|
type AgentVO,
|
||||||
updateAgentLlmSettingsApi,
|
updateAgentLlmSettingsApi,
|
||||||
@@ -75,16 +78,24 @@ const draft = ref('');
|
|||||||
const citations = ref<CatalogCite[]>([]);
|
const citations = ref<CatalogCite[]>([]);
|
||||||
const settingsOpen = ref(false);
|
const settingsOpen = ref(false);
|
||||||
const savingSettings = ref(false);
|
const savingSettings = ref(false);
|
||||||
|
const probingModels = ref(false);
|
||||||
const memories = ref<AgentVO.Memory[]>([]);
|
const memories = ref<AgentVO.Memory[]>([]);
|
||||||
|
/** 探测到的候选模型(勾选后进 enabledModels) */
|
||||||
|
const probedModels = ref<AgentVO.ProbedLlmModel[]>([]);
|
||||||
|
const manualModelId = ref('');
|
||||||
|
type EnabledModelRow = {
|
||||||
|
model: string;
|
||||||
|
contextWindow: string;
|
||||||
|
isDefault: boolean;
|
||||||
|
};
|
||||||
const llmForm = ref({
|
const llmForm = ref({
|
||||||
baseUrl: '',
|
baseUrl: '',
|
||||||
model: '',
|
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
apiKeyMasked: '' as string | null,
|
apiKeyMasked: '' as string | null,
|
||||||
configured: false,
|
configured: false,
|
||||||
/** 空字符串=自动估计;数字字符串=显式窗口 */
|
displayName: '',
|
||||||
contextWindow: '' as string,
|
|
||||||
});
|
});
|
||||||
|
const enabledModels = ref<EnabledModelRow[]>([]);
|
||||||
const messagePaneRef = ref<HTMLElement | null>(null);
|
const messagePaneRef = ref<HTMLElement | null>(null);
|
||||||
let abort: AbortController | null = null;
|
let abort: AbortController | null = null;
|
||||||
let messagesLoadSeq = 0;
|
let messagesLoadSeq = 0;
|
||||||
@@ -230,6 +241,8 @@ async function ensureSession(): Promise<string | null> {
|
|||||||
|
|
||||||
async function openSettings() {
|
async function openSettings() {
|
||||||
settingsOpen.value = true;
|
settingsOpen.value = true;
|
||||||
|
probedModels.value = [];
|
||||||
|
manualModelId.value = '';
|
||||||
try {
|
try {
|
||||||
const [s, mem] = await Promise.all([
|
const [s, mem] = await Promise.all([
|
||||||
getAgentLlmSettingsApi(),
|
getAgentLlmSettingsApi(),
|
||||||
@@ -237,21 +250,119 @@ async function openSettings() {
|
|||||||
]);
|
]);
|
||||||
llmForm.value = {
|
llmForm.value = {
|
||||||
baseUrl: s.baseUrl || '',
|
baseUrl: s.baseUrl || '',
|
||||||
model: s.model || '',
|
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
apiKeyMasked: s.apiKeyMasked || null,
|
apiKeyMasked: s.apiKeyMasked || null,
|
||||||
configured: !!s.configured,
|
configured: !!s.configured,
|
||||||
contextWindow:
|
displayName: s.displayName || '',
|
||||||
s.contextWindow != null && s.contextWindow > 0
|
|
||||||
? String(s.contextWindow)
|
|
||||||
: '',
|
|
||||||
};
|
};
|
||||||
|
enabledModels.value = (s.models || []).map((m) => ({
|
||||||
|
model: m.model,
|
||||||
|
contextWindow:
|
||||||
|
m.contextWindow != null && m.contextWindow > 0
|
||||||
|
? String(m.contextWindow)
|
||||||
|
: '',
|
||||||
|
isDefault: !!m.isDefault,
|
||||||
|
}));
|
||||||
memories.value = mem.items || [];
|
memories.value = mem.items || [];
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '加载模型配置失败');
|
message.error(e?.message || '加载模型配置失败');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isModelEnabled(id: string) {
|
||||||
|
return enabledModels.value.some((m) => m.model === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleProbedModel(p: AgentVO.ProbedLlmModel, checked: boolean) {
|
||||||
|
if (checked) {
|
||||||
|
if (isModelEnabled(p.id)) return;
|
||||||
|
enabledModels.value.push({
|
||||||
|
model: p.id,
|
||||||
|
contextWindow:
|
||||||
|
p.contextWindow != null && p.contextWindow > 0
|
||||||
|
? String(p.contextWindow)
|
||||||
|
: '',
|
||||||
|
isDefault: enabledModels.value.length === 0,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const wasDefault = enabledModels.value.find(
|
||||||
|
(m) => m.model === p.id,
|
||||||
|
)?.isDefault;
|
||||||
|
enabledModels.value = enabledModels.value.filter((m) => m.model !== p.id);
|
||||||
|
if (wasDefault && enabledModels.value.length > 0) {
|
||||||
|
enabledModels.value[0]!.isDefault = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setDefaultModel(modelId: string) {
|
||||||
|
enabledModels.value = enabledModels.value.map((m) => ({
|
||||||
|
...m,
|
||||||
|
isDefault: m.model === modelId,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeEnabledModel(modelId: string) {
|
||||||
|
const wasDefault = enabledModels.value.find(
|
||||||
|
(m) => m.model === modelId,
|
||||||
|
)?.isDefault;
|
||||||
|
enabledModels.value = enabledModels.value.filter((m) => m.model !== modelId);
|
||||||
|
if (wasDefault && enabledModels.value.length > 0) {
|
||||||
|
enabledModels.value[0]!.isDefault = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addManualModel() {
|
||||||
|
const id = manualModelId.value.trim();
|
||||||
|
if (!id) {
|
||||||
|
message.warning('请输入模型 id');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isModelEnabled(id)) {
|
||||||
|
message.warning('该模型已在启用列表中');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
enabledModels.value.push({
|
||||||
|
model: id,
|
||||||
|
contextWindow: '',
|
||||||
|
isDefault: enabledModels.value.length === 0,
|
||||||
|
});
|
||||||
|
manualModelId.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probeModels() {
|
||||||
|
if (!llmForm.value.baseUrl.trim()) {
|
||||||
|
message.warning('请先填写 Base URL');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const useStored =
|
||||||
|
!!llmForm.value.configured &&
|
||||||
|
(!llmForm.value.apiKey.trim() ||
|
||||||
|
llmForm.value.apiKey.trim().startsWith('****'));
|
||||||
|
if (!useStored && !llmForm.value.apiKey.trim()) {
|
||||||
|
message.warning('请填写 API Key,或先保存密钥后再用已存密钥探测');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
probingModels.value = true;
|
||||||
|
try {
|
||||||
|
const res = await probeAgentLlmModelsApi({
|
||||||
|
baseUrl: llmForm.value.baseUrl.trim(),
|
||||||
|
apiKey: useStored ? undefined : llmForm.value.apiKey.trim(),
|
||||||
|
useStoredKey: useStored,
|
||||||
|
});
|
||||||
|
probedModels.value = res.items || [];
|
||||||
|
if (probedModels.value.length === 0) {
|
||||||
|
message.warning('未返回模型,可手动添加模型 id');
|
||||||
|
} else {
|
||||||
|
message.success(`已加载 ${probedModels.value.length} 个模型`);
|
||||||
|
}
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '加载模型列表失败,可改为手动添加');
|
||||||
|
} finally {
|
||||||
|
probingModels.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function removeMemory(id: string) {
|
async function removeMemory(id: string) {
|
||||||
try {
|
try {
|
||||||
await deleteAgentMemoryApi(id);
|
await deleteAgentMemoryApi(id);
|
||||||
@@ -263,37 +374,58 @@ async function removeMemory(id: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function saveSettings() {
|
async function saveSettings() {
|
||||||
if (!llmForm.value.baseUrl.trim() || !llmForm.value.model.trim()) {
|
if (!llmForm.value.baseUrl.trim()) {
|
||||||
message.warning('请填写 Base URL 与模型名');
|
message.warning('请填写 Base URL');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (enabledModels.value.length === 0) {
|
||||||
|
message.warning('请至少启用一个模型(加载列表勾选或手动添加)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!enabledModels.value.some((m) => m.isDefault)) {
|
||||||
|
enabledModels.value[0]!.isDefault = true;
|
||||||
|
}
|
||||||
|
if (!llmForm.value.configured && !llmForm.value.apiKey.trim()) {
|
||||||
|
message.warning('首次配置必须填写 API Key');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
savingSettings.value = true;
|
savingSettings.value = true;
|
||||||
try {
|
try {
|
||||||
const cwRaw = llmForm.value.contextWindow.trim();
|
const models = enabledModels.value.map((m) => {
|
||||||
let contextWindow: number | undefined;
|
const cw = m.contextWindow.trim();
|
||||||
if (cwRaw === '') {
|
let contextWindow: number | null | undefined;
|
||||||
contextWindow = 0; // 清空为自动估计
|
if (cw === '') {
|
||||||
} else {
|
contextWindow = 0;
|
||||||
const n = Number(cwRaw);
|
} else {
|
||||||
if (!Number.isFinite(n) || n < 0) {
|
const n = Number(cw);
|
||||||
message.warning('上下文窗口请填写正整数,或留空自动估计');
|
if (!Number.isFinite(n) || n < 0) {
|
||||||
return;
|
throw new Error(`模型 ${m.model} 的上下文窗口无效`);
|
||||||
|
}
|
||||||
|
contextWindow = Math.floor(n);
|
||||||
}
|
}
|
||||||
contextWindow = Math.floor(n);
|
return {
|
||||||
}
|
model: m.model,
|
||||||
|
contextWindow,
|
||||||
|
isDefault: m.isDefault,
|
||||||
|
};
|
||||||
|
});
|
||||||
const s = await updateAgentLlmSettingsApi({
|
const s = await updateAgentLlmSettingsApi({
|
||||||
baseUrl: llmForm.value.baseUrl.trim(),
|
baseUrl: llmForm.value.baseUrl.trim(),
|
||||||
model: llmForm.value.model.trim(),
|
|
||||||
apiKey: llmForm.value.apiKey.trim() || undefined,
|
apiKey: llmForm.value.apiKey.trim() || undefined,
|
||||||
contextWindow,
|
displayName: llmForm.value.displayName.trim() || undefined,
|
||||||
|
models,
|
||||||
});
|
});
|
||||||
llmForm.value.configured = s.configured;
|
llmForm.value.configured = s.configured;
|
||||||
llmForm.value.apiKeyMasked = s.apiKeyMasked || null;
|
llmForm.value.apiKeyMasked = s.apiKeyMasked || null;
|
||||||
llmForm.value.apiKey = '';
|
llmForm.value.apiKey = '';
|
||||||
llmForm.value.contextWindow =
|
enabledModels.value = (s.models || []).map((m) => ({
|
||||||
s.contextWindow != null && s.contextWindow > 0
|
model: m.model,
|
||||||
? String(s.contextWindow)
|
contextWindow:
|
||||||
: '';
|
m.contextWindow != null && m.contextWindow > 0
|
||||||
|
? String(m.contextWindow)
|
||||||
|
: '',
|
||||||
|
isDefault: !!m.isDefault,
|
||||||
|
}));
|
||||||
message.success('模型配置已保存');
|
message.success('模型配置已保存');
|
||||||
settingsOpen.value = false;
|
settingsOpen.value = false;
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
@@ -588,14 +720,14 @@ void refreshSessions();
|
|||||||
title="公司模型 API(OpenAI Compatible)"
|
title="公司模型 API(OpenAI Compatible)"
|
||||||
:confirm-loading="savingSettings"
|
:confirm-loading="savingSettings"
|
||||||
ok-text="保存"
|
ok-text="保存"
|
||||||
|
width="640px"
|
||||||
destroy-on-close
|
destroy-on-close
|
||||||
@ok="saveSettings"
|
@ok="saveSettings"
|
||||||
>
|
>
|
||||||
<p class="text-muted-foreground mb-3 text-sm">
|
<p class="text-muted-foreground mb-3 text-sm">
|
||||||
各租户自行填写 Base URL、API Key 与模型名。Key
|
填写 Base URL 与 API Key 后加载模型列表并勾选启用;指定一个默认模型供对话使用。Key
|
||||||
加密落库(MySQL),Agent 经内部接口/Redis 注入;界面仅显示掩码。
|
加密落库,界面仅显示掩码。上下文窗口多数厂商不会在 API 返回,有则预填,可改或留空由
|
||||||
上下文窗口多数厂商不会在 API 里返回,需按模型文档填写;留空则由
|
Agent 估计。
|
||||||
Agent 按模型名估计。
|
|
||||||
</p>
|
</p>
|
||||||
<Form layout="vertical">
|
<Form layout="vertical">
|
||||||
<FormItem label="Base URL" required>
|
<FormItem label="Base URL" required>
|
||||||
@@ -604,19 +736,10 @@ void refreshSessions();
|
|||||||
placeholder="https://api.deepseek.com/v1"
|
placeholder="https://api.deepseek.com/v1"
|
||||||
/>
|
/>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
<FormItem label="Model" required>
|
|
||||||
<Input v-model:value="llmForm.model" placeholder="deepseek-chat" />
|
|
||||||
</FormItem>
|
|
||||||
<FormItem label="上下文窗口(token)">
|
|
||||||
<Input
|
|
||||||
v-model:value="llmForm.contextWindow"
|
|
||||||
placeholder="留空=按模型名自动估计,例如 128000"
|
|
||||||
/>
|
|
||||||
</FormItem>
|
|
||||||
<FormItem
|
<FormItem
|
||||||
:label="
|
:label="
|
||||||
llmForm.configured
|
llmForm.configured
|
||||||
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则不修改)`
|
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则用已存密钥探测/不改 Key)`
|
||||||
: 'API Key'
|
: 'API Key'
|
||||||
"
|
"
|
||||||
:required="!llmForm.configured"
|
:required="!llmForm.configured"
|
||||||
@@ -626,6 +749,93 @@ void refreshSessions();
|
|||||||
placeholder="sk-..."
|
placeholder="sk-..."
|
||||||
/>
|
/>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
<FormItem label="提供商备注(可选)">
|
||||||
|
<Input
|
||||||
|
v-model:value="llmForm.displayName"
|
||||||
|
placeholder="如 DeepSeek"
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
<FormItem label="模型列表">
|
||||||
|
<div class="mb-2 flex flex-wrap gap-2">
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
ghost
|
||||||
|
:loading="probingModels"
|
||||||
|
@click="probeModels"
|
||||||
|
>
|
||||||
|
加载模型列表
|
||||||
|
</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="isModelEnabled(p.id)"
|
||||||
|
@update:checked="(v: boolean) => toggleProbedModel(p, v)"
|
||||||
|
/>
|
||||||
|
<span class="min-w-0 flex-1 truncate">{{ p.id }}</span>
|
||||||
|
<span
|
||||||
|
v-if="p.contextWindow"
|
||||||
|
class="text-muted-foreground shrink-0 text-xs"
|
||||||
|
>
|
||||||
|
{{ p.contextWindow }}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="mb-2 flex gap-2">
|
||||||
|
<Input
|
||||||
|
v-model:value="manualModelId"
|
||||||
|
class="flex-1"
|
||||||
|
placeholder="手动添加模型 id,如 deepseek-chat"
|
||||||
|
@press-enter="addManualModel"
|
||||||
|
/>
|
||||||
|
<Button @click="addManualModel">添加</Button>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="enabledModels.length === 0"
|
||||||
|
class="text-muted-foreground text-xs"
|
||||||
|
>
|
||||||
|
尚未启用模型。请加载列表勾选,或手动添加。
|
||||||
|
</div>
|
||||||
|
<div v-else class="space-y-2">
|
||||||
|
<div
|
||||||
|
v-for="m in 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(m.model)"
|
||||||
|
>
|
||||||
|
默认
|
||||||
|
</Radio>
|
||||||
|
<span class="min-w-0 flex-1 truncate font-medium">{{
|
||||||
|
m.model
|
||||||
|
}}</span>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
danger
|
||||||
|
@click="removeEnabledModel(m.model)"
|
||||||
|
>
|
||||||
|
移除
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
v-model:value="m.contextWindow"
|
||||||
|
size="small"
|
||||||
|
placeholder="上下文窗口 token,留空=自动估计"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</FormItem>
|
||||||
</Form>
|
</Form>
|
||||||
<div class="mt-4 border-t border-border pt-3">
|
<div class="mt-4 border-t border-border pt-3">
|
||||||
<div class="mb-2 text-sm font-medium">我的记忆</div>
|
<div class="mb-2 text-sm font-medium">我的记忆</div>
|
||||||
@@ -640,7 +850,9 @@ void refreshSessions();
|
|||||||
:key="m.id"
|
:key="m.id"
|
||||||
class="mb-1 flex items-start gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-xs"
|
class="mb-1 flex items-start gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-xs"
|
||||||
>
|
>
|
||||||
<span class="min-w-0 flex-1 break-words">{{ m.text }}</span>
|
<span class="min-w-0 flex-1 break-words">{{
|
||||||
|
m.summary || m.text
|
||||||
|
}}</span>
|
||||||
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
||||||
删
|
删
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
Reference in New Issue
Block a user