mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 模型管理独立页与会话级选模型
This commit is contained in:
+33
-31
@@ -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 配置
|
||||
|
||||
+13
-10
@@ -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),
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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,或所选模型未启用;"
|
||||
"请在「模型管理」中配置凭证并启用模型"
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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';
|
||||
+13
-5
@@ -12,36 +12,44 @@ import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
|
||||
/**
|
||||
* 公司模型 API 配置(浏览器 JWT):凭证 + 多模型勾选。
|
||||
* 公司模型 API 配置(浏览器 JWT)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/company/agent-llm-settings")
|
||||
@RequestMapping("/api/company")
|
||||
@RequiredArgsConstructor
|
||||
public class AgentCompanyLlmSettingsController {
|
||||
|
||||
private final AgentCompanyLlmSettingsService settingsService;
|
||||
|
||||
@GetMapping
|
||||
@GetMapping("/agent-llm-settings")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "查看模型配置", allowSuper = true)
|
||||
public ApiResponse<AgentLlmSettingsVO> get() {
|
||||
return ApiResponse.success(settingsService.getForCurrentCompany());
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
@PutMapping("/agent-llm-settings")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "更新模型配置", allowSuper = true)
|
||||
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
||||
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto));
|
||||
}
|
||||
|
||||
@PostMapping("/probe-models")
|
||||
@PostMapping("/agent-llm-settings/probe-models")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "探测模型列表", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProbeModelsResultVO> probeModels(
|
||||
@RequestBody ProbeAgentLlmModelsDTO dto) {
|
||||
return ApiResponse.success(settingsService.probeModels(dto));
|
||||
}
|
||||
|
||||
/** 聊天选模型:仅启用列表,无 Key */
|
||||
@GetMapping("/agent-llm-models")
|
||||
@RequirePermission(value = "agent:chat", description = "查看可用模型", allowSuper = true)
|
||||
public ApiResponse<AgentLlmEnabledModelsVO> listEnabledModels() {
|
||||
return ApiResponse.success(settingsService.listEnabledModelsForChat());
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -30,12 +30,13 @@ public class AgentInternalLlmController {
|
||||
@GetMapping("/llm-runtime")
|
||||
public ApiResponse<AgentLlmRuntimeVO> runtime(
|
||||
@RequestParam("companyId") Long companyId,
|
||||
@RequestParam(value = "model", required = false) String model,
|
||||
HttpServletRequest request) {
|
||||
assertAgentBearer(request);
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
return ApiResponse.success(settingsService.getRuntime(companyId));
|
||||
return ApiResponse.success(settingsService.getRuntime(companyId, model));
|
||||
}
|
||||
|
||||
private void assertAgentBearer(HttpServletRequest request) {
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AgentLlmEnabledModelsVO {
|
||||
private List<AgentLlmModelVO> items = new ArrayList<>();
|
||||
}
|
||||
+10
-2
@@ -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);
|
||||
}
|
||||
|
||||
+63
-48
@@ -18,6 +18,7 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModels
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmProviderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmModelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO;
|
||||
@@ -26,7 +27,6 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.member.service.CompanyMemberService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.time.Duration;
|
||||
@@ -39,7 +39,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 公司模型 API:MySQL 存密文与启用模型;Redis 缓存默认模型明文供 Agent。
|
||||
* 公司模型 API:MySQL 存密文与启用模型;Redis 按模型缓存明文供 Agent。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -53,7 +53,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
private final AgentLlmCrypto crypto;
|
||||
private final AgentLlmProperties llmProperties;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final CompanyMemberService companyMemberService;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OpenAiCompatibleModelsProbe modelsProbe;
|
||||
@@ -61,9 +60,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
@Override
|
||||
public AgentLlmSettingsVO getForCurrentCompany() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
||||
return toPublicVo(provider, models);
|
||||
return toPublicVo(findProvider(companyId), listModels(companyId));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -71,7 +68,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
requireOwner(companyId, userId);
|
||||
|
||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||
List<AgentLlmModelItemDTO> modelItems = normalizeModelItems(dto.getModels());
|
||||
@@ -113,7 +109,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
providerMapper.updateById(existing);
|
||||
}
|
||||
|
||||
// 全量覆盖模型:先删后插
|
||||
modelMapper.delete(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId));
|
||||
for (AgentLlmModelItemDTO item : modelItems) {
|
||||
@@ -131,7 +126,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
List<AgentCompanyLlmModelPO> savedModels = listModels(companyId);
|
||||
evictRuntimeCache(companyId);
|
||||
try {
|
||||
cacheRuntime(companyId, buildRuntime(existing, savedModels));
|
||||
for (AgentCompanyLlmModelPO m : savedModels) {
|
||||
cacheRuntime(companyId, buildRuntimeForModel(existing, m));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e);
|
||||
}
|
||||
@@ -141,9 +138,6 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
@Override
|
||||
public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
requireOwner(companyId, userId);
|
||||
|
||||
if (dto == null || !StringUtils.hasText(dto.getBaseUrl())) {
|
||||
throw new BusinessException("baseUrl 不能为空");
|
||||
}
|
||||
@@ -161,21 +155,28 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥");
|
||||
}
|
||||
|
||||
List<AgentLlmProbedModelVO> items = modelsProbe.listModels(baseUrl, apiKey);
|
||||
AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO();
|
||||
vo.setItems(modelsProbe.listModels(baseUrl, apiKey));
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmEnabledModelsVO listEnabledModelsForChat() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO();
|
||||
List<AgentLlmModelVO> items = new ArrayList<>();
|
||||
for (AgentCompanyLlmModelPO m : listModels(companyId)) {
|
||||
items.add(toModelVo(m));
|
||||
}
|
||||
vo.setItems(items);
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmRuntimeVO getRuntime(Long companyId) {
|
||||
public AgentLlmRuntimeVO getRuntime(Long companyId, String model) {
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
AgentLlmRuntimeVO cached = readRuntimeCache(companyId);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
||||
if (provider == null) {
|
||||
throw new BusinessException("公司尚未配置模型 API");
|
||||
@@ -184,18 +185,30 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
if (models.isEmpty()) {
|
||||
throw new BusinessException("公司尚未启用任何模型");
|
||||
}
|
||||
AgentLlmRuntimeVO runtime = buildRuntime(provider, models);
|
||||
|
||||
AgentCompanyLlmModelPO selected;
|
||||
if (StringUtils.hasText(model)) {
|
||||
String want = model.trim();
|
||||
selected = models.stream()
|
||||
.filter(m -> want.equals(m.getModel()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException("模型未启用或不存在: " + want));
|
||||
} else {
|
||||
selected = models.stream()
|
||||
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
|
||||
.findFirst()
|
||||
.orElse(models.get(0));
|
||||
}
|
||||
|
||||
AgentLlmRuntimeVO cached = readRuntimeCache(companyId, selected.getModel());
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
AgentLlmRuntimeVO runtime = buildRuntimeForModel(provider, selected);
|
||||
cacheRuntime(companyId, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private void requireOwner(Long companyId, Long userId) {
|
||||
if (!currentUserContext.isCurrentUserSuper()
|
||||
&& !companyMemberService.isOwner(userId, companyId)) {
|
||||
throw new BusinessException("仅公司拥有者可配置模型 API");
|
||||
}
|
||||
}
|
||||
|
||||
private List<AgentLlmModelItemDTO> normalizeModelItems(List<AgentLlmModelItemDTO> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
throw new BusinessException("至少启用一个模型");
|
||||
@@ -203,8 +216,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
Set<String> seen = new HashSet<>();
|
||||
List<AgentLlmModelItemDTO> out = new ArrayList<>();
|
||||
int defaultIdx = -1;
|
||||
for (int i = 0; i < raw.size(); i++) {
|
||||
AgentLlmModelItemDTO item = raw.get(i);
|
||||
for (AgentLlmModelItemDTO item : raw) {
|
||||
if (item == null || !StringUtils.hasText(item.getModel())) {
|
||||
continue;
|
||||
}
|
||||
@@ -235,17 +247,13 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
return out;
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO buildRuntime(
|
||||
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
|
||||
AgentCompanyLlmModelPO def = models.stream()
|
||||
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
|
||||
.findFirst()
|
||||
.orElse(models.get(0));
|
||||
private AgentLlmRuntimeVO buildRuntimeForModel(
|
||||
AgentCompanyLlmProviderPO provider, AgentCompanyLlmModelPO model) {
|
||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||
vo.setModel(def.getModel());
|
||||
vo.setContextWindow(def.getContextWindow());
|
||||
vo.setModel(model.getModel());
|
||||
vo.setContextWindow(model.getContextWindow());
|
||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||
return vo;
|
||||
}
|
||||
@@ -290,6 +298,15 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m) {
|
||||
AgentLlmModelVO mv = new AgentLlmModelVO();
|
||||
mv.setModel(m.getModel());
|
||||
mv.setLabel(m.getLabel());
|
||||
mv.setContextWindow(m.getContextWindow());
|
||||
mv.setDefault(Boolean.TRUE.equals(m.getIsDefault()));
|
||||
return mv;
|
||||
}
|
||||
|
||||
private AgentLlmSettingsVO toPublicVo(
|
||||
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
|
||||
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
|
||||
@@ -306,19 +323,14 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
List<AgentLlmModelVO> modelVos = new ArrayList<>();
|
||||
for (AgentCompanyLlmModelPO m : models) {
|
||||
AgentLlmModelVO mv = new AgentLlmModelVO();
|
||||
mv.setModel(m.getModel());
|
||||
mv.setLabel(m.getLabel());
|
||||
mv.setContextWindow(m.getContextWindow());
|
||||
mv.setDefault(Boolean.TRUE.equals(m.getIsDefault()));
|
||||
modelVos.add(mv);
|
||||
modelVos.add(toModelVo(m));
|
||||
}
|
||||
vo.setModels(modelVos);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private static String redisKey(Long companyId) {
|
||||
return "agent:llm:rt:" + companyId;
|
||||
private static String redisKey(Long companyId, String model) {
|
||||
return "agent:llm:rt:" + companyId + ":" + model;
|
||||
}
|
||||
|
||||
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
|
||||
@@ -331,7 +343,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
payload.put("extra_headers",
|
||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
redisKey(companyId),
|
||||
redisKey(companyId, runtime.getModel()),
|
||||
objectMapper.writeValueAsString(payload),
|
||||
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
|
||||
} catch (Exception e) {
|
||||
@@ -339,9 +351,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO readRuntimeCache(Long companyId) {
|
||||
private AgentLlmRuntimeVO readRuntimeCache(Long companyId, String model) {
|
||||
try {
|
||||
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId));
|
||||
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, model));
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return null;
|
||||
}
|
||||
@@ -379,6 +391,9 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
||||
}
|
||||
|
||||
private void evictRuntimeCache(Long companyId) {
|
||||
stringRedisTemplate.delete(redisKey(companyId));
|
||||
Set<String> keys = stringRedisTemplate.keys("agent:llm:rt:" + companyId + "*");
|
||||
if (keys != null && !keys.isEmpty()) {
|
||||
stringRedisTemplate.delete(keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -950,5 +950,12 @@ SELECT 4802, (SELECT id FROM `sys_permission` WHERE `code` = 'agent' LIMIT 1), '
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `id` = 4802 OR `code` = 'agent:llm-settings');
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code IN ('agent:chat', 'agent:llm-settings') WHERE m.route_name = 'AgentAssistant';
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:chat' WHERE m.route_name = 'AgentAssistant';
|
||||
|
||||
INSERT INTO `sys_menu` (`id`, `parent_id`, `super`, `route_name`, `title`, `path`, `component`, `redirect`, `icon`, `type`, `visible`, `status`, `keep_alive`, `order`)
|
||||
SELECT 14081, NULL, 0, 'AgentLlmSettings', '模型管理', '/agent/llm-settings', '/agent/llm-settings/index', '', 'lucide:brain-circuit', 'menu', 1, 1, 0, 15
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_menu` WHERE `id` = 14081 OR `route_name` = 'AgentLlmSettings');
|
||||
|
||||
INSERT IGNORE INTO `sys_menu_permission` (`menu_id`, `permission_id`)
|
||||
SELECT m.id, p.id FROM `sys_menu` m JOIN `sys_permission` p ON p.code = 'agent:llm-settings' WHERE m.route_name = 'AgentLlmSettings';
|
||||
|
||||
|
||||
@@ -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<AgentVO.Session>('/agent/sessions', { title });
|
||||
export async function createAgentSessionApi(options?: {
|
||||
title?: string;
|
||||
llmModel?: string;
|
||||
}) {
|
||||
return requestClient.post<AgentVO.Session>('/agent/sessions', {
|
||||
title: options?.title,
|
||||
llmModel: options?.llmModel,
|
||||
});
|
||||
}
|
||||
|
||||
export async function patchAgentSessionApi(
|
||||
threadId: string,
|
||||
body: { title?: string; llmModel?: string },
|
||||
) {
|
||||
return requestClient.patch<AgentVO.Session>(
|
||||
`/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;
|
||||
|
||||
@@ -3,9 +3,11 @@ export {
|
||||
createAgentSessionApi,
|
||||
deleteAgentMemoryApi,
|
||||
getAgentLlmSettingsApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentMemoriesApi,
|
||||
listAgentMessagesApi,
|
||||
listAgentSessionsApi,
|
||||
patchAgentSessionApi,
|
||||
probeAgentLlmModelsApi,
|
||||
streamAgentChat,
|
||||
updateAgentLlmSettingsApi,
|
||||
|
||||
@@ -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<CatalogCite[]>([]);
|
||||
const settingsOpen = ref(false);
|
||||
const savingSettings = ref(false);
|
||||
const probingModels = ref(false);
|
||||
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({
|
||||
baseUrl: '',
|
||||
apiKey: '',
|
||||
apiKeyMasked: '' as string | null,
|
||||
configured: false,
|
||||
displayName: '',
|
||||
});
|
||||
const enabledModels = ref<EnabledModelRow[]>([]);
|
||||
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
||||
/** 当前选中模型(有会话时与 session.llmModel 同步;草稿态本地暂存) */
|
||||
const selectedModel = ref<string | undefined>(undefined);
|
||||
const patchingModel = ref(false);
|
||||
const messagePaneRef = ref<HTMLElement | null>(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<string | null> {
|
||||
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());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -618,25 +456,29 @@ void refreshSessions();
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="border-t border-border p-3">
|
||||
<Button block @click="openSettings">
|
||||
<template #icon><SettingOutlined /></template>
|
||||
模型 API 设置
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="agent-chat-main flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<header
|
||||
class="flex h-12 shrink-0 items-center border-b border-border px-4"
|
||||
class="flex h-12 shrink-0 items-center gap-3 border-b border-border px-4"
|
||||
>
|
||||
<span class="truncate font-medium">
|
||||
<span class="min-w-0 flex-1 truncate font-medium">
|
||||
{{
|
||||
composingNew
|
||||
? '新对话'
|
||||
: activeSession?.title || '智能助手'
|
||||
}}
|
||||
</span>
|
||||
<Select
|
||||
:value="selectedModel"
|
||||
:options="modelOptions"
|
||||
:loading="patchingModel"
|
||||
:disabled="sending || modelOptions.length === 0"
|
||||
placeholder="选择模型"
|
||||
class="w-56 shrink-0"
|
||||
:allow-clear="false"
|
||||
@change="(v: string) => onModelChange(v)"
|
||||
/>
|
||||
</header>
|
||||
|
||||
<div class="relative flex min-h-0 flex-1 flex-col">
|
||||
@@ -649,7 +491,7 @@ void refreshSessions();
|
||||
<Empty
|
||||
v-if="!showStarter && !showMessageLoading && messages.length === 0"
|
||||
class="absolute inset-0 flex items-center justify-center"
|
||||
description="开始提问吧(需先配置公司模型 API)"
|
||||
description="开始提问吧(需先在「模型管理」配置 API)"
|
||||
/>
|
||||
<div
|
||||
ref="messagePaneRef"
|
||||
@@ -714,151 +556,6 @@ void refreshSessions();
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
v-model:open="settingsOpen"
|
||||
title="公司模型 API(OpenAI Compatible)"
|
||||
:confirm-loading="savingSettings"
|
||||
ok-text="保存"
|
||||
width="640px"
|
||||
destroy-on-close
|
||||
@ok="saveSettings"
|
||||
>
|
||||
<p class="text-muted-foreground mb-3 text-sm">
|
||||
填写 Base URL 与 API Key 后加载模型列表并勾选启用;指定一个默认模型供对话使用。Key
|
||||
加密落库,界面仅显示掩码。上下文窗口多数厂商不会在 API 返回,有则预填,可改或留空由
|
||||
Agent 估计。
|
||||
</p>
|
||||
<Form layout="vertical">
|
||||
<FormItem label="Base URL" required>
|
||||
<Input
|
||||
v-model:value="llmForm.baseUrl"
|
||||
placeholder="https://api.deepseek.com/v1"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem
|
||||
:label="
|
||||
llmForm.configured
|
||||
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则用已存密钥探测/不改 Key)`
|
||||
: 'API Key'
|
||||
"
|
||||
:required="!llmForm.configured"
|
||||
>
|
||||
<InputPassword
|
||||
v-model:value="llmForm.apiKey"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
</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>
|
||||
<div class="mt-4 border-t border-border pt-3">
|
||||
<div class="mb-2 text-sm font-medium">我的记忆</div>
|
||||
<p class="text-muted-foreground mb-2 text-xs">
|
||||
对话中发送「记住:…」可写入;助手按需检索,不会默认注入全部记忆。
|
||||
</p>
|
||||
<div v-if="memories.length === 0" class="text-muted-foreground text-xs">
|
||||
暂无记忆
|
||||
</div>
|
||||
<div
|
||||
v-for="m in memories"
|
||||
:key="m.id"
|
||||
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.summary || m.text
|
||||
}}</span>
|
||||
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
||||
删
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Checkbox,
|
||||
Form,
|
||||
FormItem,
|
||||
Input,
|
||||
InputPassword,
|
||||
Radio,
|
||||
Spin,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
deleteAgentMemoryApi,
|
||||
getAgentLlmSettingsApi,
|
||||
listAgentMemoriesApi,
|
||||
probeAgentLlmModelsApi,
|
||||
type AgentVO,
|
||||
updateAgentLlmSettingsApi,
|
||||
} from '#/api/agent';
|
||||
|
||||
defineOptions({ name: 'AgentLlmSettings' });
|
||||
|
||||
const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
const probingModels = ref(false);
|
||||
const memories = ref<AgentVO.Memory[]>([]);
|
||||
const probedModels = ref<AgentVO.ProbedLlmModel[]>([]);
|
||||
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<EnabledModelRow[]>([]);
|
||||
|
||||
async function loadAll() {
|
||||
loading.value = true;
|
||||
probedModels.value = [];
|
||||
manualModelId.value = '';
|
||||
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 || '加载模型配置失败');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
saving.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('模型配置已保存');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadAll();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height>
|
||||
<div class="relative mx-auto max-w-3xl space-y-4 pb-8">
|
||||
<div
|
||||
v-if="loading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-background/50"
|
||||
>
|
||||
<Spin />
|
||||
</div>
|
||||
|
||||
<Card title="公司模型 API(OpenAI Compatible)" :bordered="false">
|
||||
<p class="text-muted-foreground mb-4 text-sm">
|
||||
填写 Base URL 与 API Key 后加载模型列表并勾选启用;指定一个默认模型供新对话使用。Key
|
||||
加密落库,界面仅显示掩码。上下文窗口多数厂商不会在 API
|
||||
返回,有则预填,可改或留空由 Agent 估计。
|
||||
</p>
|
||||
<Form layout="vertical">
|
||||
<FormItem label="Base URL" required>
|
||||
<Input
|
||||
v-model:value="llmForm.baseUrl"
|
||||
placeholder="https://api.deepseek.com/v1"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem
|
||||
:label="
|
||||
llmForm.configured
|
||||
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则用已存密钥探测/不改 Key)`
|
||||
: 'API Key'
|
||||
"
|
||||
:required="!llmForm.configured"
|
||||
>
|
||||
<InputPassword
|
||||
v-model:value="llmForm.apiKey"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
</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>
|
||||
<Button type="primary" :loading="saving" @click="saveSettings">
|
||||
保存
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Card title="我的记忆" :bordered="false">
|
||||
<p class="text-muted-foreground mb-3 text-xs">
|
||||
对话中发送「记住:…」可写入;助手按需检索,不会默认注入全部记忆。
|
||||
</p>
|
||||
<div v-if="memories.length === 0" class="text-muted-foreground text-sm">
|
||||
暂无记忆
|
||||
</div>
|
||||
<div
|
||||
v-for="m in memories"
|
||||
:key="m.id"
|
||||
class="mb-2 flex items-start gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm"
|
||||
>
|
||||
<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>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</Page>
|
||||
</template>
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -125,6 +125,17 @@ class RequestClient {
|
||||
return this.request<T>(url, { ...config, data, method: 'PUT' });
|
||||
}
|
||||
|
||||
/**
|
||||
* PATCH请求方法
|
||||
*/
|
||||
public patch<T = any>(
|
||||
url: string,
|
||||
data?: any,
|
||||
config?: RequestClientConfig,
|
||||
): Promise<T> {
|
||||
return this.request<T>(url, { ...config, data, method: 'PATCH' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用的请求方法
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user