From aac34249114653de7ea696fc810099d966b025b8 Mon Sep 17 00:00:00 2001 From: ah-max150 Date: Sun, 20 Sep 2026 15:42:25 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=A8=A1=E5=9E=8B=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E9=A1=B5=E4=B8=8E=E4=BC=9A=E8=AF=9D=E7=BA=A7?= =?UTF-8?q?=E9=80=89=E6=A8=A1=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/agent/DESIGN.md | 64 +-- apps/agent/api/deps.py | 23 +- apps/agent/api/routers/sessions.py | 24 +- apps/agent/application/chat_service.py | 8 +- .../agent/application/llm_settings_service.py | 22 +- apps/agent/application/session_service.py | 33 +- apps/agent/domain/models.py | 2 + apps/agent/domain/ports.py | 18 +- apps/agent/infrastructure/llm/gateway.py | 20 +- .../persistence/mongo/repositories.py | 3 + .../infrastructure/persistence/redis/cache.py | 44 +- .../V20260920c__agent_llm_settings_menu.sql | 16 + .../AgentCompanyLlmSettingsController.java | 18 +- .../AgentInternalLlmController.java | 3 +- .../llm/model/vo/AgentLlmEnabledModelsVO.java | 11 + .../AgentCompanyLlmSettingsService.java | 12 +- .../AgentCompanyLlmSettingsServiceImpl.java | 111 +++-- .../src/main/resources/sql/init/sys_seed.sql | 9 +- apps/web/apps/web-antd/src/api/agent/apis.ts | 28 +- apps/web/apps/web-antd/src/api/agent/index.ts | 2 + .../web-antd/src/views/agent/chat/index.vue | 471 ++++-------------- .../src/views/agent/llm-settings/index.vue | 405 +++++++++++++++ .../src/request-client/request-client.test.ts | 10 +- .../src/request-client/request-client.ts | 11 + 24 files changed, 845 insertions(+), 523 deletions(-) create mode 100644 apps/server/sql/migration/V20260920c__agent_llm_settings_menu.sql create mode 100644 apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/model/vo/AgentLlmEnabledModelsVO.java create mode 100644 apps/web/apps/web-antd/src/views/agent/llm-settings/index.vue diff --git a/apps/agent/DESIGN.md b/apps/agent/DESIGN.md index aafbc593..8eb504c4 100644 --- a/apps/agent/DESIGN.md +++ b/apps/agent/DESIGN.md @@ -20,20 +20,22 @@ | 层 | 职责 | 不做什么 | |----|------|----------| -| `apps/web` 聊天页 | UI、会话列表、流式展示;公司 LLM 配置表单(调 Server) | 不编排 LLM、不调 MCP、不持有明文长期 Key(仅提交时传一次) | -| `apps/agent` | 会话/记忆/编排/流式 API、调 MCP、注入租户 LLM 凭证 | 不持久业务单据、不实现业务规则、**不存模型 Key** | +| `apps/web` 聊天页 | UI、会话列表、流式展示、**会话级选模型** | 不编排 LLM、不调 MCP、不持有明文 Key | +| `apps/web` 模型管理页 | 凭证 CRUD、启用模型列表、记忆管理(`agent:llm-settings`) | 不发聊天 | +| `apps/agent` | 会话/记忆/编排/流式 API、调 MCP、按会话模型注入凭证 | 不持久业务单据、不实现业务规则、**不存模型 Key** | | `apps/server` | MySQL 存公司模型配置;MCP `@McpTool`;内部 llm-runtime | 不存聊天记录(对话在 Agent Mongo) | ### 1.3 数据流 ```text -[ web-antd 聊天页 ] +[ web-antd ] │ JWT - ├─► Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key) - └─► Agent /api/agent/sessions|chat|memories (Mongo 会话/记忆) + ├─► 模型管理页 → Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key) + ├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,无 Key) + └─► 聊天页 → Agent /api/agent/sessions|chat|memories (Mongo;会话含 llm_model) │ - ├─ Redis agent:llm:rt:{companyId} 或 Server /api/internal/agent/llm-runtime - ├─ ChatOpenAI(base_url, api_key, model) 按租户注入 + ├─ Redis agent:llm:rt:{companyId}:{model} 或 Server /api/internal/agent/llm-runtime?model= + ├─ ChatOpenAI(base_url, api_key, model) 按会话模型注入 └─ MCP /mcp + X-Agent-Company-Id / X-Agent-User-Id → BI tools ``` @@ -67,11 +69,11 @@ 约束: -1. **真相源**:MySQL `agent_company_llm_settings`(见 `apps/server/sql/design/agent/`);`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。 -2. **缓存**:Redis `agent:llm:rt:{company_id}` → `{base_url, api_key, model, …}`,TTL;配置变更时 DEL;**Agent 与 Server 须同 Redis DB**。 -3. **注入**:Agent 只读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`)。 -4. **权限**:更新需公司 owner(或超管);权限码 `agent:llm-settings`。 -5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发。 +1. **真相源**:MySQL `agent_company_llm_provider` + `agent_company_llm_model`;`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。 +2. **缓存**:Redis `agent:llm:rt:{company_id}:{model}` → `{base_url, api_key, model, context_window, …}`,TTL;配置变更时按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。 +3. **注入**:Agent 按**会话 `llm_model`** 读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`;聊天仅 `GET /agent-llm-models`)。 +4. **权限**:写配置靠 `agent:llm-settings`(不限 owner);聊天选模靠 `agent:chat`。 +5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且仅在无指定 model 时)。 --- @@ -119,6 +121,7 @@ apps/agent/ | `title` | 可空,首轮后可自动生成 | | `status` | `active` / `archived` / `deleted` | | `summary` | 会话滚动摘要(可选) | +| `llm_model` | 会话选用的模型 id(公司启用列表内);空则对话时回落默认并回写 | | `created_at`, `updated_at`, `last_message_at` | | 唯一索引:`(company_id, user_id, thread_id)` @@ -181,7 +184,11 @@ apps/agent/ | `agent_company_llm_provider` | 公司一套 `base_url` + 加密 Key(UNIQUE company) | | `agent_company_llm_model` | 已启用模型多行;`is_default=1` 供 Agent 注入 | -浏览器:`GET/PUT /api/company/agent-llm-settings`;`POST .../probe-models` 代理 `{baseUrl}/v1/models`(不落库)。Agent 内部:`/api/internal/agent/llm-runtime` 返回**默认模型**明文(含 `contextWindow`)。 +浏览器: +- `GET/PUT /api/company/agent-llm-settings` + `POST .../probe-models`(需 `agent:llm-settings`) +- `GET /api/company/agent-llm-models`:启用列表 `{ items: [{ model, label, contextWindow, isDefault }] }`(需 `agent:chat`,无 Key) + +Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&model=` —— `model` 空取默认;有值须在启用列表中,否则 400;返回明文凭证 + `contextWindow`。 ### 4.3 与 LangGraph 的关系 @@ -211,17 +218,17 @@ apps/agent/ | 方法 | 路径 | 说明 | |------|------|------| -| GET | `/sessions` | 当前用户会话列表 | -| POST | `/sessions` | 新建会话 | -| PATCH | `/sessions/{thread_id}` | 改标题/归档 | +| GET | `/sessions` | 当前用户会话列表(含 `llmModel`) | +| POST | `/sessions` | 新建会话(可带 `llmModel`;缺省写公司默认) | +| PATCH | `/sessions/{thread_id}` | 改标题 / `llmModel` | | GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) | -| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE) | +| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话 `llm_model` 解析 runtime | | GET | `/memories` | 查看自己的记忆条目(可透明) | | DELETE | `/memories/{id}` | 用户删除某条记忆 | SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。 -公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型列表);`POST .../probe-models` 拉提供商模型目录(不经 Agent)。 +公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型);`POST .../probe-models`;聊天只读 `GET /api/company/agent-llm-models`。 鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。 @@ -242,25 +249,20 @@ SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状 ### 7.1 页面 -- 路由示例:`/agent/chat` -- 菜单:一级「智能助手」 -- 另:公司配置入口「模型 API」(或聊天页设置抽屉)维护 OpenAI Compatible 凭证 +- 聊天:`/agent/chat`,菜单「智能助手」(仅 `agent:chat`) +- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`) +- 聊天顶栏:`Select` 切换当前会话模型(PATCH `llmModel`);新对话草稿本地暂存,创建时带上 - 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范) ### 7.2 组件(自建,不引入 AI UI 库) ```text views/agent/chat/ - index.vue # 页壳 - components/ - SessionSidebar.vue - MessageList.vue - MessageBubble.vue - ChatComposer.vue - ToolCallBlock.vue # 可选:折叠展示 tool 结果 - composables/ - useAgentChat.ts # 流式消费、本地消息缓冲 -api/agent/ # 调 Agent 服务,非调 Java /api + index.vue # 聊天:会话列表 + 消息 + 顶栏选模型 + catalog-cite*.vue/ts # 店铺/商品引用输入 +views/agent/llm-settings/ + index.vue # 模型管理:凭证 / 启用列表 / 记忆 +api/agent/ # 调 Agent + Server 公司 LLM API ``` ### 7.3 配置 diff --git a/apps/agent/api/deps.py b/apps/agent/api/deps.py index c9aa7136..9ff6aa2d 100644 --- a/apps/agent/api/deps.py +++ b/apps/agent/api/deps.py @@ -34,16 +34,6 @@ async def current_actor( return parse_actor(settings, token) -async def session_service(settings: Settings = Depends(get_settings)) -> SessionService: - db = await get_db(settings) - return SessionService(MongoSessionRepository(db)) - - -async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService: - db = await get_db(settings) - return MemoryService(settings, MongoMemoryRepository(db)) - - async def llm_runtime_service( settings: Settings = Depends(get_settings), ) -> LlmRuntimeService: @@ -51,6 +41,19 @@ async def llm_runtime_service( return LlmRuntimeService(settings, cache, ServerLlmRuntimeGateway(settings)) +async def session_service( + settings: Settings = Depends(get_settings), + llm_svc: LlmRuntimeService = Depends(llm_runtime_service), +) -> SessionService: + db = await get_db(settings) + return SessionService(MongoSessionRepository(db), llm_runtime=llm_svc) + + +async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService: + db = await get_db(settings) + return MemoryService(settings, MongoMemoryRepository(db)) + + async def chat_service( settings: Settings = Depends(get_settings), sessions: SessionService = Depends(session_service), diff --git a/apps/agent/api/routers/sessions.py b/apps/agent/api/routers/sessions.py index 59758e43..fdc7c714 100644 --- a/apps/agent/api/routers/sessions.py +++ b/apps/agent/api/routers/sessions.py @@ -15,10 +15,12 @@ router = APIRouter(prefix="/sessions", tags=["sessions"]) class CreateSessionBody(BaseModel): title: str | None = None + llmModel: str | None = None -class RenameBody(BaseModel): - title: str = Field(min_length=1, max_length=200) +class PatchSessionBody(BaseModel): + title: str | None = Field(default=None, min_length=1, max_length=200) + llmModel: str | None = None def _session_vo(s) -> dict: @@ -26,6 +28,7 @@ def _session_vo(s) -> dict: "threadId": s.thread_id, "title": s.title, "status": s.status.value, + "llmModel": s.llm_model, "createdAt": s.created_at.isoformat() + "Z", "updatedAt": s.updated_at.isoformat() + "Z", "lastMessageAt": s.last_message_at.isoformat() + "Z" if s.last_message_at else None, @@ -47,19 +50,28 @@ async def create_session( actor: Actor = Depends(current_actor), svc: SessionService = Depends(session_service), ): - s = await svc.create(actor, body.title) + s = await svc.create(actor, body.title, llm_model=body.llmModel) return ok(_session_vo(s)) @router.patch("/{thread_id}") -async def rename_session( +async def patch_session( thread_id: str, - body: RenameBody, + body: PatchSessionBody, actor: Actor = Depends(current_actor), svc: SessionService = Depends(session_service), ): + if body.title is None and body.llmModel is None: + raise HTTPException(status_code=400, detail="无有效更新字段") try: - s = await svc.rename(actor, thread_id, body.title) + s = None + if body.title is not None: + s = await svc.rename(actor, thread_id, body.title) + if body.llmModel is not None: + s = await svc.update_llm_model(actor, thread_id, body.llmModel) + assert s is not None + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) from e except LookupError as e: raise HTTPException(status_code=404, detail=str(e)) from e return ok(_session_vo(s)) diff --git a/apps/agent/application/chat_service.py b/apps/agent/application/chat_service.py index a6bb4b89..cdd2381a 100644 --- a/apps/agent/application/chat_service.py +++ b/apps/agent/application/chat_service.py @@ -52,7 +52,13 @@ class ChatService: raise ValueError("消息不能为空") session = await self._sessions.require_owned(actor, thread_id) - llm = await self._llm_runtime.resolve_runtime(actor.company_id) + llm = await self._llm_runtime.resolve_runtime( + actor.company_id, model=session.llm_model + ) + # 会话未记模型或回落后写回,保证列表/选框有稳定值 + if not session.llm_model or session.llm_model != llm.model: + session.llm_model = llm.model + await self._session_repo.update(session) just_saved = await self._memory.maybe_capture_from_user( actor, thread_id=thread_id, text=text ) diff --git a/apps/agent/application/llm_settings_service.py b/apps/agent/application/llm_settings_service.py index 392fdeeb..dad53a46 100644 --- a/apps/agent/application/llm_settings_service.py +++ b/apps/agent/application/llm_settings_service.py @@ -1,4 +1,4 @@ -"""租户 LLM 运行时解析:Redis(Server 写入)→ Server 内部 API → 本地 fallback。""" +"""租户 LLM 运行时解析:Redis → Server 内部 API → 本地 fallback。""" from __future__ import annotations @@ -20,21 +20,28 @@ class LlmRuntimeService: self._cache = cache self._gateway = gateway - async def resolve_runtime(self, company_id: int) -> LlmRuntimeConfig: - cached = await self._cache.get(company_id) + async def resolve_runtime( + self, company_id: int, model: str | None = None + ) -> LlmRuntimeConfig: + want = (model or "").strip() or None + cached = await self._cache.get(company_id, want) if cached is not None and cached.api_key: return cached - remote = await self._gateway.fetch(company_id) + remote = await self._gateway.fetch(company_id, want) if remote is not None and remote.api_key and remote.base_url and remote.model: await self._cache.set( - company_id, remote, self._settings.llm_cache_ttl_seconds + company_id, + remote, + self._settings.llm_cache_ttl_seconds, + model=remote.model, ) return remote if ( self._settings.llm_fallback_enabled and self._settings.llm_fallback_api_key + and not want ): return LlmRuntimeConfig( base_url=self._settings.llm_fallback_base_url.rstrip("/"), @@ -45,5 +52,8 @@ class LlmRuntimeService: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, - detail="当前公司尚未配置模型 API,请先在智能助手设置中填写 OpenAI Compatible 凭证", + detail=( + "当前公司尚未配置模型 API,或所选模型未启用;" + "请在「模型管理」中配置凭证并启用模型" + ), ) diff --git a/apps/agent/application/session_service.py b/apps/agent/application/session_service.py index 1a64a9f5..1ec2adc7 100644 --- a/apps/agent/application/session_service.py +++ b/apps/agent/application/session_service.py @@ -5,22 +5,41 @@ from __future__ import annotations import uuid from datetime import datetime +from application.llm_settings_service import LlmRuntimeService from domain.models import Actor, Session, SessionStatus from domain.ports import SessionRepository class SessionService: - def __init__(self, sessions: SessionRepository) -> None: + def __init__( + self, + sessions: SessionRepository, + llm_runtime: LlmRuntimeService | None = None, + ) -> None: self._sessions = sessions + self._llm_runtime = llm_runtime - async def create(self, actor: Actor, title: str | None = None) -> Session: + async def create( + self, + actor: Actor, + title: str | None = None, + llm_model: str | None = None, + ) -> Session: now = datetime.utcnow() + model = (llm_model or "").strip() or None + if not model and self._llm_runtime is not None: + try: + rt = await self._llm_runtime.resolve_runtime(actor.company_id) + model = rt.model or None + except Exception: + model = None session = Session( thread_id=str(uuid.uuid4()), company_id=actor.company_id, user_id=actor.user_id, title=(title or "新对话").strip() or "新对话", status=SessionStatus.ACTIVE, + llm_model=model, created_at=now, updated_at=now, ) @@ -40,6 +59,16 @@ class SessionService: session.title = title.strip() or session.title return await self._sessions.update(session) + async def update_llm_model( + self, actor: Actor, thread_id: str, llm_model: str + ) -> Session: + model = (llm_model or "").strip() + if not model: + raise ValueError("模型不能为空") + session = await self.require_owned(actor, thread_id) + session.llm_model = model + return await self._sessions.update(session) + async def archive(self, actor: Actor, thread_id: str) -> Session: session = await self.require_owned(actor, thread_id) session.status = SessionStatus.ARCHIVED diff --git a/apps/agent/domain/models.py b/apps/agent/domain/models.py index 044a2a6a..f1ae6a78 100644 --- a/apps/agent/domain/models.py +++ b/apps/agent/domain/models.py @@ -58,6 +58,8 @@ class Session: title: str = "新对话" status: SessionStatus = SessionStatus.ACTIVE summary: str | None = None + # 会话选用的模型 id;空则对话时回落公司默认 + llm_model: str | None = None created_at: datetime = field(default_factory=datetime.utcnow) updated_at: datetime = field(default_factory=datetime.utcnow) last_message_at: datetime | None = None diff --git a/apps/agent/domain/ports.py b/apps/agent/domain/ports.py index 4d8fcd22..bbdfb274 100644 --- a/apps/agent/domain/ports.py +++ b/apps/agent/domain/ports.py @@ -63,20 +63,30 @@ class MemoryRepository(ABC): class LlmRuntimeCache(ABC): @abstractmethod - async def get(self, company_id: int) -> LlmRuntimeConfig | None: ... + async def get( + self, company_id: int, model: str | None = None + ) -> LlmRuntimeConfig | None: ... @abstractmethod - async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None: ... + async def set( + self, + company_id: int, + config: LlmRuntimeConfig, + ttl_seconds: int, + model: str | None = None, + ) -> None: ... @abstractmethod - async def delete(self, company_id: int) -> None: ... + async def delete(self, company_id: int, model: str | None = None) -> None: ... class LlmRuntimeGateway(ABC): """从 Server 拉取运行时模型配置(MySQL 真相源)。""" @abstractmethod - async def fetch(self, company_id: int) -> LlmRuntimeConfig | None: ... + async def fetch( + self, company_id: int, model: str | None = None + ) -> LlmRuntimeConfig | None: ... class ChatStreamer(ABC): diff --git a/apps/agent/infrastructure/llm/gateway.py b/apps/agent/infrastructure/llm/gateway.py index 2f7e0070..9d0bac63 100644 --- a/apps/agent/infrastructure/llm/gateway.py +++ b/apps/agent/infrastructure/llm/gateway.py @@ -14,21 +14,23 @@ logger = logging.getLogger(__name__) class ServerLlmRuntimeGateway(LlmRuntimeGateway): - """GET /api/internal/agent/llm-runtime?companyId=…(Agent Bearer)。""" + """GET /api/internal/agent/llm-runtime?companyId=&model=(Agent Bearer)。""" def __init__(self, settings: Settings) -> None: self._settings = settings - async def fetch(self, company_id: int) -> LlmRuntimeConfig | None: + async def fetch( + self, company_id: int, model: str | None = None + ) -> LlmRuntimeConfig | None: url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime" headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"} + params: dict[str, str | int] = {"companyId": company_id} + if model: + params["model"] = model try: async with httpx.AsyncClient(timeout=15.0) as client: - resp = await client.get( - url, params={"companyId": company_id}, headers=headers - ) + resp = await client.get(url, params=params, headers=headers) if resp.status_code == 400: - # 未配置 return None resp.raise_for_status() body = resp.json() @@ -46,7 +48,11 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway): context_window=_optional_positive_int(data.get("contextWindow")), ) except Exception: - logger.exception("拉取 Server LLM runtime 失败 company_id=%s", company_id) + logger.exception( + "拉取 Server LLM runtime 失败 company_id=%s model=%s", + company_id, + model, + ) return None diff --git a/apps/agent/infrastructure/persistence/mongo/repositories.py b/apps/agent/infrastructure/persistence/mongo/repositories.py index 966037db..ab4d21a9 100644 --- a/apps/agent/infrastructure/persistence/mongo/repositories.py +++ b/apps/agent/infrastructure/persistence/mongo/repositories.py @@ -39,6 +39,7 @@ class MongoSessionRepository(SessionRepository): "title": session.title, "status": session.status.value, "summary": session.summary, + "llm_model": session.llm_model, "created_at": session.created_at, "updated_at": session.updated_at, "last_message_at": session.last_message_at, @@ -79,6 +80,7 @@ class MongoSessionRepository(SessionRepository): "title": session.title, "status": session.status.value, "summary": session.summary, + "llm_model": session.llm_model, "updated_at": session.updated_at, "last_message_at": session.last_message_at, } @@ -95,6 +97,7 @@ class MongoSessionRepository(SessionRepository): title=doc.get("title") or "新对话", status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value), summary=doc.get("summary"), + llm_model=doc.get("llm_model"), created_at=_dt(doc.get("created_at")), updated_at=_dt(doc.get("updated_at")), last_message_at=doc.get("last_message_at"), diff --git a/apps/agent/infrastructure/persistence/redis/cache.py b/apps/agent/infrastructure/persistence/redis/cache.py index 899b9c74..ba50348a 100644 --- a/apps/agent/infrastructure/persistence/redis/cache.py +++ b/apps/agent/infrastructure/persistence/redis/cache.py @@ -1,4 +1,4 @@ -"""Redis 缓存租户 LLM 运行时配置。""" +"""Redis 缓存租户 LLM 运行时配置(按公司+模型)。""" from __future__ import annotations @@ -16,23 +16,40 @@ class RedisLlmRuntimeCache(LlmRuntimeCache): self._r = client @staticmethod - def _key(company_id: int) -> str: + def _key(company_id: int, model: str | None) -> str: + if model: + return f"agent:llm:rt:{company_id}:{model}" return f"agent:llm:rt:{company_id}" - async def get(self, company_id: int) -> LlmRuntimeConfig | None: - raw = await self._r.get(self._key(company_id)) + async def get( + self, company_id: int, model: str | None = None + ) -> LlmRuntimeConfig | None: + raw = await self._r.get(self._key(company_id, model)) + if not raw and model: + # 兼容旧缓存键(仅 companyId) + raw = await self._r.get(self._key(company_id, None)) if not raw: return None data = json.loads(raw) - return LlmRuntimeConfig( + cfg = LlmRuntimeConfig( base_url=data["base_url"], api_key=data["api_key"], model=data["model"], extra_headers=data.get("extra_headers") or {}, context_window=_optional_int(data.get("context_window")), ) + if model and cfg.model and cfg.model != model: + return None + return cfg - async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None: + async def set( + self, + company_id: int, + config: LlmRuntimeConfig, + ttl_seconds: int, + model: str | None = None, + ) -> None: + key_model = model or config.model payload = { "base_url": config.base_url, "api_key": config.api_key, @@ -40,10 +57,19 @@ class RedisLlmRuntimeCache(LlmRuntimeCache): "extra_headers": config.extra_headers, "context_window": config.context_window, } - await self._r.set(self._key(company_id), json.dumps(payload), ex=ttl_seconds) + await self._r.set( + self._key(company_id, key_model), + json.dumps(payload), + ex=ttl_seconds, + ) - async def delete(self, company_id: int) -> None: - await self._r.delete(self._key(company_id)) + async def delete(self, company_id: int, model: str | None = None) -> None: + if model: + await self._r.delete(self._key(company_id, model)) + return + keys = await self._r.keys(f"agent:llm:rt:{company_id}*") + if keys: + await self._r.delete(*keys) _redis: redis.Redis | None = None diff --git a/apps/server/sql/migration/V20260920c__agent_llm_settings_menu.sql b/apps/server/sql/migration/V20260920c__agent_llm_settings_menu.sql new file mode 100644 index 00000000..b2cbb1e8 --- /dev/null +++ b/apps/server/sql/migration/V20260920c__agent_llm_settings_menu.sql @@ -0,0 +1,16 @@ +-- 一级菜单「模型管理」;智能助手菜单仅保留 agent:chat + +INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`) +SELECT 14081, NULL, 0, 'AgentLlmSettings', '模型管理', '/agent/llm-settings', '/agent/llm-settings/index', '', 'lucide:brain-circuit', 'menu', 1, 1, 0, 15 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14081 OR `route_name` = 'AgentLlmSettings'); + +INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`) +SELECT m.id, p.id +FROM `sys_menu` m +JOIN `sys_permission` p ON p.code = 'agent:llm-settings' +WHERE m.route_name = 'AgentLlmSettings'; + +-- 助手菜单去掉模型配置权限绑定(有配置权才看得到新一级菜单) +DELETE mp FROM `sys_menu_permission` mp +INNER JOIN `sys_menu` m ON m.id = mp.menu_id AND m.route_name = 'AgentAssistant' +INNER JOIN `sys_permission` p ON p.id = mp.permission_id AND p.code = 'agent:llm-settings'; diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentCompanyLlmSettingsController.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentCompanyLlmSettingsController.java index b60911b1..b66eaf07 100644 --- a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentCompanyLlmSettingsController.java +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentCompanyLlmSettingsController.java @@ -12,36 +12,44 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission; import top.xyquan.ecomdmbbackend.common.response.ApiResponse; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO; +import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService; /** - * 公司模型 API 配置(浏览器 JWT):凭证 + 多模型勾选。 + * 公司模型 API 配置(浏览器 JWT)。 */ @RestController -@RequestMapping("/api/company/agent-llm-settings") +@RequestMapping("/api/company") @RequiredArgsConstructor public class AgentCompanyLlmSettingsController { private final AgentCompanyLlmSettingsService settingsService; - @GetMapping + @GetMapping("/agent-llm-settings") @RequirePermission(value = "agent:llm-settings", description = "查看模型配置", allowSuper = true) public ApiResponse get() { return ApiResponse.success(settingsService.getForCurrentCompany()); } - @PutMapping + @PutMapping("/agent-llm-settings") @RequirePermission(value = "agent:llm-settings", description = "更新模型配置", allowSuper = true) public ApiResponse upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) { return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto)); } - @PostMapping("/probe-models") + @PostMapping("/agent-llm-settings/probe-models") @RequirePermission(value = "agent:llm-settings", description = "探测模型列表", allowSuper = true) public ApiResponse probeModels( @RequestBody ProbeAgentLlmModelsDTO dto) { return ApiResponse.success(settingsService.probeModels(dto)); } + + /** 聊天选模型:仅启用列表,无 Key */ + @GetMapping("/agent-llm-models") + @RequirePermission(value = "agent:chat", description = "查看可用模型", allowSuper = true) + public ApiResponse listEnabledModels() { + return ApiResponse.success(settingsService.listEnabledModelsForChat()); + } } diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentInternalLlmController.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentInternalLlmController.java index 8d5fa5e7..91f333b8 100644 --- a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentInternalLlmController.java +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/controller/AgentInternalLlmController.java @@ -30,12 +30,13 @@ public class AgentInternalLlmController { @GetMapping("/llm-runtime") public ApiResponse runtime( @RequestParam("companyId") Long companyId, + @RequestParam(value = "model", required = false) String model, HttpServletRequest request) { assertAgentBearer(request); if (companyId == null) { throw new BusinessException("companyId 不能为空"); } - return ApiResponse.success(settingsService.getRuntime(companyId)); + return ApiResponse.success(settingsService.getRuntime(companyId, model)); } private void assertAgentBearer(HttpServletRequest request) { diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/model/vo/AgentLlmEnabledModelsVO.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/model/vo/AgentLlmEnabledModelsVO.java new file mode 100644 index 00000000..50218c09 --- /dev/null +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/model/vo/AgentLlmEnabledModelsVO.java @@ -0,0 +1,11 @@ +package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +@Data +public class AgentLlmEnabledModelsVO { + private List items = new ArrayList<>(); +} diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/AgentCompanyLlmSettingsService.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/AgentCompanyLlmSettingsService.java index 51b0e446..913b2923 100644 --- a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/AgentCompanyLlmSettingsService.java +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/AgentCompanyLlmSettingsService.java @@ -2,6 +2,7 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.service; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO; +import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO; @@ -17,6 +18,13 @@ public interface AgentCompanyLlmSettingsService { AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto); - /** Agent 内部:按公司取默认模型运行时明文 */ - AgentLlmRuntimeVO getRuntime(Long companyId); + /** 聊天用:启用模型列表(无 Key) */ + AgentLlmEnabledModelsVO listEnabledModelsForChat(); + + /** + * Agent 内部:运行时明文。 + * + * @param model 空则默认模型;非空须在启用列表中 + */ + AgentLlmRuntimeVO getRuntime(Long companyId, String model); } diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java index d11f5ec1..99b14ac1 100644 --- a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/agent/llm/service/impl/AgentCompanyLlmSettingsServiceImpl.java @@ -18,6 +18,7 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModels import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmProviderPO; +import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmModelVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO; @@ -26,7 +27,6 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO; import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService; import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto; import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe; -import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.time.Duration; @@ -39,7 +39,7 @@ import java.util.Map; import java.util.Set; /** - * 公司模型 API:MySQL 存密文与启用模型;Redis 缓存默认模型明文供 Agent。 + * 公司模型 API:MySQL 存密文与启用模型;Redis 按模型缓存明文供 Agent。 */ @Slf4j @Service @@ -53,7 +53,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin private final AgentLlmCrypto crypto; private final AgentLlmProperties llmProperties; private final CurrentUserContext currentUserContext; - private final CompanyMemberService companyMemberService; private final StringRedisTemplate stringRedisTemplate; private final ObjectMapper objectMapper; private final OpenAiCompatibleModelsProbe modelsProbe; @@ -61,9 +60,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin @Override public AgentLlmSettingsVO getForCurrentCompany() { Long companyId = currentUserContext.getCurrentCompanyId(); - AgentCompanyLlmProviderPO provider = findProvider(companyId); - List models = listModels(companyId); - return toPublicVo(provider, models); + return toPublicVo(findProvider(companyId), listModels(companyId)); } @Override @@ -71,7 +68,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) { Long companyId = currentUserContext.getCurrentCompanyId(); Long userId = currentUserContext.getCurrentUserId(); - requireOwner(companyId, userId); String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", ""); List modelItems = normalizeModelItems(dto.getModels()); @@ -113,7 +109,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin providerMapper.updateById(existing); } - // 全量覆盖模型:先删后插 modelMapper.delete(new LambdaQueryWrapper() .eq(AgentCompanyLlmModelPO::getCompanyId, companyId)); for (AgentLlmModelItemDTO item : modelItems) { @@ -131,7 +126,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin List savedModels = listModels(companyId); evictRuntimeCache(companyId); try { - cacheRuntime(companyId, buildRuntime(existing, savedModels)); + for (AgentCompanyLlmModelPO m : savedModels) { + cacheRuntime(companyId, buildRuntimeForModel(existing, m)); + } } catch (Exception e) { log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e); } @@ -141,9 +138,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin @Override public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) { Long companyId = currentUserContext.getCurrentCompanyId(); - Long userId = currentUserContext.getCurrentUserId(); - requireOwner(companyId, userId); - if (dto == null || !StringUtils.hasText(dto.getBaseUrl())) { throw new BusinessException("baseUrl 不能为空"); } @@ -161,21 +155,28 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥"); } - List items = modelsProbe.listModels(baseUrl, apiKey); AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO(); + vo.setItems(modelsProbe.listModels(baseUrl, apiKey)); + return vo; + } + + @Override + public AgentLlmEnabledModelsVO listEnabledModelsForChat() { + Long companyId = currentUserContext.getCurrentCompanyId(); + AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO(); + List items = new ArrayList<>(); + for (AgentCompanyLlmModelPO m : listModels(companyId)) { + items.add(toModelVo(m)); + } vo.setItems(items); return vo; } @Override - public AgentLlmRuntimeVO getRuntime(Long companyId) { + public AgentLlmRuntimeVO getRuntime(Long companyId, String model) { if (companyId == null) { throw new BusinessException("companyId 不能为空"); } - AgentLlmRuntimeVO cached = readRuntimeCache(companyId); - if (cached != null) { - return cached; - } AgentCompanyLlmProviderPO provider = findProvider(companyId); if (provider == null) { throw new BusinessException("公司尚未配置模型 API"); @@ -184,18 +185,30 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin if (models.isEmpty()) { throw new BusinessException("公司尚未启用任何模型"); } - AgentLlmRuntimeVO runtime = buildRuntime(provider, models); + + AgentCompanyLlmModelPO selected; + if (StringUtils.hasText(model)) { + String want = model.trim(); + selected = models.stream() + .filter(m -> want.equals(m.getModel())) + .findFirst() + .orElseThrow(() -> new BusinessException("模型未启用或不存在: " + want)); + } else { + selected = models.stream() + .filter(m -> Boolean.TRUE.equals(m.getIsDefault())) + .findFirst() + .orElse(models.get(0)); + } + + AgentLlmRuntimeVO cached = readRuntimeCache(companyId, selected.getModel()); + if (cached != null) { + return cached; + } + AgentLlmRuntimeVO runtime = buildRuntimeForModel(provider, selected); cacheRuntime(companyId, runtime); return runtime; } - private void requireOwner(Long companyId, Long userId) { - if (!currentUserContext.isCurrentUserSuper() - && !companyMemberService.isOwner(userId, companyId)) { - throw new BusinessException("仅公司拥有者可配置模型 API"); - } - } - private List normalizeModelItems(List raw) { if (raw == null || raw.isEmpty()) { throw new BusinessException("至少启用一个模型"); @@ -203,8 +216,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin Set seen = new HashSet<>(); List out = new ArrayList<>(); int defaultIdx = -1; - for (int i = 0; i < raw.size(); i++) { - AgentLlmModelItemDTO item = raw.get(i); + for (AgentLlmModelItemDTO item : raw) { if (item == null || !StringUtils.hasText(item.getModel())) { continue; } @@ -235,17 +247,13 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin return out; } - private AgentLlmRuntimeVO buildRuntime( - AgentCompanyLlmProviderPO provider, List models) { - AgentCompanyLlmModelPO def = models.stream() - .filter(m -> Boolean.TRUE.equals(m.getIsDefault())) - .findFirst() - .orElse(models.get(0)); + private AgentLlmRuntimeVO buildRuntimeForModel( + AgentCompanyLlmProviderPO provider, AgentCompanyLlmModelPO model) { AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO(); vo.setBaseUrl(provider.getBaseUrl()); vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted())); - vo.setModel(def.getModel()); - vo.setContextWindow(def.getContextWindow()); + vo.setModel(model.getModel()); + vo.setContextWindow(model.getContextWindow()); vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson())); return vo; } @@ -290,6 +298,15 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin .orderByAsc(AgentCompanyLlmModelPO::getId)); } + private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m) { + AgentLlmModelVO mv = new AgentLlmModelVO(); + mv.setModel(m.getModel()); + mv.setLabel(m.getLabel()); + mv.setContextWindow(m.getContextWindow()); + mv.setDefault(Boolean.TRUE.equals(m.getIsDefault())); + return mv; + } + private AgentLlmSettingsVO toPublicVo( AgentCompanyLlmProviderPO provider, List models) { AgentLlmSettingsVO vo = new AgentLlmSettingsVO(); @@ -306,19 +323,14 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin } List modelVos = new ArrayList<>(); for (AgentCompanyLlmModelPO m : models) { - AgentLlmModelVO mv = new AgentLlmModelVO(); - mv.setModel(m.getModel()); - mv.setLabel(m.getLabel()); - mv.setContextWindow(m.getContextWindow()); - mv.setDefault(Boolean.TRUE.equals(m.getIsDefault())); - modelVos.add(mv); + modelVos.add(toModelVo(m)); } vo.setModels(modelVos); return vo; } - private static String redisKey(Long companyId) { - return "agent:llm:rt:" + companyId; + private static String redisKey(Long companyId, String model) { + return "agent:llm:rt:" + companyId + ":" + model; } private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) { @@ -331,7 +343,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin payload.put("extra_headers", runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders()); stringRedisTemplate.opsForValue().set( - redisKey(companyId), + redisKey(companyId, runtime.getModel()), objectMapper.writeValueAsString(payload), Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds()))); } catch (Exception e) { @@ -339,9 +351,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin } } - private AgentLlmRuntimeVO readRuntimeCache(Long companyId) { + private AgentLlmRuntimeVO readRuntimeCache(Long companyId, String model) { try { - String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId)); + String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, model)); if (!StringUtils.hasText(raw)) { return null; } @@ -379,6 +391,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin } private void evictRuntimeCache(Long companyId) { - stringRedisTemplate.delete(redisKey(companyId)); + Set keys = stringRedisTemplate.keys("agent:llm:rt:" + companyId + "*"); + if (keys != null && !keys.isEmpty()) { + stringRedisTemplate.delete(keys); + } } } diff --git a/apps/server/src/main/resources/sql/init/sys_seed.sql b/apps/server/src/main/resources/sql/init/sys_seed.sql index ee125ba3..2fe8d315 100644 --- a/apps/server/src/main/resources/sql/init/sys_seed.sql +++ b/apps/server/src/main/resources/sql/init/sys_seed.sql @@ -950,5 +950,12 @@ SELECT 4802, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), ' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4802 OR `code` = 'agent:llm-settings'); INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`) -SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('agent:chat', 'agent:llm-settings') WHERE m.route_name = 'AgentAssistant'; +SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:chat' WHERE m.route_name = 'AgentAssistant'; + +INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`) +SELECT 14081, NULL, 0, 'AgentLlmSettings', '模型管理', '/agent/llm-settings', '/agent/llm-settings/index', '', 'lucide:brain-circuit', 'menu', 1, 1, 0, 15 +FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14081 OR `route_name` = 'AgentLlmSettings'); + +INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`) +SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:llm-settings' WHERE m.route_name = 'AgentLlmSettings'; diff --git a/apps/web/apps/web-antd/src/api/agent/apis.ts b/apps/web/apps/web-antd/src/api/agent/apis.ts index 9eddd84b..640017cc 100644 --- a/apps/web/apps/web-antd/src/api/agent/apis.ts +++ b/apps/web/apps/web-antd/src/api/agent/apis.ts @@ -9,6 +9,7 @@ export namespace AgentVO { threadId: string; title: string; status: string; + llmModel?: string | null; createdAt?: string; updatedAt?: string; lastMessageAt?: string | null; @@ -57,8 +58,24 @@ export async function listAgentSessionsApi() { return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions'); } -export async function createAgentSessionApi(title?: string) { - return requestClient.post('/agent/sessions', { title }); +export async function createAgentSessionApi(options?: { + title?: string; + llmModel?: string; +}) { + return requestClient.post('/agent/sessions', { + title: options?.title, + llmModel: options?.llmModel, + }); +} + +export async function patchAgentSessionApi( + threadId: string, + body: { title?: string; llmModel?: string }, +) { + return requestClient.patch( + `/agent/sessions/${threadId}`, + body, + ); } export async function listAgentMessagesApi(threadId: string) { @@ -98,6 +115,13 @@ export async function updateAgentLlmSettingsApi(body: { ); } +/** 聊天选模型:已启用列表,不含 Key */ +export async function listAgentEnabledLlmModelsApi() { + return requestClient.get<{ items: AgentVO.LlmModelItem[] }>( + '/company/agent-llm-models', + ); +} + /** 服务端代理 GET /v1/models,不落库 */ export async function probeAgentLlmModelsApi(body: { baseUrl: string; diff --git a/apps/web/apps/web-antd/src/api/agent/index.ts b/apps/web/apps/web-antd/src/api/agent/index.ts index 942a4dae..0e30860f 100644 --- a/apps/web/apps/web-antd/src/api/agent/index.ts +++ b/apps/web/apps/web-antd/src/api/agent/index.ts @@ -3,9 +3,11 @@ export { createAgentSessionApi, deleteAgentMemoryApi, getAgentLlmSettingsApi, + listAgentEnabledLlmModelsApi, listAgentMemoriesApi, listAgentMessagesApi, listAgentSessionsApi, + patchAgentSessionApi, probeAgentLlmModelsApi, streamAgentChat, updateAgentLlmSettingsApi, diff --git a/apps/web/apps/web-antd/src/views/agent/chat/index.vue b/apps/web/apps/web-antd/src/views/agent/chat/index.vue index 75f90a6a..16814b59 100644 --- a/apps/web/apps/web-antd/src/views/agent/chat/index.vue +++ b/apps/web/apps/web-antd/src/views/agent/chat/index.vue @@ -2,36 +2,21 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'; import { Page } from '@vben/common-ui'; -import { PlusOutlined, SettingOutlined } from '@ant-design/icons-vue'; +import { PlusOutlined } from '@ant-design/icons-vue'; -import { - Button, - Checkbox, - Empty, - Form, - FormItem, - Input, - InputPassword, - Modal, - Radio, - Spin, - message, -} from 'ant-design-vue'; +import { Button, Empty, Select, Spin, message } from 'ant-design-vue'; import { ChatItem } from '@tdesign-vue-next/chat'; import 'tdesign-vue-next/es/style/index.css'; import '@tdesign-vue-next/chat/es/style/index.css'; import { createAgentSessionApi, - deleteAgentMemoryApi, - getAgentLlmSettingsApi, - listAgentMemoriesApi, + listAgentEnabledLlmModelsApi, listAgentMessagesApi, listAgentSessionsApi, - probeAgentLlmModelsApi, + patchAgentSessionApi, streamAgentChat, type AgentVO, - updateAgentLlmSettingsApi, } from '#/api/agent'; import CatalogCiteSender from './catalog-cite-sender.vue'; @@ -76,26 +61,10 @@ const toolStatusActive = ref(false); const draft = ref(''); /** 本条消息附带的店铺/商品/SKU,发送时写成 [引用] 块 */ const citations = ref([]); -const settingsOpen = ref(false); -const savingSettings = ref(false); -const probingModels = ref(false); -const memories = ref([]); -/** 探测到的候选模型(勾选后进 enabledModels) */ -const probedModels = ref([]); -const manualModelId = ref(''); -type EnabledModelRow = { - model: string; - contextWindow: string; - isDefault: boolean; -}; -const llmForm = ref({ - baseUrl: '', - apiKey: '', - apiKeyMasked: '' as string | null, - configured: false, - displayName: '', -}); -const enabledModels = ref([]); +const enabledModels = ref([]); +/** 当前选中模型(有会话时与 session.llmModel 同步;草稿态本地暂存) */ +const selectedModel = ref(undefined); +const patchingModel = ref(false); const messagePaneRef = ref(null); let abort: AbortController | null = null; let messagesLoadSeq = 0; @@ -104,6 +73,13 @@ const activeSession = computed(() => sessions.value.find((s) => s.threadId === activeThreadId.value), ); +const modelOptions = computed(() => + enabledModels.value.map((m) => ({ + value: m.model, + label: m.label || m.model, + })), +); + const showMessageLoading = computed( () => loadingMessages.value && !sending.value && messages.value.length === 0, ); @@ -151,6 +127,22 @@ function scrollChatToBottom() { el.scrollTop = el.scrollHeight; } +function defaultModelId() { + const d = enabledModels.value.find((m) => m.isDefault); + return d?.model || enabledModels.value[0]?.model; +} + +function syncSelectedFromSession() { + const s = activeSession.value; + if (s?.llmModel) { + selectedModel.value = s.llmModel; + return; + } + if (!selectedModel.value) { + selectedModel.value = defaultModelId(); + } +} + function onSessionClick(threadId: string) { if (sending.value) { message.warning('回复生成中,请稍候再切换会话'); @@ -169,6 +161,7 @@ async function refreshSessions() { if (!composingNew.value && !activeThreadId.value && sessions.value[0]) { activeThreadId.value = sessions.value[0].threadId; } + syncSelectedFromSession(); } catch (e: any) { message.error(e?.message || '加载会话失败'); } finally { @@ -176,6 +169,18 @@ async function refreshSessions() { } } +async function loadEnabledModels() { + try { + const res = await listAgentEnabledLlmModelsApi(); + enabledModels.value = res.items || []; + if (!selectedModel.value) { + selectedModel.value = defaultModelId(); + } + } catch { + enabledModels.value = []; + } +} + async function loadMessages(threadId: string) { const seq = ++messagesLoadSeq; loadingMessages.value = true; @@ -190,6 +195,7 @@ async function loadMessages(threadId: string) { } messages.value = res.items || []; streamingText.value = ''; + syncSelectedFromSession(); await nextTick(); scrollChatToBottom(); } catch (e: any) { @@ -205,10 +211,14 @@ async function loadMessages(threadId: string) { watch(activeThreadId, (id) => { if (sending.value) return; - if (id) void loadMessages(id); - else { + if (id) { + void loadMessages(id); + } else { messages.value = []; streamingText.value = ''; + if (!selectedModel.value) { + selectedModel.value = defaultModelId(); + } } }); @@ -227,211 +237,40 @@ function beginNewChat() { streamingText.value = ''; draft.value = ''; citations.value = []; + selectedModel.value = defaultModelId(); } /** 第一条消息发出时才落库 */ async function ensureSession(): Promise { if (activeThreadId.value) return activeThreadId.value; - const s = await createAgentSessionApi(); + const s = await createAgentSessionApi({ + llmModel: selectedModel.value, + }); composingNew.value = false; sessions.value = [s, ...sessions.value]; activeThreadId.value = s.threadId; + if (s.llmModel) { + selectedModel.value = s.llmModel; + } return s.threadId; } -async function openSettings() { - settingsOpen.value = true; - probedModels.value = []; - manualModelId.value = ''; +async function onModelChange(model: string) { + selectedModel.value = model; + const threadId = activeThreadId.value; + if (!threadId || composingNew.value) return; + patchingModel.value = true; try { - const [s, mem] = await Promise.all([ - getAgentLlmSettingsApi(), - listAgentMemoriesApi().catch(() => ({ items: [] as AgentVO.Memory[] })), - ]); - llmForm.value = { - baseUrl: s.baseUrl || '', - apiKey: '', - apiKeyMasked: s.apiKeyMasked || null, - configured: !!s.configured, - displayName: s.displayName || '', - }; - 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 || []; - } catch (e: any) { - 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} 个模型`); + const s = await patchAgentSessionApi(threadId, { llmModel: model }); + const idx = sessions.value.findIndex((x) => x.threadId === threadId); + if (idx >= 0) { + sessions.value[idx] = { ...sessions.value[idx]!, ...s }; } } catch (e: any) { - message.error(e?.message || '加载模型列表失败,可改为手动添加'); + message.error(e?.message || '切换模型失败'); + syncSelectedFromSession(); } finally { - probingModels.value = false; - } -} - -async function removeMemory(id: string) { - try { - await deleteAgentMemoryApi(id); - memories.value = memories.value.filter((m) => m.id !== id); - message.success('已删除记忆'); - } catch (e: any) { - message.error(e?.message || '删除失败'); - } -} - -async function saveSettings() { - if (!llmForm.value.baseUrl.trim()) { - 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; - } - savingSettings.value = true; - try { - const models = enabledModels.value.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} 的上下文窗口无效`); - } - contextWindow = Math.floor(n); - } - return { - model: m.model, - contextWindow, - isDefault: m.isDefault, - }; - }); - const s = await updateAgentLlmSettingsApi({ - baseUrl: llmForm.value.baseUrl.trim(), - apiKey: llmForm.value.apiKey.trim() || undefined, - displayName: llmForm.value.displayName.trim() || undefined, - models, - }); - llmForm.value.configured = s.configured; - llmForm.value.apiKeyMasked = s.apiKeyMasked || null; - llmForm.value.apiKey = ''; - enabledModels.value = (s.models || []).map((m) => ({ - model: m.model, - contextWindow: - m.contextWindow != null && m.contextWindow > 0 - ? String(m.contextWindow) - : '', - isDefault: !!m.isDefault, - })); - message.success('模型配置已保存'); - settingsOpen.value = false; - } catch (e: any) { - message.error(e?.message || '保存失败'); - } finally { - savingSettings.value = false; + patchingModel.value = false; } } @@ -459,7 +298,6 @@ function onStreamTool(payload: { toolStatusLabel.value = payload.label; void nextTick().then(scrollChatToBottom); } else if (payload.phase === 'end') { - // 同轮可能多个工具;最后一个 end 后仍保持到有 token / done 再清也可 toolStatusLabel.value = payload.label; } } @@ -558,7 +396,7 @@ function onSenderStop() { onBeforeUnmount(() => abort?.abort()); -void refreshSessions(); +void loadEnabledModels().then(() => refreshSessions()); diff --git a/apps/web/apps/web-antd/src/views/agent/llm-settings/index.vue b/apps/web/apps/web-antd/src/views/agent/llm-settings/index.vue new file mode 100644 index 00000000..18856855 --- /dev/null +++ b/apps/web/apps/web-antd/src/views/agent/llm-settings/index.vue @@ -0,0 +1,405 @@ + + + diff --git a/apps/web/packages/effects/request/src/request-client/request-client.test.ts b/apps/web/packages/effects/request/src/request-client/request-client.test.ts index 2d94525e..022342df 100644 --- a/apps/web/packages/effects/request/src/request-client/request-client.test.ts +++ b/apps/web/packages/effects/request/src/request-client/request-client.test.ts @@ -41,6 +41,14 @@ describe('requestClient', () => { expect(response.data).toEqual(mockData); }); + it('should successfully make a PATCH request', async () => { + const patchData = { key: 'patchedValue' }; + const mockData = { data: 'patched response' }; + mock.onPatch('/test/patch', patchData).reply(200, mockData); + const response = await requestClient.patch('/test/patch', patchData); + expect(response.data).toEqual(mockData); + }); + it('should successfully make a DELETE request', async () => { const mockData = { data: 'delete response' }; mock.onDelete('/test/delete').reply(200, mockData); @@ -94,6 +102,6 @@ describe('requestClient', () => { const res = await requestClient.download('/test/download'); - expect(res.data).toBeInstanceOf(Blob); + expect(res).toBeInstanceOf(Blob); }); }); diff --git a/apps/web/packages/effects/request/src/request-client/request-client.ts b/apps/web/packages/effects/request/src/request-client/request-client.ts index 42e95de2..c497d83f 100644 --- a/apps/web/packages/effects/request/src/request-client/request-client.ts +++ b/apps/web/packages/effects/request/src/request-client/request-client.ts @@ -125,6 +125,17 @@ class RequestClient { return this.request(url, { ...config, data, method: 'PUT' }); } + /** + * PATCH请求方法 + */ + public patch( + url: string, + data?: any, + config?: RequestClientConfig, + ): Promise { + return this.request(url, { ...config, data, method: 'PATCH' }); + } + /** * 通用的请求方法 */