mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 07:09:20 +08:00
feat: 公司支持多模型提供商与会话消歧选型
This commit is contained in:
+29
-25
@@ -30,12 +30,13 @@
|
|||||||
```text
|
```text
|
||||||
[ web-antd ]
|
[ web-antd ]
|
||||||
│ JWT
|
│ JWT
|
||||||
├─► 模型管理页 → Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key)
|
├─► 模型管理页 → Server /api/company/agent-llm-providers* (多提供商 CRUD)
|
||||||
├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,无 Key)
|
├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,含 providerId)
|
||||||
└─► 聊天页 → Agent /api/agent/sessions|chat|memories (Mongo;会话含 llm_model)
|
└─► 聊天页 → Agent /api/agent/sessions|chat|memories (Mongo;会话含 llm_provider_id + llm_model)
|
||||||
│
|
│
|
||||||
├─ Redis agent:llm:rt:{companyId}:{model} 或 Server /api/internal/agent/llm-runtime?model=
|
├─ Redis agent:llm:rt:{companyId}:{providerId}:{model}
|
||||||
├─ ChatOpenAI(base_url, api_key, model) 按会话模型注入
|
├─ Server /api/internal/agent/llm-runtime?companyId=&providerId=&model=
|
||||||
|
├─ ChatOpenAI(base_url, api_key, model) 按会话选型注入
|
||||||
└─ MCP /mcp + X-Agent-Company-Id / X-Agent-User-Id → BI tools
|
└─ MCP /mcp + X-Agent-Company-Id / X-Agent-User-Id → BI tools
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -69,11 +70,12 @@
|
|||||||
|
|
||||||
约束:
|
约束:
|
||||||
|
|
||||||
1. **真相源**:MySQL `agent_company_llm_provider` + `agent_company_llm_model`;`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。
|
1. **真相源**:MySQL `agent_company_llm_provider`(多行/公司)+ `agent_company_llm_model`(挂 `provider_id`);`api_key` **AES-GCM 加密**。
|
||||||
2. **缓存**:Redis `agent:llm:rt:{company_id}:{model}` → `{base_url, api_key, model, context_window, …}`,TTL;配置变更时按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。
|
2. **缓存**:Redis `agent:llm:rt:{company_id}:{provider_id}:{model}`;配置变更按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。
|
||||||
3. **注入**:Agent 按**会话 `llm_model`** 读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`;聊天仅 `GET /agent-llm-models`)。
|
3. **注入**:Agent 按会话 **`llm_provider_id` + `llm_model`** 解析;跨提供商允许同名 model。
|
||||||
4. **权限**:写配置靠 `agent:llm-settings`(不限 owner);聊天选模靠 `agent:chat`。
|
4. **权限**:写配置靠 `agent:llm-settings`;聊天选模靠 `agent:chat`。
|
||||||
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且仅在无指定 model 时)。
|
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且未指定选型时)。
|
||||||
|
6. **启用列表写入**:按 `(provider_id, model)` **增量 upsert**(更新已有、插入新增、删除取消勾选),禁止整表删建,以免破坏会话引用。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -121,7 +123,8 @@ apps/agent/
|
|||||||
| `title` | 可空,首轮后可自动生成 |
|
| `title` | 可空,首轮后可自动生成 |
|
||||||
| `status` | `active` / `archived` / `deleted` |
|
| `status` | `active` / `archived` / `deleted` |
|
||||||
| `summary` | 会话滚动摘要(可选) |
|
| `summary` | 会话滚动摘要(可选) |
|
||||||
| `llm_model` | 会话选用的模型 id(公司启用列表内);空则对话时回落默认并回写 |
|
| `llm_provider_id` | 会话选用的提供商 id |
|
||||||
|
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
|
||||||
| `created_at`, `updated_at`, `last_message_at` | |
|
| `created_at`, `updated_at`, `last_message_at` | |
|
||||||
|
|
||||||
唯一索引:`(company_id, user_id, thread_id)`
|
唯一索引:`(company_id, user_id, thread_id)`
|
||||||
@@ -177,18 +180,19 @@ apps/agent/
|
|||||||
|
|
||||||
### 4.2.1 公司模型配置(MySQL,不在 Mongo)
|
### 4.2.1 公司模型配置(MySQL,不在 Mongo)
|
||||||
|
|
||||||
见 `apps/server/sql/design/agent/agent_company_llm_provider_models_design.sql` 与迁移 `V20260920b__agent_llm_provider_models.sql`(旧单表迁入后改名为 `_deprecated`)。
|
见 `apps/server/sql/design/agent/agent_company_llm_provider_models_design.sql` 与迁移 `V20260920b` / `V20260920d`(多提供商)。
|
||||||
|
|
||||||
| 表 | 说明 |
|
| 表 | 说明 |
|
||||||
|----|------|
|
|----|------|
|
||||||
| `agent_company_llm_provider` | 公司一套 `base_url` + 加密 Key(UNIQUE company) |
|
| `agent_company_llm_provider` | 公司多套 `base_url` + 加密 Key |
|
||||||
| `agent_company_llm_model` | 已启用模型多行;`is_default=1` 供 Agent 注入 |
|
| `agent_company_llm_model` | 挂 `provider_id`;`UNIQUE(provider_id, model)`;公司级全局一条 `is_default=1` |
|
||||||
|
|
||||||
浏览器:
|
浏览器:
|
||||||
- `GET/PUT /api/company/agent-llm-settings` + `POST .../probe-models`(需 `agent:llm-settings`)
|
- `GET/POST /api/company/agent-llm-providers`;`GET/PUT/DELETE .../providers/{id}`;`PUT .../providers/{id}/models`(增量 upsert)
|
||||||
- `GET /api/company/agent-llm-models`:启用列表 `{ items: [{ model, label, contextWindow, isDefault }] }`(需 `agent:chat`,无 Key)
|
- `POST /api/company/agent-llm-settings/probe-models`(可带 `providerId` + `useStoredKey`)
|
||||||
|
- `GET /api/company/agent-llm-models`:`{ items: [{ providerId, providerDisplayName, model, label, contextWindow, isDefault }] }`
|
||||||
|
|
||||||
Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&model=` —— `model` 空取默认;有值须在启用列表中,否则 400;返回明文凭证 + `contextWindow`。
|
Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=`。
|
||||||
|
|
||||||
### 4.3 与 LangGraph 的关系
|
### 4.3 与 LangGraph 的关系
|
||||||
|
|
||||||
@@ -218,17 +222,17 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&model=` —— `m
|
|||||||
|
|
||||||
| 方法 | 路径 | 说明 |
|
| 方法 | 路径 | 说明 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| GET | `/sessions` | 当前用户会话列表(含 `llmModel`) |
|
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
||||||
| POST | `/sessions` | 新建会话(可带 `llmModel`;缺省写公司默认) |
|
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
||||||
| PATCH | `/sessions/{thread_id}` | 改标题 / `llmModel` |
|
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
||||||
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
||||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话 `llm_model` 解析 runtime |
|
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
||||||
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
||||||
| DELETE | `/memories/{id}` | 用户删除某条记忆 |
|
| DELETE | `/memories/{id}` | 用户删除某条记忆 |
|
||||||
|
|
||||||
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
|
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
|
||||||
|
|
||||||
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型);`POST .../probe-models`;聊天只读 `GET /api/company/agent-llm-models`。
|
公司 LLM 配置在 **Server**:按提供商 CRUD + `PUT .../models` 增量 upsert;聊天只读 `GET /api/company/agent-llm-models`。
|
||||||
|
|
||||||
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
|
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
|
||||||
|
|
||||||
@@ -250,9 +254,9 @@ SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状
|
|||||||
### 7.1 页面
|
### 7.1 页面
|
||||||
|
|
||||||
- 聊天:`/agent/chat`,菜单「智能助手」(仅 `agent:chat`)
|
- 聊天:`/agent/chat`,菜单「智能助手」(仅 `agent:chat`)
|
||||||
- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`)
|
- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`);多提供商卡片
|
||||||
- 我的记忆:`/agent/memories`,头像下拉入口(有 `agent:chat` 时显示;静态路由)
|
- 我的记忆:`/agent/memories`,头像下拉入口(有 `agent:chat` 时显示;静态路由)
|
||||||
- 聊天顶栏:`Select` 切换当前会话模型(PATCH `llmModel`);新对话草稿本地暂存,创建时带上
|
- 聊天顶栏:按提供商分组 `Select`;切换即 PATCH `llmProviderId`+`llmModel`
|
||||||
- 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范)
|
- 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范)
|
||||||
|
|
||||||
### 7.2 组件(自建,不引入 AI UI 库)
|
### 7.2 组件(自建,不引入 AI UI 库)
|
||||||
@@ -262,7 +266,7 @@ views/agent/chat/
|
|||||||
index.vue # 聊天:会话列表 + 消息 + 顶栏选模型
|
index.vue # 聊天:会话列表 + 消息 + 顶栏选模型
|
||||||
catalog-cite*.vue/ts # 店铺/商品引用输入
|
catalog-cite*.vue/ts # 店铺/商品引用输入
|
||||||
views/agent/llm-settings/
|
views/agent/llm-settings/
|
||||||
index.vue # 模型管理:凭证 / 启用列表
|
index.vue # 模型管理:多提供商 CRUD + 启用列表增量保存
|
||||||
views/agent/memories/
|
views/agent/memories/
|
||||||
index.vue # 我的记忆:列表 / 删除(用户中心入口)
|
index.vue # 我的记忆:列表 / 删除(用户中心入口)
|
||||||
api/agent/ # 调 Agent + Server 公司 LLM API
|
api/agent/ # 调 Agent + Server 公司 LLM API
|
||||||
|
|||||||
@@ -15,11 +15,13 @@ router = APIRouter(prefix="/sessions", tags=["sessions"])
|
|||||||
|
|
||||||
class CreateSessionBody(BaseModel):
|
class CreateSessionBody(BaseModel):
|
||||||
title: str | None = None
|
title: str | None = None
|
||||||
|
llmProviderId: int | None = None
|
||||||
llmModel: str | None = None
|
llmModel: str | None = None
|
||||||
|
|
||||||
|
|
||||||
class PatchSessionBody(BaseModel):
|
class PatchSessionBody(BaseModel):
|
||||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||||
|
llmProviderId: int | None = None
|
||||||
llmModel: str | None = None
|
llmModel: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@@ -28,6 +30,7 @@ def _session_vo(s) -> dict:
|
|||||||
"threadId": s.thread_id,
|
"threadId": s.thread_id,
|
||||||
"title": s.title,
|
"title": s.title,
|
||||||
"status": s.status.value,
|
"status": s.status.value,
|
||||||
|
"llmProviderId": s.llm_provider_id,
|
||||||
"llmModel": s.llm_model,
|
"llmModel": s.llm_model,
|
||||||
"createdAt": s.created_at.isoformat() + "Z",
|
"createdAt": s.created_at.isoformat() + "Z",
|
||||||
"updatedAt": s.updated_at.isoformat() + "Z",
|
"updatedAt": s.updated_at.isoformat() + "Z",
|
||||||
@@ -50,7 +53,12 @@ async def create_session(
|
|||||||
actor: Actor = Depends(current_actor),
|
actor: Actor = Depends(current_actor),
|
||||||
svc: SessionService = Depends(session_service),
|
svc: SessionService = Depends(session_service),
|
||||||
):
|
):
|
||||||
s = await svc.create(actor, body.title, llm_model=body.llmModel)
|
s = await svc.create(
|
||||||
|
actor,
|
||||||
|
body.title,
|
||||||
|
llm_provider_id=body.llmProviderId,
|
||||||
|
llm_model=body.llmModel,
|
||||||
|
)
|
||||||
return ok(_session_vo(s))
|
return ok(_session_vo(s))
|
||||||
|
|
||||||
|
|
||||||
@@ -61,14 +69,23 @@ async def patch_session(
|
|||||||
actor: Actor = Depends(current_actor),
|
actor: Actor = Depends(current_actor),
|
||||||
svc: SessionService = Depends(session_service),
|
svc: SessionService = Depends(session_service),
|
||||||
):
|
):
|
||||||
if body.title is None and body.llmModel is None:
|
if body.title is None and body.llmModel is None and body.llmProviderId is None:
|
||||||
raise HTTPException(status_code=400, detail="无有效更新字段")
|
raise HTTPException(status_code=400, detail="无有效更新字段")
|
||||||
try:
|
try:
|
||||||
s = None
|
s = None
|
||||||
if body.title is not None:
|
if body.title is not None:
|
||||||
s = await svc.rename(actor, thread_id, body.title)
|
s = await svc.rename(actor, thread_id, body.title)
|
||||||
if body.llmModel is not None:
|
if body.llmModel is not None or body.llmProviderId is not None:
|
||||||
s = await svc.update_llm_model(actor, thread_id, body.llmModel)
|
if body.llmModel is None or body.llmProviderId is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400, detail="切换模型须同时提供 llmProviderId 与 llmModel"
|
||||||
|
)
|
||||||
|
s = await svc.update_llm_selection(
|
||||||
|
actor,
|
||||||
|
thread_id,
|
||||||
|
llm_provider_id=body.llmProviderId,
|
||||||
|
llm_model=body.llmModel,
|
||||||
|
)
|
||||||
assert s is not None
|
assert s is not None
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||||
|
|||||||
@@ -53,11 +53,19 @@ class ChatService:
|
|||||||
|
|
||||||
session = await self._sessions.require_owned(actor, thread_id)
|
session = await self._sessions.require_owned(actor, thread_id)
|
||||||
llm = await self._llm_runtime.resolve_runtime(
|
llm = await self._llm_runtime.resolve_runtime(
|
||||||
actor.company_id, model=session.llm_model
|
actor.company_id,
|
||||||
|
provider_id=session.llm_provider_id,
|
||||||
|
model=session.llm_model,
|
||||||
)
|
)
|
||||||
# 会话未记模型或回落后写回,保证列表/选框有稳定值
|
# 回落默认或消歧后写回会话,保证列表/选框稳定
|
||||||
if not session.llm_model or session.llm_model != llm.model:
|
changed = False
|
||||||
|
if session.llm_model != llm.model:
|
||||||
session.llm_model = llm.model
|
session.llm_model = llm.model
|
||||||
|
changed = True
|
||||||
|
if llm.provider_id is not None and session.llm_provider_id != llm.provider_id:
|
||||||
|
session.llm_provider_id = llm.provider_id
|
||||||
|
changed = True
|
||||||
|
if changed:
|
||||||
await self._session_repo.update(session)
|
await self._session_repo.update(session)
|
||||||
just_saved = await self._memory.maybe_capture_from_user(
|
just_saved = await self._memory.maybe_capture_from_user(
|
||||||
actor, thread_id=thread_id, text=text
|
actor, thread_id=thread_id, text=text
|
||||||
|
|||||||
@@ -21,32 +21,37 @@ class LlmRuntimeService:
|
|||||||
self._gateway = gateway
|
self._gateway = gateway
|
||||||
|
|
||||||
async def resolve_runtime(
|
async def resolve_runtime(
|
||||||
self, company_id: int, model: str | None = None
|
self,
|
||||||
|
company_id: int,
|
||||||
|
provider_id: int | None = None,
|
||||||
|
model: str | None = None,
|
||||||
) -> LlmRuntimeConfig:
|
) -> LlmRuntimeConfig:
|
||||||
want = (model or "").strip() or None
|
want_model = (model or "").strip() or None
|
||||||
cached = await self._cache.get(company_id, want)
|
want_provider = provider_id
|
||||||
|
cached = await self._cache.get(company_id, want_provider, want_model)
|
||||||
if cached is not None and cached.api_key:
|
if cached is not None and cached.api_key:
|
||||||
return cached
|
return cached
|
||||||
|
|
||||||
remote = await self._gateway.fetch(company_id, want)
|
remote = await self._gateway.fetch(company_id, want_provider, want_model)
|
||||||
if remote is not None and remote.api_key and remote.base_url and remote.model:
|
if remote is not None and remote.api_key and remote.base_url and remote.model:
|
||||||
await self._cache.set(
|
await self._cache.set(
|
||||||
company_id,
|
company_id,
|
||||||
remote,
|
remote,
|
||||||
self._settings.llm_cache_ttl_seconds,
|
self._settings.llm_cache_ttl_seconds,
|
||||||
model=remote.model,
|
|
||||||
)
|
)
|
||||||
return remote
|
return remote
|
||||||
|
|
||||||
if (
|
if (
|
||||||
self._settings.llm_fallback_enabled
|
self._settings.llm_fallback_enabled
|
||||||
and self._settings.llm_fallback_api_key
|
and self._settings.llm_fallback_api_key
|
||||||
and not want
|
and not want_model
|
||||||
|
and want_provider is None
|
||||||
):
|
):
|
||||||
return LlmRuntimeConfig(
|
return LlmRuntimeConfig(
|
||||||
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
|
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
|
||||||
api_key=self._settings.llm_fallback_api_key,
|
api_key=self._settings.llm_fallback_api_key,
|
||||||
model=self._settings.llm_fallback_model,
|
model=self._settings.llm_fallback_model,
|
||||||
|
provider_id=None,
|
||||||
context_window=None,
|
context_window=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -54,6 +59,6 @@ class LlmRuntimeService:
|
|||||||
status_code=status.HTTP_400_BAD_REQUEST,
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
detail=(
|
detail=(
|
||||||
"当前公司尚未配置模型 API,或所选模型未启用;"
|
"当前公司尚未配置模型 API,或所选模型未启用;"
|
||||||
"请在「模型管理」中配置凭证并启用模型"
|
"请在「模型管理」中配置提供商并启用模型"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -23,22 +23,30 @@ class SessionService:
|
|||||||
self,
|
self,
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
title: str | None = None,
|
title: str | None = None,
|
||||||
|
llm_provider_id: int | None = None,
|
||||||
llm_model: str | None = None,
|
llm_model: str | None = None,
|
||||||
) -> Session:
|
) -> Session:
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
model = (llm_model or "").strip() or None
|
model = (llm_model or "").strip() or None
|
||||||
if not model and self._llm_runtime is not None:
|
provider_id = llm_provider_id
|
||||||
|
if (not model or provider_id is None) and self._llm_runtime is not None:
|
||||||
try:
|
try:
|
||||||
rt = await self._llm_runtime.resolve_runtime(actor.company_id)
|
rt = await self._llm_runtime.resolve_runtime(
|
||||||
model = rt.model or None
|
actor.company_id,
|
||||||
|
provider_id=provider_id,
|
||||||
|
model=model,
|
||||||
|
)
|
||||||
|
model = rt.model or model
|
||||||
|
provider_id = rt.provider_id if rt.provider_id is not None else provider_id
|
||||||
except Exception:
|
except Exception:
|
||||||
model = None
|
pass
|
||||||
session = Session(
|
session = Session(
|
||||||
thread_id=str(uuid.uuid4()),
|
thread_id=str(uuid.uuid4()),
|
||||||
company_id=actor.company_id,
|
company_id=actor.company_id,
|
||||||
user_id=actor.user_id,
|
user_id=actor.user_id,
|
||||||
title=(title or "新对话").strip() or "新对话",
|
title=(title or "新对话").strip() or "新对话",
|
||||||
status=SessionStatus.ACTIVE,
|
status=SessionStatus.ACTIVE,
|
||||||
|
llm_provider_id=provider_id,
|
||||||
llm_model=model,
|
llm_model=model,
|
||||||
created_at=now,
|
created_at=now,
|
||||||
updated_at=now,
|
updated_at=now,
|
||||||
@@ -59,13 +67,21 @@ class SessionService:
|
|||||||
session.title = title.strip() or session.title
|
session.title = title.strip() or session.title
|
||||||
return await self._sessions.update(session)
|
return await self._sessions.update(session)
|
||||||
|
|
||||||
async def update_llm_model(
|
async def update_llm_selection(
|
||||||
self, actor: Actor, thread_id: str, llm_model: str
|
self,
|
||||||
|
actor: Actor,
|
||||||
|
thread_id: str,
|
||||||
|
*,
|
||||||
|
llm_provider_id: int,
|
||||||
|
llm_model: str,
|
||||||
) -> Session:
|
) -> Session:
|
||||||
model = (llm_model or "").strip()
|
model = (llm_model or "").strip()
|
||||||
if not model:
|
if not model:
|
||||||
raise ValueError("模型不能为空")
|
raise ValueError("模型不能为空")
|
||||||
|
if llm_provider_id is None or int(llm_provider_id) <= 0:
|
||||||
|
raise ValueError("提供商不能为空")
|
||||||
session = await self.require_owned(actor, thread_id)
|
session = await self.require_owned(actor, thread_id)
|
||||||
|
session.llm_provider_id = int(llm_provider_id)
|
||||||
session.llm_model = model
|
session.llm_model = model
|
||||||
return await self._sessions.update(session)
|
return await self._sessions.update(session)
|
||||||
|
|
||||||
|
|||||||
@@ -58,7 +58,8 @@ class Session:
|
|||||||
title: str = "新对话"
|
title: str = "新对话"
|
||||||
status: SessionStatus = SessionStatus.ACTIVE
|
status: SessionStatus = SessionStatus.ACTIVE
|
||||||
summary: str | None = None
|
summary: str | None = None
|
||||||
# 会话选用的模型 id;空则对话时回落公司默认
|
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
|
||||||
|
llm_provider_id: int | None = None
|
||||||
llm_model: str | None = None
|
llm_model: str | None = None
|
||||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||||
@@ -105,6 +106,7 @@ class LlmRuntimeConfig:
|
|||||||
base_url: str
|
base_url: str
|
||||||
api_key: str
|
api_key: str
|
||||||
model: str
|
model: str
|
||||||
|
provider_id: int | None = None
|
||||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||||
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
|
||||||
context_window: int | None = None
|
context_window: int | None = None
|
||||||
|
|||||||
@@ -64,7 +64,10 @@ class MemoryRepository(ABC):
|
|||||||
class LlmRuntimeCache(ABC):
|
class LlmRuntimeCache(ABC):
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def get(
|
async def get(
|
||||||
self, company_id: int, model: str | None = None
|
self,
|
||||||
|
company_id: int,
|
||||||
|
provider_id: int | None = None,
|
||||||
|
model: str | None = None,
|
||||||
) -> LlmRuntimeConfig | None: ...
|
) -> LlmRuntimeConfig | None: ...
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
@@ -73,11 +76,10 @@ class LlmRuntimeCache(ABC):
|
|||||||
company_id: int,
|
company_id: int,
|
||||||
config: LlmRuntimeConfig,
|
config: LlmRuntimeConfig,
|
||||||
ttl_seconds: int,
|
ttl_seconds: int,
|
||||||
model: str | None = None,
|
|
||||||
) -> None: ...
|
) -> None: ...
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def delete(self, company_id: int, model: str | None = None) -> None: ...
|
async def delete(self, company_id: int) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
class LlmRuntimeGateway(ABC):
|
class LlmRuntimeGateway(ABC):
|
||||||
@@ -85,7 +87,10 @@ class LlmRuntimeGateway(ABC):
|
|||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def fetch(
|
async def fetch(
|
||||||
self, company_id: int, model: str | None = None
|
self,
|
||||||
|
company_id: int,
|
||||||
|
provider_id: int | None = None,
|
||||||
|
model: str | None = None,
|
||||||
) -> LlmRuntimeConfig | None: ...
|
) -> LlmRuntimeConfig | None: ...
|
||||||
|
|
||||||
|
|
||||||
@@ -101,5 +106,5 @@ class ChatStreamer(ABC):
|
|||||||
user_text: str,
|
user_text: str,
|
||||||
system_prompt: str,
|
system_prompt: str,
|
||||||
tools: list[Any] | None = None,
|
tools: list[Any] | None = None,
|
||||||
max_tool_result_chars: int = 8000,
|
max_tool_result_chars: int = 4000,
|
||||||
) -> AsyncIterator[StreamEvent]: ...
|
) -> AsyncIterator[StreamEvent]: ...
|
||||||
|
|||||||
@@ -14,17 +14,22 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||||
"""GET /api/internal/agent/llm-runtime?companyId=&model=(Agent Bearer)。"""
|
"""GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=。"""
|
||||||
|
|
||||||
def __init__(self, settings: Settings) -> None:
|
def __init__(self, settings: Settings) -> None:
|
||||||
self._settings = settings
|
self._settings = settings
|
||||||
|
|
||||||
async def fetch(
|
async def fetch(
|
||||||
self, company_id: int, model: str | None = None
|
self,
|
||||||
|
company_id: int,
|
||||||
|
provider_id: int | None = None,
|
||||||
|
model: str | None = None,
|
||||||
) -> LlmRuntimeConfig | None:
|
) -> LlmRuntimeConfig | None:
|
||||||
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
|
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
|
||||||
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
|
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
|
||||||
params: dict[str, str | int] = {"companyId": company_id}
|
params: dict[str, str | int] = {"companyId": company_id}
|
||||||
|
if provider_id is not None:
|
||||||
|
params["providerId"] = provider_id
|
||||||
if model:
|
if model:
|
||||||
params["model"] = model
|
params["model"] = model
|
||||||
try:
|
try:
|
||||||
@@ -37,10 +42,12 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
|||||||
data = body.get("data") if isinstance(body, dict) else None
|
data = body.get("data") if isinstance(body, dict) else None
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
return None
|
return None
|
||||||
|
pid = data.get("providerId")
|
||||||
return LlmRuntimeConfig(
|
return LlmRuntimeConfig(
|
||||||
base_url=str(data.get("baseUrl") or "").rstrip("/"),
|
base_url=str(data.get("baseUrl") or "").rstrip("/"),
|
||||||
api_key=str(data.get("apiKey") or ""),
|
api_key=str(data.get("apiKey") or ""),
|
||||||
model=str(data.get("model") or ""),
|
model=str(data.get("model") or ""),
|
||||||
|
provider_id=int(pid) if pid is not None else provider_id,
|
||||||
extra_headers={
|
extra_headers={
|
||||||
str(k): str(v)
|
str(k): str(v)
|
||||||
for k, v in (data.get("extraHeaders") or {}).items()
|
for k, v in (data.get("extraHeaders") or {}).items()
|
||||||
@@ -49,8 +56,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
|||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(
|
logger.exception(
|
||||||
"拉取 Server LLM runtime 失败 company_id=%s model=%s",
|
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
|
||||||
company_id,
|
company_id,
|
||||||
|
provider_id,
|
||||||
model,
|
model,
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -27,6 +27,15 @@ def _dt(v: Any) -> datetime:
|
|||||||
return datetime.utcnow()
|
return datetime.utcnow()
|
||||||
|
|
||||||
|
|
||||||
|
def _optional_int(v: Any) -> int | None:
|
||||||
|
if v is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return int(v)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
class MongoSessionRepository(SessionRepository):
|
class MongoSessionRepository(SessionRepository):
|
||||||
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
def __init__(self, db: AsyncIOMotorDatabase) -> None:
|
||||||
self._col = db.agent_sessions
|
self._col = db.agent_sessions
|
||||||
@@ -39,6 +48,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
"title": session.title,
|
"title": session.title,
|
||||||
"status": session.status.value,
|
"status": session.status.value,
|
||||||
"summary": session.summary,
|
"summary": session.summary,
|
||||||
|
"llm_provider_id": session.llm_provider_id,
|
||||||
"llm_model": session.llm_model,
|
"llm_model": session.llm_model,
|
||||||
"created_at": session.created_at,
|
"created_at": session.created_at,
|
||||||
"updated_at": session.updated_at,
|
"updated_at": session.updated_at,
|
||||||
@@ -80,6 +90,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
"title": session.title,
|
"title": session.title,
|
||||||
"status": session.status.value,
|
"status": session.status.value,
|
||||||
"summary": session.summary,
|
"summary": session.summary,
|
||||||
|
"llm_provider_id": session.llm_provider_id,
|
||||||
"llm_model": session.llm_model,
|
"llm_model": session.llm_model,
|
||||||
"updated_at": session.updated_at,
|
"updated_at": session.updated_at,
|
||||||
"last_message_at": session.last_message_at,
|
"last_message_at": session.last_message_at,
|
||||||
@@ -97,6 +108,7 @@ class MongoSessionRepository(SessionRepository):
|
|||||||
title=doc.get("title") or "新对话",
|
title=doc.get("title") or "新对话",
|
||||||
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
|
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
|
||||||
summary=doc.get("summary"),
|
summary=doc.get("summary"),
|
||||||
|
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
|
||||||
llm_model=doc.get("llm_model"),
|
llm_model=doc.get("llm_model"),
|
||||||
created_at=_dt(doc.get("created_at")),
|
created_at=_dt(doc.get("created_at")),
|
||||||
updated_at=_dt(doc.get("updated_at")),
|
updated_at=_dt(doc.get("updated_at")),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Redis 缓存租户 LLM 运行时配置(按公司+模型)。"""
|
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -16,18 +16,23 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
self._r = client
|
self._r = client
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _key(company_id: int, model: str | None) -> str:
|
def _key(company_id: int, provider_id: int | None, model: str | None) -> str:
|
||||||
|
if provider_id is not None and model:
|
||||||
|
return f"agent:llm:rt:{company_id}:{provider_id}:{model}"
|
||||||
if model:
|
if model:
|
||||||
return f"agent:llm:rt:{company_id}:{model}"
|
return f"agent:llm:rt:{company_id}:{model}"
|
||||||
return f"agent:llm:rt:{company_id}"
|
return f"agent:llm:rt:{company_id}"
|
||||||
|
|
||||||
async def get(
|
async def get(
|
||||||
self, company_id: int, model: str | None = None
|
self,
|
||||||
|
company_id: int,
|
||||||
|
provider_id: int | None = None,
|
||||||
|
model: str | None = None,
|
||||||
) -> LlmRuntimeConfig | None:
|
) -> LlmRuntimeConfig | None:
|
||||||
raw = await self._r.get(self._key(company_id, model))
|
raw = await self._r.get(self._key(company_id, provider_id, model))
|
||||||
if not raw and model:
|
if not raw and provider_id is not None and model:
|
||||||
# 兼容旧缓存键(仅 companyId)
|
# 兼容旧键 companyId:model
|
||||||
raw = await self._r.get(self._key(company_id, None))
|
raw = await self._r.get(self._key(company_id, None, model))
|
||||||
if not raw:
|
if not raw:
|
||||||
return None
|
return None
|
||||||
data = json.loads(raw)
|
data = json.loads(raw)
|
||||||
@@ -35,11 +40,14 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
base_url=data["base_url"],
|
base_url=data["base_url"],
|
||||||
api_key=data["api_key"],
|
api_key=data["api_key"],
|
||||||
model=data["model"],
|
model=data["model"],
|
||||||
|
provider_id=_optional_int(data.get("provider_id")) or provider_id,
|
||||||
extra_headers=data.get("extra_headers") or {},
|
extra_headers=data.get("extra_headers") or {},
|
||||||
context_window=_optional_int(data.get("context_window")),
|
context_window=_optional_int(data.get("context_window")),
|
||||||
)
|
)
|
||||||
if model and cfg.model and cfg.model != model:
|
if model and cfg.model and cfg.model != model:
|
||||||
return None
|
return None
|
||||||
|
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
|
||||||
|
return None
|
||||||
return cfg
|
return cfg
|
||||||
|
|
||||||
async def set(
|
async def set(
|
||||||
@@ -47,10 +55,9 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
company_id: int,
|
company_id: int,
|
||||||
config: LlmRuntimeConfig,
|
config: LlmRuntimeConfig,
|
||||||
ttl_seconds: int,
|
ttl_seconds: int,
|
||||||
model: str | None = None,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
key_model = model or config.model
|
|
||||||
payload = {
|
payload = {
|
||||||
|
"provider_id": config.provider_id,
|
||||||
"base_url": config.base_url,
|
"base_url": config.base_url,
|
||||||
"api_key": config.api_key,
|
"api_key": config.api_key,
|
||||||
"model": config.model,
|
"model": config.model,
|
||||||
@@ -58,15 +65,12 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
|||||||
"context_window": config.context_window,
|
"context_window": config.context_window,
|
||||||
}
|
}
|
||||||
await self._r.set(
|
await self._r.set(
|
||||||
self._key(company_id, key_model),
|
self._key(company_id, config.provider_id, config.model),
|
||||||
json.dumps(payload),
|
json.dumps(payload),
|
||||||
ex=ttl_seconds,
|
ex=ttl_seconds,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def delete(self, company_id: int, model: str | None = None) -> None:
|
async def delete(self, company_id: int) -> None:
|
||||||
if model:
|
|
||||||
await self._r.delete(self._key(company_id, model))
|
|
||||||
return
|
|
||||||
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
|
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
|
||||||
if keys:
|
if keys:
|
||||||
await self._r.delete(*keys)
|
await self._r.delete(*keys)
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
-- ========================================
|
-- ========================================
|
||||||
-- Agent:公司 LLM 提供商凭证 + 已启用模型
|
-- Agent:公司 LLM 多提供商凭证 + 已启用模型
|
||||||
-- 迁移:V20260920b__agent_llm_provider_models.sql
|
-- 迁移:V20260920b(初建)/ V20260920d(多提供商)
|
||||||
-- 旧表 agent_company_llm_settings → agent_company_llm_settings_deprecated
|
|
||||||
-- ========================================
|
-- ========================================
|
||||||
-- 约定:
|
-- 约定:
|
||||||
-- 1) 公司一套 base_url + api_key(provider 表 UNIQUE company_id)
|
-- 1) 公司可有多个 provider(各一套 base_url + api_key)
|
||||||
-- 2) 多个已启用模型;同公司一条 is_default=1 供 Agent 注入
|
-- 2) 模型挂 provider_id;UNIQUE(provider_id, model) → 跨提供商允许同名
|
||||||
-- 3) Agent Redis agent:llm:rt:{companyId} 缓存默认模型明文
|
-- 3) 公司级全局至多一条 is_default=1
|
||||||
|
-- 4) Agent Redis agent:llm:rt:{companyId}:{providerId}:{model}
|
||||||
-- ========================================
|
-- ========================================
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
||||||
@@ -22,23 +22,26 @@ CREATE TABLE IF NOT EXISTS `agent_company_llm_provider` (
|
|||||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `uk_agent_llm_provider_company` (`company_id`),
|
KEY `idx_agent_llm_provider_company` (`company_id`),
|
||||||
CONSTRAINT `fk_agent_llm_provider_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
CONSTRAINT `fk_agent_llm_provider_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent LLM 提供商凭证';
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司 Agent LLM 提供商凭证';
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS `agent_company_llm_model` (
|
CREATE TABLE IF NOT EXISTS `agent_company_llm_model` (
|
||||||
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
`company_id` bigint UNSIGNED NOT NULL COMMENT '公司ID',
|
||||||
|
`provider_id` bigint UNSIGNED NOT NULL COMMENT '提供商ID',
|
||||||
`model` varchar(200) NOT NULL COMMENT '提供商模型 id',
|
`model` varchar(200) NOT NULL COMMENT '提供商模型 id',
|
||||||
`label` varchar(200) NULL COMMENT '展示名',
|
`label` varchar(200) NULL COMMENT '展示名',
|
||||||
`context_window` int UNSIGNED NULL COMMENT '上下文窗口 token,空则 Agent 估计',
|
`context_window` int UNSIGNED NULL COMMENT '上下文窗口 token,空则 Agent 估计',
|
||||||
`is_default` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否默认聊天模型',
|
`is_default` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否公司默认聊天模型(全局唯一)',
|
||||||
`create_by` bigint UNSIGNED NULL,
|
`create_by` bigint UNSIGNED NULL,
|
||||||
`update_by` bigint UNSIGNED NULL,
|
`update_by` bigint UNSIGNED NULL,
|
||||||
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (`id`),
|
PRIMARY KEY (`id`),
|
||||||
UNIQUE KEY `uk_agent_llm_model_company_model` (`company_id`, `model`),
|
UNIQUE KEY `uk_agent_llm_model_provider_model` (`provider_id`, `model`),
|
||||||
KEY `idx_agent_llm_model_company_default` (`company_id`, `is_default`),
|
KEY `idx_agent_llm_model_company_default` (`company_id`, `is_default`),
|
||||||
CONSTRAINT `fk_agent_llm_model_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE
|
KEY `idx_agent_llm_model_provider` (`provider_id`),
|
||||||
|
CONSTRAINT `fk_agent_llm_model_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT `fk_agent_llm_model_provider` FOREIGN KEY (`provider_id`) REFERENCES `agent_company_llm_provider` (`id`) ON DELETE CASCADE
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司已启用的 LLM 模型';
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='公司已启用的 LLM 模型';
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- 多提供商:去掉公司唯一 provider;model 归属 provider_id;允许跨提供商同名 model
|
||||||
|
|
||||||
|
ALTER TABLE `agent_company_llm_model`
|
||||||
|
ADD COLUMN `provider_id` bigint UNSIGNED NULL COMMENT '提供商ID' AFTER `company_id`;
|
||||||
|
|
||||||
|
UPDATE `agent_company_llm_model` m
|
||||||
|
INNER JOIN `agent_company_llm_provider` p ON p.company_id = m.company_id
|
||||||
|
SET m.provider_id = p.id
|
||||||
|
WHERE m.provider_id IS NULL;
|
||||||
|
|
||||||
|
DELETE FROM `agent_company_llm_model` WHERE `provider_id` IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE `agent_company_llm_model`
|
||||||
|
MODIFY COLUMN `provider_id` bigint UNSIGNED NOT NULL COMMENT '提供商ID';
|
||||||
|
|
||||||
|
ALTER TABLE `agent_company_llm_model`
|
||||||
|
DROP INDEX `uk_agent_llm_model_company_model`,
|
||||||
|
ADD UNIQUE KEY `uk_agent_llm_model_provider_model` (`provider_id`, `model`),
|
||||||
|
ADD KEY `idx_agent_llm_model_provider` (`provider_id`),
|
||||||
|
ADD CONSTRAINT `fk_agent_llm_model_provider`
|
||||||
|
FOREIGN KEY (`provider_id`) REFERENCES `agent_company_llm_provider` (`id`) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE `agent_company_llm_provider`
|
||||||
|
DROP INDEX `uk_agent_llm_provider_company`,
|
||||||
|
ADD KEY `idx_agent_llm_provider_company` (`company_id`);
|
||||||
+45
-11
@@ -2,7 +2,9 @@ package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
|||||||
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
@@ -10,15 +12,18 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
|||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
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.AgentLlmProbeModelsResultVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderListVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公司模型 API 配置(浏览器 JWT)。
|
* 公司多提供商模型 API(浏览器 JWT)。
|
||||||
*/
|
*/
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/company")
|
@RequestMapping("/api/company")
|
||||||
@@ -27,16 +32,45 @@ public class AgentCompanyLlmSettingsController {
|
|||||||
|
|
||||||
private final AgentCompanyLlmSettingsService settingsService;
|
private final AgentCompanyLlmSettingsService settingsService;
|
||||||
|
|
||||||
@GetMapping("/agent-llm-settings")
|
@GetMapping("/agent-llm-providers")
|
||||||
@RequirePermission(value = "agent:llm-settings", description = "查看模型配置", allowSuper = true)
|
@RequirePermission(value = "agent:llm-settings", description = "查看模型提供商", allowSuper = true)
|
||||||
public ApiResponse<AgentLlmSettingsVO> get() {
|
public ApiResponse<AgentLlmProviderListVO> listProviders() {
|
||||||
return ApiResponse.success(settingsService.getForCurrentCompany());
|
return ApiResponse.success(settingsService.listProvidersForCurrentCompany());
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/agent-llm-settings")
|
@GetMapping("/agent-llm-providers/{id}")
|
||||||
@RequirePermission(value = "agent:llm-settings", description = "更新模型配置", allowSuper = true)
|
@RequirePermission(value = "agent:llm-settings", description = "查看模型提供商", allowSuper = true)
|
||||||
public ApiResponse<AgentLlmSettingsVO> upsert(@Valid @RequestBody UpsertAgentLlmSettingsDTO dto) {
|
public ApiResponse<AgentLlmProviderVO> getProvider(@PathVariable("id") Long id) {
|
||||||
return ApiResponse.success("保存成功", settingsService.upsertForCurrentCompany(dto));
|
return ApiResponse.success(settingsService.getProviderForCurrentCompany(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/agent-llm-providers")
|
||||||
|
@RequirePermission(value = "agent:llm-settings", description = "创建模型提供商", allowSuper = true)
|
||||||
|
public ApiResponse<AgentLlmProviderVO> createProvider(@Valid @RequestBody CreateAgentLlmProviderDTO dto) {
|
||||||
|
return ApiResponse.success("创建成功", settingsService.createProvider(dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/agent-llm-providers/{id}")
|
||||||
|
@RequirePermission(value = "agent:llm-settings", description = "更新模型提供商", allowSuper = true)
|
||||||
|
public ApiResponse<AgentLlmProviderVO> updateProvider(
|
||||||
|
@PathVariable("id") Long id,
|
||||||
|
@RequestBody UpdateAgentLlmProviderDTO dto) {
|
||||||
|
return ApiResponse.success("保存成功", settingsService.updateProvider(id, dto));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/agent-llm-providers/{id}")
|
||||||
|
@RequirePermission(value = "agent:llm-settings", description = "删除模型提供商", allowSuper = true)
|
||||||
|
public ApiResponse<Void> deleteProvider(@PathVariable("id") Long id) {
|
||||||
|
settingsService.deleteProvider(id);
|
||||||
|
return ApiResponse.success("删除成功", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/agent-llm-providers/{id}/models")
|
||||||
|
@RequirePermission(value = "agent:llm-settings", description = "更新启用模型", allowSuper = true)
|
||||||
|
public ApiResponse<AgentLlmProviderVO> upsertModels(
|
||||||
|
@PathVariable("id") Long id,
|
||||||
|
@Valid @RequestBody UpsertAgentLlmProviderModelsDTO dto) {
|
||||||
|
return ApiResponse.success("保存成功", settingsService.upsertProviderModels(id, dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/agent-llm-settings/probe-models")
|
@PostMapping("/agent-llm-settings/probe-models")
|
||||||
|
|||||||
+2
-1
@@ -30,13 +30,14 @@ public class AgentInternalLlmController {
|
|||||||
@GetMapping("/llm-runtime")
|
@GetMapping("/llm-runtime")
|
||||||
public ApiResponse<AgentLlmRuntimeVO> runtime(
|
public ApiResponse<AgentLlmRuntimeVO> runtime(
|
||||||
@RequestParam("companyId") Long companyId,
|
@RequestParam("companyId") Long companyId,
|
||||||
|
@RequestParam(value = "providerId", required = false) Long providerId,
|
||||||
@RequestParam(value = "model", required = false) String model,
|
@RequestParam(value = "model", required = false) String model,
|
||||||
HttpServletRequest request) {
|
HttpServletRequest request) {
|
||||||
assertAgentBearer(request);
|
assertAgentBearer(request);
|
||||||
if (companyId == null) {
|
if (companyId == null) {
|
||||||
throw new BusinessException("companyId 不能为空");
|
throw new BusinessException("companyId 不能为空");
|
||||||
}
|
}
|
||||||
return ApiResponse.success(settingsService.getRuntime(companyId, model));
|
return ApiResponse.success(settingsService.getRuntime(companyId, providerId, model));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void assertAgentBearer(HttpServletRequest request) {
|
private void assertAgentBearer(HttpServletRequest request) {
|
||||||
|
|||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建提供商。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CreateAgentLlmProviderDTO {
|
||||||
|
|
||||||
|
@NotBlank(message = "baseUrl 不能为空")
|
||||||
|
private String baseUrl;
|
||||||
|
|
||||||
|
@NotBlank(message = "apiKey 不能为空")
|
||||||
|
private String apiKey;
|
||||||
|
|
||||||
|
private String displayName;
|
||||||
|
}
|
||||||
+5
-3
@@ -8,15 +8,17 @@ import lombok.Data;
|
|||||||
@Data
|
@Data
|
||||||
public class ProbeAgentLlmModelsDTO {
|
public class ProbeAgentLlmModelsDTO {
|
||||||
|
|
||||||
/** 必填;探测用的 Base URL */
|
/** 探测用的 Base URL;useStoredKey 且传 providerId 时可空(用库中 URL) */
|
||||||
private String baseUrl;
|
private String baseUrl;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 临时 Key;与 useStoredKey 二选一。
|
* 临时 Key;与 useStoredKey 二选一。
|
||||||
* 留空且 useStoredKey=true 时用库中密钥。
|
|
||||||
*/
|
*/
|
||||||
private String apiKey;
|
private String apiKey;
|
||||||
|
|
||||||
/** 为 true 时使用已保存的 apiKey(须已配置) */
|
/** 为 true 时使用已保存的 apiKey(须指定 providerId) */
|
||||||
private Boolean useStoredKey;
|
private Boolean useStoredKey;
|
||||||
|
|
||||||
|
/** 使用已存密钥时指定提供商 */
|
||||||
|
private Long providerId;
|
||||||
}
|
}
|
||||||
|
|||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新提供商凭证(apiKey 留空则不改)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class UpdateAgentLlmProviderDTO {
|
||||||
|
|
||||||
|
/** 非空则更新 Base URL */
|
||||||
|
private String baseUrl;
|
||||||
|
|
||||||
|
/** 非空且非掩码则更新 Key */
|
||||||
|
private String apiKey;
|
||||||
|
|
||||||
|
/** 传 null 表示不改;传空串可清空备注 */
|
||||||
|
private String displayName;
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 某提供商下启用模型列表(增量 upsert,按 model 字符串匹配)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class UpsertAgentLlmProviderModelsDTO {
|
||||||
|
|
||||||
|
@NotEmpty(message = "至少启用一个模型")
|
||||||
|
@Valid
|
||||||
|
private List<AgentLlmModelItemDTO> models;
|
||||||
|
}
|
||||||
-27
@@ -1,27 +0,0 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
|
||||||
|
|
||||||
import jakarta.validation.Valid;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
|
||||||
import jakarta.validation.constraints.NotEmpty;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新公司 LLM:凭证 + 启用模型列表(全量覆盖模型)。
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
public class UpsertAgentLlmSettingsDTO {
|
|
||||||
|
|
||||||
@NotBlank(message = "baseUrl 不能为空")
|
|
||||||
private String baseUrl;
|
|
||||||
|
|
||||||
/** 首次必填;后续留空表示不改 Key */
|
|
||||||
private String apiKey;
|
|
||||||
|
|
||||||
private String displayName;
|
|
||||||
|
|
||||||
@NotEmpty(message = "至少启用一个模型")
|
|
||||||
@Valid
|
|
||||||
private List<AgentLlmModelItemDTO> models;
|
|
||||||
}
|
|
||||||
+3
@@ -21,6 +21,9 @@ public class AgentCompanyLlmModelPO {
|
|||||||
@TableField("company_id")
|
@TableField("company_id")
|
||||||
private Long companyId;
|
private Long companyId;
|
||||||
|
|
||||||
|
@TableField("provider_id")
|
||||||
|
private Long providerId;
|
||||||
|
|
||||||
@TableField("model")
|
@TableField("model")
|
||||||
private String model;
|
private String model;
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -4,10 +4,12 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
|||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 已启用模型条目(对外)。
|
* 已启用模型条目(对外;含提供商消歧)。
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class AgentLlmModelVO {
|
public class AgentLlmModelVO {
|
||||||
|
private Long providerId;
|
||||||
|
private String providerDisplayName;
|
||||||
private String model;
|
private String model;
|
||||||
private String label;
|
private String label;
|
||||||
private Integer contextWindow;
|
private Integer contextWindow;
|
||||||
|
|||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司提供商列表。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class AgentLlmProviderListVO {
|
||||||
|
private List<AgentLlmProviderVO> items = new ArrayList<>();
|
||||||
|
}
|
||||||
+3
-2
@@ -6,10 +6,11 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对公司管理员可见的模型配置(Key 仅掩码)。
|
* 提供商(Key 仅掩码)+ 其下启用模型。
|
||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class AgentLlmSettingsVO {
|
public class AgentLlmProviderVO {
|
||||||
|
private Long id;
|
||||||
private boolean configured;
|
private boolean configured;
|
||||||
private String baseUrl;
|
private String baseUrl;
|
||||||
private String displayName;
|
private String displayName;
|
||||||
+1
@@ -9,6 +9,7 @@ import java.util.Map;
|
|||||||
*/
|
*/
|
||||||
@Data
|
@Data
|
||||||
public class AgentLlmRuntimeVO {
|
public class AgentLlmRuntimeVO {
|
||||||
|
private Long providerId;
|
||||||
private String baseUrl;
|
private String baseUrl;
|
||||||
private String apiKey;
|
private String apiKey;
|
||||||
private String model;
|
private String model;
|
||||||
|
|||||||
+21
-8
@@ -1,30 +1,43 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
||||||
|
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
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.AgentLlmProbeModelsResultVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderListVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公司模型 API:凭证 + 多模型勾选。
|
* 公司多提供商模型 API:凭证 CRUD + 按提供商增量 upsert 启用模型。
|
||||||
*/
|
*/
|
||||||
public interface AgentCompanyLlmSettingsService {
|
public interface AgentCompanyLlmSettingsService {
|
||||||
|
|
||||||
AgentLlmSettingsVO getForCurrentCompany();
|
AgentLlmProviderListVO listProvidersForCurrentCompany();
|
||||||
|
|
||||||
AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto);
|
AgentLlmProviderVO getProviderForCurrentCompany(Long providerId);
|
||||||
|
|
||||||
|
AgentLlmProviderVO createProvider(CreateAgentLlmProviderDTO dto);
|
||||||
|
|
||||||
|
AgentLlmProviderVO updateProvider(Long providerId, UpdateAgentLlmProviderDTO dto);
|
||||||
|
|
||||||
|
void deleteProvider(Long providerId);
|
||||||
|
|
||||||
|
/** 按 (provider_id, model) 增量 upsert,不删再建仍保留的行 */
|
||||||
|
AgentLlmProviderVO upsertProviderModels(Long providerId, UpsertAgentLlmProviderModelsDTO dto);
|
||||||
|
|
||||||
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
|
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
|
||||||
|
|
||||||
/** 聊天用:启用模型列表(无 Key) */
|
/** 聊天用:启用模型列表(无 Key,含 providerId) */
|
||||||
AgentLlmEnabledModelsVO listEnabledModelsForChat();
|
AgentLlmEnabledModelsVO listEnabledModelsForChat();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agent 内部:运行时明文。
|
* Agent 内部:运行时明文。
|
||||||
*
|
*
|
||||||
* @param model 空则默认模型;非空须在启用列表中
|
* @param providerId 与 model 同时为空 → 公司默认;仅 model 时若唯一匹配则用之,否则须带 providerId
|
||||||
|
* @param model 空则取默认(或该 provider 下默认/首个)
|
||||||
*/
|
*/
|
||||||
AgentLlmRuntimeVO getRuntime(Long companyId, String model);
|
AgentLlmRuntimeVO getRuntime(Long companyId, Long providerId, String model);
|
||||||
}
|
}
|
||||||
|
|||||||
+293
-115
@@ -1,6 +1,7 @@
|
|||||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service.impl;
|
package top.xyquan.ecomdmbbackend.modules.agent.llm.service.impl;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
import com.fasterxml.jackson.core.type.TypeReference;
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -14,16 +15,18 @@ import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
|||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmModelMapper;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmModelMapper;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmProviderMapper;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmProviderMapper;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.AgentLlmModelItemDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.AgentLlmModelItemDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmSettingsDTO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
|
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.po.AgentCompanyLlmProviderPO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
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.AgentLlmModelVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderListVO;
|
||||||
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmSettingsVO;
|
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
||||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe;
|
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe;
|
||||||
@@ -34,12 +37,15 @@ import java.time.format.DateTimeFormatter;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 公司模型 API:MySQL 存密文与启用模型;Redis 按模型缓存明文供 Agent。
|
* 公司多提供商模型 API:MySQL 存密文;Redis 按 company+provider+model 缓存明文。
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -58,101 +64,177 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
private final OpenAiCompatibleModelsProbe modelsProbe;
|
private final OpenAiCompatibleModelsProbe modelsProbe;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public AgentLlmSettingsVO getForCurrentCompany() {
|
public AgentLlmProviderListVO listProvidersForCurrentCompany() {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
return toPublicVo(findProvider(companyId), listModels(companyId));
|
AgentLlmProviderListVO vo = new AgentLlmProviderListVO();
|
||||||
|
for (AgentCompanyLlmProviderPO p : listProviders(companyId)) {
|
||||||
|
vo.getItems().add(toProviderVo(p, listModelsByProvider(companyId, p.getId())));
|
||||||
|
}
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AgentLlmProviderVO getProviderForCurrentCompany(Long providerId) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, providerId);
|
||||||
|
return toProviderVo(provider, listModelsByProvider(companyId, providerId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public AgentLlmSettingsVO upsertForCurrentCompany(UpsertAgentLlmSettingsDTO dto) {
|
public AgentLlmProviderVO createProvider(CreateAgentLlmProviderDTO dto) {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
Long userId = currentUserContext.getCurrentUserId();
|
Long userId = currentUserContext.getCurrentUserId();
|
||||||
|
|
||||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||||
List<AgentLlmModelItemDTO> modelItems = normalizeModelItems(dto.getModels());
|
String plain = dto.getApiKey().trim();
|
||||||
|
if (!StringUtils.hasText(plain) || plain.startsWith("****")) {
|
||||||
AgentCompanyLlmProviderPO existing = findProvider(companyId);
|
throw new BusinessException("创建提供商必须填写有效 apiKey");
|
||||||
String encrypted;
|
|
||||||
String suffix;
|
|
||||||
String apiKey = dto.getApiKey();
|
|
||||||
if (StringUtils.hasText(apiKey) && !apiKey.trim().startsWith("****")) {
|
|
||||||
String plain = apiKey.trim();
|
|
||||||
encrypted = crypto.encrypt(plain);
|
|
||||||
suffix = plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain;
|
|
||||||
} else if (existing != null) {
|
|
||||||
encrypted = existing.getApiKeyEncrypted();
|
|
||||||
suffix = existing.getApiKeySuffix();
|
|
||||||
} else {
|
|
||||||
throw new BusinessException("首次配置必须提供 apiKey");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existing == null) {
|
AgentCompanyLlmProviderPO po = new AgentCompanyLlmProviderPO();
|
||||||
AgentCompanyLlmProviderPO po = new AgentCompanyLlmProviderPO();
|
po.setCompanyId(companyId);
|
||||||
po.setCompanyId(companyId);
|
po.setBaseUrl(baseUrl);
|
||||||
po.setBaseUrl(baseUrl);
|
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||||
po.setApiKeyEncrypted(encrypted);
|
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||||
po.setApiKeySuffix(suffix);
|
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
po.setCreateBy(userId);
|
||||||
po.setCreateBy(userId);
|
po.setUpdateBy(userId);
|
||||||
po.setUpdateBy(userId);
|
providerMapper.insert(po);
|
||||||
providerMapper.insert(po);
|
|
||||||
existing = po;
|
|
||||||
} else {
|
|
||||||
existing.setBaseUrl(baseUrl);
|
|
||||||
existing.setApiKeyEncrypted(encrypted);
|
|
||||||
existing.setApiKeySuffix(suffix);
|
|
||||||
if (dto.getDisplayName() != null) {
|
|
||||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
|
||||||
}
|
|
||||||
existing.setUpdateBy(userId);
|
|
||||||
providerMapper.updateById(existing);
|
|
||||||
}
|
|
||||||
|
|
||||||
modelMapper.delete(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
|
||||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId));
|
|
||||||
for (AgentLlmModelItemDTO item : modelItems) {
|
|
||||||
AgentCompanyLlmModelPO m = new AgentCompanyLlmModelPO();
|
|
||||||
m.setCompanyId(companyId);
|
|
||||||
m.setModel(item.getModel().trim());
|
|
||||||
m.setLabel(trimToNull(item.getLabel()));
|
|
||||||
m.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
|
||||||
m.setIsDefault(Boolean.TRUE.equals(item.getIsDefault()));
|
|
||||||
m.setCreateBy(userId);
|
|
||||||
m.setUpdateBy(userId);
|
|
||||||
modelMapper.insert(m);
|
|
||||||
}
|
|
||||||
|
|
||||||
List<AgentCompanyLlmModelPO> savedModels = listModels(companyId);
|
|
||||||
evictRuntimeCache(companyId);
|
evictRuntimeCache(companyId);
|
||||||
try {
|
return toProviderVo(po, List.of());
|
||||||
for (AgentCompanyLlmModelPO m : savedModels) {
|
}
|
||||||
cacheRuntime(companyId, buildRuntimeForModel(existing, m));
|
|
||||||
}
|
@Override
|
||||||
} catch (Exception e) {
|
@Transactional(rollbackFor = Exception.class)
|
||||||
log.warn("预热 LLM 运行时缓存失败 companyId={}", companyId, e);
|
public AgentLlmProviderVO updateProvider(Long providerId, UpdateAgentLlmProviderDTO dto) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
Long userId = currentUserContext.getCurrentUserId();
|
||||||
|
AgentCompanyLlmProviderPO existing = requireOwnedProvider(companyId, providerId);
|
||||||
|
|
||||||
|
if (StringUtils.hasText(dto.getBaseUrl())) {
|
||||||
|
existing.setBaseUrl(dto.getBaseUrl().trim().replaceAll("/+$", ""));
|
||||||
}
|
}
|
||||||
return toPublicVo(existing, savedModels);
|
if (StringUtils.hasText(dto.getApiKey()) && !dto.getApiKey().trim().startsWith("****")) {
|
||||||
|
String plain = dto.getApiKey().trim();
|
||||||
|
existing.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||||
|
existing.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||||
|
}
|
||||||
|
if (dto.getDisplayName() != null) {
|
||||||
|
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||||
|
}
|
||||||
|
existing.setUpdateBy(userId);
|
||||||
|
providerMapper.updateById(existing);
|
||||||
|
evictRuntimeCache(companyId);
|
||||||
|
warmCacheForProvider(existing);
|
||||||
|
return toProviderVo(existing, listModelsByProvider(companyId, providerId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void deleteProvider(Long providerId) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
requireOwnedProvider(companyId, providerId);
|
||||||
|
boolean hadDefault = listModelsByProvider(companyId, providerId).stream()
|
||||||
|
.anyMatch(m -> Boolean.TRUE.equals(m.getIsDefault()));
|
||||||
|
// 模型 FK CASCADE
|
||||||
|
providerMapper.deleteById(providerId);
|
||||||
|
if (hadDefault) {
|
||||||
|
ensureCompanyHasDefault(companyId, currentUserContext.getCurrentUserId());
|
||||||
|
}
|
||||||
|
evictRuntimeCache(companyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public AgentLlmProviderVO upsertProviderModels(Long providerId, UpsertAgentLlmProviderModelsDTO dto) {
|
||||||
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
Long userId = currentUserContext.getCurrentUserId();
|
||||||
|
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, providerId);
|
||||||
|
|
||||||
|
List<AgentLlmModelItemDTO> items = normalizeModelItemsForProvider(dto.getModels());
|
||||||
|
Map<String, AgentCompanyLlmModelPO> existingByModel = listModelsByProvider(companyId, providerId)
|
||||||
|
.stream()
|
||||||
|
.collect(Collectors.toMap(AgentCompanyLlmModelPO::getModel, m -> m, (a, b) -> a, LinkedHashMap::new));
|
||||||
|
|
||||||
|
Set<String> keep = new HashSet<>();
|
||||||
|
boolean requestSetsDefault = items.stream().anyMatch(i -> Boolean.TRUE.equals(i.getIsDefault()));
|
||||||
|
Long newDefaultModelRowId = null;
|
||||||
|
|
||||||
|
for (AgentLlmModelItemDTO item : items) {
|
||||||
|
String modelId = item.getModel().trim();
|
||||||
|
keep.add(modelId);
|
||||||
|
AgentCompanyLlmModelPO row = existingByModel.get(modelId);
|
||||||
|
if (row == null) {
|
||||||
|
row = new AgentCompanyLlmModelPO();
|
||||||
|
row.setCompanyId(companyId);
|
||||||
|
row.setProviderId(providerId);
|
||||||
|
row.setModel(modelId);
|
||||||
|
row.setLabel(trimToNull(item.getLabel()));
|
||||||
|
row.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||||
|
row.setIsDefault(false);
|
||||||
|
row.setCreateBy(userId);
|
||||||
|
row.setUpdateBy(userId);
|
||||||
|
modelMapper.insert(row);
|
||||||
|
} else {
|
||||||
|
row.setLabel(trimToNull(item.getLabel()));
|
||||||
|
row.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||||
|
row.setUpdateBy(userId);
|
||||||
|
modelMapper.updateById(row);
|
||||||
|
}
|
||||||
|
if (Boolean.TRUE.equals(item.getIsDefault())) {
|
||||||
|
newDefaultModelRowId = row.getId();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (AgentCompanyLlmModelPO old : existingByModel.values()) {
|
||||||
|
if (!keep.contains(old.getModel())) {
|
||||||
|
modelMapper.deleteById(old.getId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestSetsDefault && newDefaultModelRowId != null) {
|
||||||
|
clearCompanyDefaults(companyId);
|
||||||
|
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||||
|
.eq(AgentCompanyLlmModelPO::getId, newDefaultModelRowId)
|
||||||
|
.set(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||||
|
.set(AgentCompanyLlmModelPO::getUpdateBy, userId));
|
||||||
|
} else {
|
||||||
|
ensureCompanyHasDefault(companyId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<AgentCompanyLlmModelPO> saved = listModelsByProvider(companyId, providerId);
|
||||||
|
evictRuntimeCache(companyId);
|
||||||
|
warmCacheForProvider(provider);
|
||||||
|
return toProviderVo(provider, saved);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) {
|
public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
if (dto == null || !StringUtils.hasText(dto.getBaseUrl())) {
|
if (dto == null) {
|
||||||
throw new BusinessException("baseUrl 不能为空");
|
throw new BusinessException("请求体不能为空");
|
||||||
}
|
}
|
||||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
|
||||||
|
String baseUrl;
|
||||||
String apiKey;
|
String apiKey;
|
||||||
if (Boolean.TRUE.equals(dto.getUseStoredKey())) {
|
if (Boolean.TRUE.equals(dto.getUseStoredKey())) {
|
||||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
if (dto.getProviderId() == null) {
|
||||||
if (provider == null) {
|
throw new BusinessException("使用已存密钥时须指定 providerId");
|
||||||
throw new BusinessException("尚未保存 API Key,请先填写密钥或关闭「使用已存密钥」");
|
|
||||||
}
|
}
|
||||||
|
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, dto.getProviderId());
|
||||||
|
baseUrl = StringUtils.hasText(dto.getBaseUrl())
|
||||||
|
? dto.getBaseUrl().trim().replaceAll("/+$", "")
|
||||||
|
: provider.getBaseUrl();
|
||||||
apiKey = crypto.decrypt(provider.getApiKeyEncrypted());
|
apiKey = crypto.decrypt(provider.getApiKeyEncrypted());
|
||||||
} else if (StringUtils.hasText(dto.getApiKey()) && !dto.getApiKey().trim().startsWith("****")) {
|
|
||||||
apiKey = dto.getApiKey().trim();
|
|
||||||
} else {
|
} else {
|
||||||
throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥");
|
if (!StringUtils.hasText(dto.getBaseUrl())) {
|
||||||
|
throw new BusinessException("baseUrl 不能为空");
|
||||||
|
}
|
||||||
|
baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||||
|
if (!StringUtils.hasText(dto.getApiKey()) || dto.getApiKey().trim().startsWith("****")) {
|
||||||
|
throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥");
|
||||||
|
}
|
||||||
|
apiKey = dto.getApiKey().trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO();
|
AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO();
|
||||||
@@ -163,44 +245,34 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
@Override
|
@Override
|
||||||
public AgentLlmEnabledModelsVO listEnabledModelsForChat() {
|
public AgentLlmEnabledModelsVO listEnabledModelsForChat() {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
|
Map<Long, AgentCompanyLlmProviderPO> providers = listProviders(companyId).stream()
|
||||||
|
.collect(Collectors.toMap(AgentCompanyLlmProviderPO::getId, p -> p));
|
||||||
AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO();
|
AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO();
|
||||||
List<AgentLlmModelVO> items = new ArrayList<>();
|
List<AgentLlmModelVO> items = new ArrayList<>();
|
||||||
for (AgentCompanyLlmModelPO m : listModels(companyId)) {
|
for (AgentCompanyLlmModelPO m : listModels(companyId)) {
|
||||||
items.add(toModelVo(m));
|
items.add(toModelVo(m, providers.get(m.getProviderId())));
|
||||||
}
|
}
|
||||||
vo.setItems(items);
|
vo.setItems(items);
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public AgentLlmRuntimeVO getRuntime(Long companyId, String model) {
|
public AgentLlmRuntimeVO getRuntime(Long companyId, Long providerId, String model) {
|
||||||
if (companyId == null) {
|
if (companyId == null) {
|
||||||
throw new BusinessException("companyId 不能为空");
|
throw new BusinessException("companyId 不能为空");
|
||||||
}
|
}
|
||||||
AgentCompanyLlmProviderPO provider = findProvider(companyId);
|
|
||||||
if (provider == null) {
|
|
||||||
throw new BusinessException("公司尚未配置模型 API");
|
|
||||||
}
|
|
||||||
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
List<AgentCompanyLlmModelPO> models = listModels(companyId);
|
||||||
if (models.isEmpty()) {
|
if (models.isEmpty()) {
|
||||||
throw new BusinessException("公司尚未启用任何模型");
|
throw new BusinessException("公司尚未启用任何模型");
|
||||||
}
|
}
|
||||||
|
|
||||||
AgentCompanyLlmModelPO selected;
|
AgentCompanyLlmModelPO selected = resolveModelRow(models, providerId, model);
|
||||||
if (StringUtils.hasText(model)) {
|
AgentCompanyLlmProviderPO provider = providerMapper.selectById(selected.getProviderId());
|
||||||
String want = model.trim();
|
if (provider == null || !Objects.equals(provider.getCompanyId(), companyId)) {
|
||||||
selected = models.stream()
|
throw new BusinessException("提供商不存在");
|
||||||
.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());
|
AgentLlmRuntimeVO cached = readRuntimeCache(companyId, provider.getId(), selected.getModel());
|
||||||
if (cached != null) {
|
if (cached != null) {
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
@@ -209,7 +281,49 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
return runtime;
|
return runtime;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<AgentLlmModelItemDTO> normalizeModelItems(List<AgentLlmModelItemDTO> raw) {
|
private AgentCompanyLlmModelPO resolveModelRow(
|
||||||
|
List<AgentCompanyLlmModelPO> models, Long providerId, String model) {
|
||||||
|
boolean hasModel = StringUtils.hasText(model);
|
||||||
|
String want = hasModel ? model.trim() : null;
|
||||||
|
|
||||||
|
if (providerId != null && hasModel) {
|
||||||
|
return models.stream()
|
||||||
|
.filter(m -> providerId.equals(m.getProviderId()) && want.equals(m.getModel()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new BusinessException(
|
||||||
|
"模型未启用或不存在: providerId=" + providerId + ", model=" + want));
|
||||||
|
}
|
||||||
|
if (providerId != null) {
|
||||||
|
List<AgentCompanyLlmModelPO> under = models.stream()
|
||||||
|
.filter(m -> providerId.equals(m.getProviderId()))
|
||||||
|
.toList();
|
||||||
|
if (under.isEmpty()) {
|
||||||
|
throw new BusinessException("该提供商尚未启用任何模型");
|
||||||
|
}
|
||||||
|
return under.stream()
|
||||||
|
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(under.get(0));
|
||||||
|
}
|
||||||
|
if (hasModel) {
|
||||||
|
List<AgentCompanyLlmModelPO> matched = models.stream()
|
||||||
|
.filter(m -> want.equals(m.getModel()))
|
||||||
|
.toList();
|
||||||
|
if (matched.isEmpty()) {
|
||||||
|
throw new BusinessException("模型未启用或不存在: " + want);
|
||||||
|
}
|
||||||
|
if (matched.size() > 1) {
|
||||||
|
throw new BusinessException("存在同名模型,请指定 providerId: " + want);
|
||||||
|
}
|
||||||
|
return matched.get(0);
|
||||||
|
}
|
||||||
|
return models.stream()
|
||||||
|
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(models.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AgentLlmModelItemDTO> normalizeModelItemsForProvider(List<AgentLlmModelItemDTO> raw) {
|
||||||
if (raw == null || raw.isEmpty()) {
|
if (raw == null || raw.isEmpty()) {
|
||||||
throw new BusinessException("至少启用一个模型");
|
throw new BusinessException("至少启用一个模型");
|
||||||
}
|
}
|
||||||
@@ -237,9 +351,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
if (out.isEmpty()) {
|
if (out.isEmpty()) {
|
||||||
throw new BusinessException("至少启用一个模型");
|
throw new BusinessException("至少启用一个模型");
|
||||||
}
|
}
|
||||||
if (defaultIdx < 0) {
|
if (defaultIdx >= 0) {
|
||||||
out.get(0).setIsDefault(true);
|
|
||||||
} else {
|
|
||||||
for (int i = 0; i < out.size(); i++) {
|
for (int i = 0; i < out.size(); i++) {
|
||||||
out.get(i).setIsDefault(i == defaultIdx);
|
out.get(i).setIsDefault(i == defaultIdx);
|
||||||
}
|
}
|
||||||
@@ -247,9 +359,33 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void clearCompanyDefaults(Long companyId) {
|
||||||
|
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||||
|
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||||
|
.eq(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||||
|
.set(AgentCompanyLlmModelPO::getIsDefault, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureCompanyHasDefault(Long companyId, Long userId) {
|
||||||
|
List<AgentCompanyLlmModelPO> all = listModels(companyId);
|
||||||
|
if (all.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
boolean has = all.stream().anyMatch(m -> Boolean.TRUE.equals(m.getIsDefault()));
|
||||||
|
if (has) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AgentCompanyLlmModelPO first = all.get(0);
|
||||||
|
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||||
|
.eq(AgentCompanyLlmModelPO::getId, first.getId())
|
||||||
|
.set(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||||
|
.set(AgentCompanyLlmModelPO::getUpdateBy, userId));
|
||||||
|
}
|
||||||
|
|
||||||
private AgentLlmRuntimeVO buildRuntimeForModel(
|
private AgentLlmRuntimeVO buildRuntimeForModel(
|
||||||
AgentCompanyLlmProviderPO provider, AgentCompanyLlmModelPO model) {
|
AgentCompanyLlmProviderPO provider, AgentCompanyLlmModelPO model) {
|
||||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||||
|
vo.setProviderId(provider.getId());
|
||||||
vo.setBaseUrl(provider.getBaseUrl());
|
vo.setBaseUrl(provider.getBaseUrl());
|
||||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||||
vo.setModel(model.getModel());
|
vo.setModel(model.getModel());
|
||||||
@@ -258,6 +394,17 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void warmCacheForProvider(AgentCompanyLlmProviderPO provider) {
|
||||||
|
try {
|
||||||
|
for (AgentCompanyLlmModelPO m : listModelsByProvider(provider.getCompanyId(), provider.getId())) {
|
||||||
|
cacheRuntime(provider.getCompanyId(), buildRuntimeForModel(provider, m));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("预热 LLM 运行时缓存失败 companyId={} providerId={}",
|
||||||
|
provider.getCompanyId(), provider.getId(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static Integer normalizeContextWindow(Integer raw) {
|
private static Integer normalizeContextWindow(Integer raw) {
|
||||||
if (raw == null || raw <= 0) {
|
if (raw == null || raw <= 0) {
|
||||||
return null;
|
return null;
|
||||||
@@ -285,21 +432,48 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private AgentCompanyLlmProviderPO findProvider(Long companyId) {
|
private AgentCompanyLlmProviderPO requireOwnedProvider(Long companyId, Long providerId) {
|
||||||
return providerMapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmProviderPO>()
|
if (providerId == null) {
|
||||||
|
throw new BusinessException("providerId 不能为空");
|
||||||
|
}
|
||||||
|
AgentCompanyLlmProviderPO provider = providerMapper.selectById(providerId);
|
||||||
|
if (provider == null || !Objects.equals(provider.getCompanyId(), companyId)) {
|
||||||
|
throw new BusinessException("提供商不存在");
|
||||||
|
}
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AgentCompanyLlmProviderPO> listProviders(Long companyId) {
|
||||||
|
return providerMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmProviderPO>()
|
||||||
.eq(AgentCompanyLlmProviderPO::getCompanyId, companyId)
|
.eq(AgentCompanyLlmProviderPO::getCompanyId, companyId)
|
||||||
.last("LIMIT 1"));
|
.orderByAsc(AgentCompanyLlmProviderPO::getId));
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<AgentCompanyLlmModelPO> listModels(Long companyId) {
|
private List<AgentCompanyLlmModelPO> listModels(Long companyId) {
|
||||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||||
|
.orderByAsc(AgentCompanyLlmModelPO::getProviderId)
|
||||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||||
}
|
}
|
||||||
|
|
||||||
private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m) {
|
private List<AgentCompanyLlmModelPO> listModelsByProvider(Long companyId, Long providerId) {
|
||||||
|
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||||
|
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||||
|
.eq(AgentCompanyLlmModelPO::getProviderId, providerId)
|
||||||
|
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||||
|
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m, AgentCompanyLlmProviderPO provider) {
|
||||||
AgentLlmModelVO mv = new AgentLlmModelVO();
|
AgentLlmModelVO mv = new AgentLlmModelVO();
|
||||||
|
mv.setProviderId(m.getProviderId());
|
||||||
|
if (provider != null) {
|
||||||
|
mv.setProviderDisplayName(
|
||||||
|
StringUtils.hasText(provider.getDisplayName())
|
||||||
|
? provider.getDisplayName()
|
||||||
|
: provider.getBaseUrl());
|
||||||
|
}
|
||||||
mv.setModel(m.getModel());
|
mv.setModel(m.getModel());
|
||||||
mv.setLabel(m.getLabel());
|
mv.setLabel(m.getLabel());
|
||||||
mv.setContextWindow(m.getContextWindow());
|
mv.setContextWindow(m.getContextWindow());
|
||||||
@@ -307,13 +481,10 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
return mv;
|
return mv;
|
||||||
}
|
}
|
||||||
|
|
||||||
private AgentLlmSettingsVO toPublicVo(
|
private AgentLlmProviderVO toProviderVo(
|
||||||
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
|
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
|
||||||
AgentLlmSettingsVO vo = new AgentLlmSettingsVO();
|
AgentLlmProviderVO vo = new AgentLlmProviderVO();
|
||||||
if (provider == null) {
|
vo.setId(provider.getId());
|
||||||
vo.setConfigured(false);
|
|
||||||
return vo;
|
|
||||||
}
|
|
||||||
vo.setConfigured(true);
|
vo.setConfigured(true);
|
||||||
vo.setBaseUrl(provider.getBaseUrl());
|
vo.setBaseUrl(provider.getBaseUrl());
|
||||||
vo.setDisplayName(provider.getDisplayName());
|
vo.setDisplayName(provider.getDisplayName());
|
||||||
@@ -323,19 +494,20 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
List<AgentLlmModelVO> modelVos = new ArrayList<>();
|
List<AgentLlmModelVO> modelVos = new ArrayList<>();
|
||||||
for (AgentCompanyLlmModelPO m : models) {
|
for (AgentCompanyLlmModelPO m : models) {
|
||||||
modelVos.add(toModelVo(m));
|
modelVos.add(toModelVo(m, provider));
|
||||||
}
|
}
|
||||||
vo.setModels(modelVos);
|
vo.setModels(modelVos);
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String redisKey(Long companyId, String model) {
|
private static String redisKey(Long companyId, Long providerId, String model) {
|
||||||
return "agent:llm:rt:" + companyId + ":" + model;
|
return "agent:llm:rt:" + companyId + ":" + providerId + ":" + model;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
|
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
|
||||||
try {
|
try {
|
||||||
Map<String, Object> payload = new HashMap<>();
|
Map<String, Object> payload = new HashMap<>();
|
||||||
|
payload.put("provider_id", runtime.getProviderId());
|
||||||
payload.put("base_url", runtime.getBaseUrl());
|
payload.put("base_url", runtime.getBaseUrl());
|
||||||
payload.put("api_key", runtime.getApiKey());
|
payload.put("api_key", runtime.getApiKey());
|
||||||
payload.put("model", runtime.getModel());
|
payload.put("model", runtime.getModel());
|
||||||
@@ -343,7 +515,7 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
payload.put("extra_headers",
|
payload.put("extra_headers",
|
||||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||||
stringRedisTemplate.opsForValue().set(
|
stringRedisTemplate.opsForValue().set(
|
||||||
redisKey(companyId, runtime.getModel()),
|
redisKey(companyId, runtime.getProviderId(), runtime.getModel()),
|
||||||
objectMapper.writeValueAsString(payload),
|
objectMapper.writeValueAsString(payload),
|
||||||
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
|
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -351,15 +523,21 @@ public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private AgentLlmRuntimeVO readRuntimeCache(Long companyId, String model) {
|
private AgentLlmRuntimeVO readRuntimeCache(Long companyId, Long providerId, String model) {
|
||||||
try {
|
try {
|
||||||
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, model));
|
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, providerId, model));
|
||||||
if (!StringUtils.hasText(raw)) {
|
if (!StringUtils.hasText(raw)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
Map<String, Object> map = objectMapper.readValue(raw, new TypeReference<>() {
|
Map<String, Object> map = objectMapper.readValue(raw, new TypeReference<>() {
|
||||||
});
|
});
|
||||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||||
|
Object pid = map.get("provider_id");
|
||||||
|
if (pid instanceof Number n) {
|
||||||
|
vo.setProviderId(n.longValue());
|
||||||
|
} else {
|
||||||
|
vo.setProviderId(providerId);
|
||||||
|
}
|
||||||
vo.setBaseUrl(String.valueOf(map.get("base_url")));
|
vo.setBaseUrl(String.valueOf(map.get("base_url")));
|
||||||
vo.setApiKey(String.valueOf(map.get("api_key")));
|
vo.setApiKey(String.valueOf(map.get("api_key")));
|
||||||
vo.setModel(String.valueOf(map.get("model")));
|
vo.setModel(String.valueOf(map.get("model")));
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export namespace AgentVO {
|
|||||||
threadId: string;
|
threadId: string;
|
||||||
title: string;
|
title: string;
|
||||||
status: string;
|
status: string;
|
||||||
|
llmProviderId?: number | null;
|
||||||
llmModel?: string | null;
|
llmModel?: string | null;
|
||||||
createdAt?: string;
|
createdAt?: string;
|
||||||
updatedAt?: string;
|
updatedAt?: string;
|
||||||
@@ -24,20 +25,22 @@ export namespace AgentVO {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface LlmModelItem {
|
export interface LlmModelItem {
|
||||||
|
providerId: number;
|
||||||
|
providerDisplayName?: string | null;
|
||||||
model: string;
|
model: string;
|
||||||
label?: string | null;
|
label?: string | null;
|
||||||
contextWindow?: number | null;
|
contextWindow?: number | null;
|
||||||
isDefault?: boolean;
|
isDefault?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LlmSettings {
|
export interface LlmProvider {
|
||||||
|
id: number;
|
||||||
configured: boolean;
|
configured: boolean;
|
||||||
baseUrl?: string | null;
|
baseUrl?: string | null;
|
||||||
displayName?: string | null;
|
displayName?: string | null;
|
||||||
apiKeyMasked?: string | null;
|
apiKeyMasked?: string | null;
|
||||||
models?: LlmModelItem[];
|
models?: LlmModelItem[];
|
||||||
updateTime?: string;
|
updateTime?: string;
|
||||||
updatedAt?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProbedLlmModel {
|
export interface ProbedLlmModel {
|
||||||
@@ -54,23 +57,26 @@ export namespace AgentVO {
|
|||||||
updatedAt?: string;
|
updatedAt?: string;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listAgentSessionsApi() {
|
export async function listAgentSessionsApi() {
|
||||||
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions');
|
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions');
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createAgentSessionApi(options?: {
|
export async function createAgentSessionApi(options?: {
|
||||||
title?: string;
|
title?: string;
|
||||||
|
llmProviderId?: number;
|
||||||
llmModel?: string;
|
llmModel?: string;
|
||||||
}) {
|
}) {
|
||||||
return requestClient.post<AgentVO.Session>('/agent/sessions', {
|
return requestClient.post<AgentVO.Session>('/agent/sessions', {
|
||||||
title: options?.title,
|
title: options?.title,
|
||||||
|
llmProviderId: options?.llmProviderId,
|
||||||
llmModel: options?.llmModel,
|
llmModel: options?.llmModel,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function patchAgentSessionApi(
|
export async function patchAgentSessionApi(
|
||||||
threadId: string,
|
threadId: string,
|
||||||
body: { title?: string; llmModel?: string },
|
body: { title?: string; llmProviderId?: number; llmModel?: string },
|
||||||
) {
|
) {
|
||||||
return requestClient.patch<AgentVO.Session>(
|
return requestClient.patch<AgentVO.Session>(
|
||||||
`/agent/sessions/${threadId}`,
|
`/agent/sessions/${threadId}`,
|
||||||
@@ -92,26 +98,51 @@ export async function deleteAgentMemoryApi(memoryId: string) {
|
|||||||
return requestClient.delete<{ ok: boolean }>(`/agent/memories/${memoryId}`);
|
return requestClient.delete<{ ok: boolean }>(`/agent/memories/${memoryId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAgentLlmSettingsApi() {
|
export async function listAgentLlmProvidersApi() {
|
||||||
return requestClient.get<AgentVO.LlmSettings>(
|
return requestClient.get<{ items: AgentVO.LlmProvider[] }>(
|
||||||
'/company/agent-llm-settings',
|
'/company/agent-llm-providers',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateAgentLlmSettingsApi(body: {
|
export async function createAgentLlmProviderApi(body: {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
apiKey?: string;
|
apiKey: string;
|
||||||
displayName?: string;
|
displayName?: string;
|
||||||
|
}) {
|
||||||
|
return requestClient.post<AgentVO.LlmProvider>(
|
||||||
|
'/company/agent-llm-providers',
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAgentLlmProviderApi(
|
||||||
|
providerId: number,
|
||||||
|
body: { baseUrl?: string; apiKey?: string; displayName?: string },
|
||||||
|
) {
|
||||||
|
return requestClient.put<AgentVO.LlmProvider>(
|
||||||
|
`/company/agent-llm-providers/${providerId}`,
|
||||||
|
body,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteAgentLlmProviderApi(providerId: number) {
|
||||||
|
return requestClient.delete<void>(
|
||||||
|
`/company/agent-llm-providers/${providerId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function upsertAgentLlmProviderModelsApi(
|
||||||
|
providerId: number,
|
||||||
models: Array<{
|
models: Array<{
|
||||||
model: string;
|
model: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
contextWindow?: number | null;
|
contextWindow?: number | null;
|
||||||
isDefault?: boolean;
|
isDefault?: boolean;
|
||||||
}>;
|
}>,
|
||||||
}) {
|
) {
|
||||||
return requestClient.put<AgentVO.LlmSettings>(
|
return requestClient.put<AgentVO.LlmProvider>(
|
||||||
'/company/agent-llm-settings',
|
`/company/agent-llm-providers/${providerId}/models`,
|
||||||
body,
|
{ models },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,9 +155,10 @@ export async function listAgentEnabledLlmModelsApi() {
|
|||||||
|
|
||||||
/** 服务端代理 GET /v1/models,不落库 */
|
/** 服务端代理 GET /v1/models,不落库 */
|
||||||
export async function probeAgentLlmModelsApi(body: {
|
export async function probeAgentLlmModelsApi(body: {
|
||||||
baseUrl: string;
|
baseUrl?: string;
|
||||||
apiKey?: string;
|
apiKey?: string;
|
||||||
useStoredKey?: boolean;
|
useStoredKey?: boolean;
|
||||||
|
providerId?: number;
|
||||||
}) {
|
}) {
|
||||||
return requestClient.post<{ items: AgentVO.ProbedLlmModel[] }>(
|
return requestClient.post<{ items: AgentVO.ProbedLlmModel[] }>(
|
||||||
'/company/agent-llm-settings/probe-models',
|
'/company/agent-llm-settings/probe-models',
|
||||||
@@ -139,7 +171,6 @@ export function streamAgentChat(options: {
|
|||||||
threadId: string;
|
threadId: string;
|
||||||
content: string;
|
content: string;
|
||||||
onToken: (text: string) => void;
|
onToken: (text: string) => void;
|
||||||
/** 工具状态(不进正文);phase=start 显示 label,end 可清除 */
|
|
||||||
onTool?: (payload: {
|
onTool?: (payload: {
|
||||||
phase: string;
|
phase: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -230,7 +261,6 @@ export function streamAgentChat(options: {
|
|||||||
const { done, value } = await reader.read();
|
const { done, value } = await reader.read();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
buffer += decoder.decode(value, { stream: true });
|
buffer += decoder.decode(value, { stream: true });
|
||||||
// 统一换行,按 SSE 事件块拆分
|
|
||||||
buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||||
const parts = buffer.split('\n\n');
|
const parts = buffer.split('\n\n');
|
||||||
buffer = parts.pop() || '';
|
buffer = parts.pop() || '';
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
export type { AgentVO } from './apis';
|
export type { AgentVO } from './apis';
|
||||||
export {
|
export {
|
||||||
|
createAgentLlmProviderApi,
|
||||||
createAgentSessionApi,
|
createAgentSessionApi,
|
||||||
|
deleteAgentLlmProviderApi,
|
||||||
deleteAgentMemoryApi,
|
deleteAgentMemoryApi,
|
||||||
getAgentLlmSettingsApi,
|
|
||||||
listAgentEnabledLlmModelsApi,
|
listAgentEnabledLlmModelsApi,
|
||||||
|
listAgentLlmProvidersApi,
|
||||||
listAgentMemoriesApi,
|
listAgentMemoriesApi,
|
||||||
listAgentMessagesApi,
|
listAgentMessagesApi,
|
||||||
listAgentSessionsApi,
|
listAgentSessionsApi,
|
||||||
patchAgentSessionApi,
|
patchAgentSessionApi,
|
||||||
probeAgentLlmModelsApi,
|
probeAgentLlmModelsApi,
|
||||||
streamAgentChat,
|
streamAgentChat,
|
||||||
updateAgentLlmSettingsApi,
|
updateAgentLlmProviderApi,
|
||||||
|
upsertAgentLlmProviderModelsApi,
|
||||||
} from './apis';
|
} from './apis';
|
||||||
|
|||||||
@@ -62,8 +62,8 @@ const draft = ref('');
|
|||||||
/** 本条消息附带的店铺/商品/SKU,发送时写成 [引用] 块 */
|
/** 本条消息附带的店铺/商品/SKU,发送时写成 [引用] 块 */
|
||||||
const citations = ref<CatalogCite[]>([]);
|
const citations = ref<CatalogCite[]>([]);
|
||||||
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
const enabledModels = ref<AgentVO.LlmModelItem[]>([]);
|
||||||
/** 当前选中模型(有会话时与 session.llmModel 同步;草稿态本地暂存) */
|
/** 选中值:`${providerId}::${model}`;会话态与草稿共用 */
|
||||||
const selectedModel = ref<string | undefined>(undefined);
|
const selectedModelKey = ref<string | undefined>(undefined);
|
||||||
const patchingModel = ref(false);
|
const patchingModel = ref(false);
|
||||||
const messagePaneRef = ref<HTMLElement | null>(null);
|
const messagePaneRef = ref<HTMLElement | null>(null);
|
||||||
let abort: AbortController | null = null;
|
let abort: AbortController | null = null;
|
||||||
@@ -73,12 +73,38 @@ const activeSession = computed(() =>
|
|||||||
sessions.value.find((s) => s.threadId === activeThreadId.value),
|
sessions.value.find((s) => s.threadId === activeThreadId.value),
|
||||||
);
|
);
|
||||||
|
|
||||||
const modelOptions = computed(() =>
|
function modelKey(providerId: number, model: string) {
|
||||||
enabledModels.value.map((m) => ({
|
return `${providerId}::${model}`;
|
||||||
value: m.model,
|
}
|
||||||
label: m.label || m.model,
|
|
||||||
})),
|
function parseModelKey(key: string | undefined): {
|
||||||
);
|
providerId: number;
|
||||||
|
model: string;
|
||||||
|
} | null {
|
||||||
|
if (!key) return null;
|
||||||
|
const idx = key.indexOf('::');
|
||||||
|
if (idx <= 0) return null;
|
||||||
|
const providerId = Number(key.slice(0, idx));
|
||||||
|
const model = key.slice(idx + 2);
|
||||||
|
if (!Number.isFinite(providerId) || !model) return null;
|
||||||
|
return { providerId, model };
|
||||||
|
}
|
||||||
|
|
||||||
|
const modelOptions = computed(() => {
|
||||||
|
const groups = new Map<string, { label: string; options: Array<{ value: string; label: string }> }>();
|
||||||
|
for (const m of enabledModels.value) {
|
||||||
|
const gLabel = m.providerDisplayName || `提供商 #${m.providerId}`;
|
||||||
|
const gKey = String(m.providerId);
|
||||||
|
if (!groups.has(gKey)) {
|
||||||
|
groups.set(gKey, { label: gLabel, options: [] });
|
||||||
|
}
|
||||||
|
groups.get(gKey)!.options.push({
|
||||||
|
value: modelKey(m.providerId, m.model),
|
||||||
|
label: m.label || m.model,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return [...groups.values()];
|
||||||
|
});
|
||||||
|
|
||||||
const showMessageLoading = computed(
|
const showMessageLoading = computed(
|
||||||
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
||||||
@@ -127,19 +153,27 @@ function scrollChatToBottom() {
|
|||||||
el.scrollTop = el.scrollHeight;
|
el.scrollTop = el.scrollHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
function defaultModelId() {
|
function defaultModelKey() {
|
||||||
const d = enabledModels.value.find((m) => m.isDefault);
|
const d = enabledModels.value.find((m) => m.isDefault);
|
||||||
return d?.model || enabledModels.value[0]?.model;
|
const pick = d || enabledModels.value[0];
|
||||||
|
return pick ? modelKey(pick.providerId, pick.model) : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function syncSelectedFromSession() {
|
function syncSelectedFromSession() {
|
||||||
const s = activeSession.value;
|
const s = activeSession.value;
|
||||||
if (s?.llmModel) {
|
if (s?.llmProviderId != null && s.llmModel) {
|
||||||
selectedModel.value = s.llmModel;
|
selectedModelKey.value = modelKey(s.llmProviderId, s.llmModel);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!selectedModel.value) {
|
if (s?.llmModel) {
|
||||||
selectedModel.value = defaultModelId();
|
const matches = enabledModels.value.filter((m) => m.model === s.llmModel);
|
||||||
|
if (matches.length === 1) {
|
||||||
|
selectedModelKey.value = modelKey(matches[0]!.providerId, matches[0]!.model);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!selectedModelKey.value) {
|
||||||
|
selectedModelKey.value = defaultModelKey();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,8 +207,8 @@ async function loadEnabledModels() {
|
|||||||
try {
|
try {
|
||||||
const res = await listAgentEnabledLlmModelsApi();
|
const res = await listAgentEnabledLlmModelsApi();
|
||||||
enabledModels.value = res.items || [];
|
enabledModels.value = res.items || [];
|
||||||
if (!selectedModel.value) {
|
if (!selectedModelKey.value) {
|
||||||
selectedModel.value = defaultModelId();
|
selectedModelKey.value = defaultModelKey();
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
enabledModels.value = [];
|
enabledModels.value = [];
|
||||||
@@ -216,8 +250,8 @@ watch(activeThreadId, (id) => {
|
|||||||
} else {
|
} else {
|
||||||
messages.value = [];
|
messages.value = [];
|
||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
if (!selectedModel.value) {
|
if (!selectedModelKey.value) {
|
||||||
selectedModel.value = defaultModelId();
|
selectedModelKey.value = defaultModelKey();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -237,31 +271,38 @@ function beginNewChat() {
|
|||||||
streamingText.value = '';
|
streamingText.value = '';
|
||||||
draft.value = '';
|
draft.value = '';
|
||||||
citations.value = [];
|
citations.value = [];
|
||||||
selectedModel.value = defaultModelId();
|
selectedModelKey.value = defaultModelKey();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 第一条消息发出时才落库 */
|
/** 第一条消息发出时才落库 */
|
||||||
async function ensureSession(): Promise<string | null> {
|
async function ensureSession(): Promise<string | null> {
|
||||||
if (activeThreadId.value) return activeThreadId.value;
|
if (activeThreadId.value) return activeThreadId.value;
|
||||||
|
const parsed = parseModelKey(selectedModelKey.value);
|
||||||
const s = await createAgentSessionApi({
|
const s = await createAgentSessionApi({
|
||||||
llmModel: selectedModel.value,
|
llmProviderId: parsed?.providerId,
|
||||||
|
llmModel: parsed?.model,
|
||||||
});
|
});
|
||||||
composingNew.value = false;
|
composingNew.value = false;
|
||||||
sessions.value = [s, ...sessions.value];
|
sessions.value = [s, ...sessions.value];
|
||||||
activeThreadId.value = s.threadId;
|
activeThreadId.value = s.threadId;
|
||||||
if (s.llmModel) {
|
if (s.llmProviderId != null && s.llmModel) {
|
||||||
selectedModel.value = s.llmModel;
|
selectedModelKey.value = modelKey(s.llmProviderId, s.llmModel);
|
||||||
}
|
}
|
||||||
return s.threadId;
|
return s.threadId;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onModelChange(model: string) {
|
async function onModelChange(key: string) {
|
||||||
selectedModel.value = model;
|
if (!key || !key.includes('::')) return;
|
||||||
|
selectedModelKey.value = key;
|
||||||
|
const parsed = parseModelKey(key);
|
||||||
const threadId = activeThreadId.value;
|
const threadId = activeThreadId.value;
|
||||||
if (!threadId || composingNew.value) return;
|
if (!threadId || composingNew.value || !parsed) return;
|
||||||
patchingModel.value = true;
|
patchingModel.value = true;
|
||||||
try {
|
try {
|
||||||
const s = await patchAgentSessionApi(threadId, { llmModel: model });
|
const s = await patchAgentSessionApi(threadId, {
|
||||||
|
llmProviderId: parsed.providerId,
|
||||||
|
llmModel: parsed.model,
|
||||||
|
});
|
||||||
const idx = sessions.value.findIndex((x) => x.threadId === threadId);
|
const idx = sessions.value.findIndex((x) => x.threadId === threadId);
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
sessions.value[idx] = { ...sessions.value[idx]!, ...s };
|
sessions.value[idx] = { ...sessions.value[idx]!, ...s };
|
||||||
@@ -470,14 +511,14 @@ void loadEnabledModels().then(() => refreshSessions());
|
|||||||
}}
|
}}
|
||||||
</span>
|
</span>
|
||||||
<Select
|
<Select
|
||||||
:value="selectedModel"
|
:value="selectedModelKey"
|
||||||
:options="modelOptions"
|
:options="modelOptions"
|
||||||
:loading="patchingModel"
|
:loading="patchingModel"
|
||||||
:disabled="sending || modelOptions.length === 0"
|
:disabled="sending || enabledModels.length === 0"
|
||||||
placeholder="选择模型"
|
placeholder="选择模型"
|
||||||
class="w-56 shrink-0"
|
class="w-64 shrink-0"
|
||||||
:allow-clear="false"
|
:allow-clear="false"
|
||||||
@change="(v: string) => onModelChange(v)"
|
@change="(v) => onModelChange(String(v ?? ''))"
|
||||||
/>
|
/>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|||||||
@@ -11,182 +11,223 @@ import {
|
|||||||
FormItem,
|
FormItem,
|
||||||
Input,
|
Input,
|
||||||
InputPassword,
|
InputPassword,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
Radio,
|
Radio,
|
||||||
Spin,
|
Spin,
|
||||||
message,
|
message,
|
||||||
} from 'ant-design-vue';
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
getAgentLlmSettingsApi,
|
createAgentLlmProviderApi,
|
||||||
|
deleteAgentLlmProviderApi,
|
||||||
|
listAgentLlmProvidersApi,
|
||||||
probeAgentLlmModelsApi,
|
probeAgentLlmModelsApi,
|
||||||
type AgentVO,
|
type AgentVO,
|
||||||
updateAgentLlmSettingsApi,
|
updateAgentLlmProviderApi,
|
||||||
|
upsertAgentLlmProviderModelsApi,
|
||||||
} from '#/api/agent';
|
} from '#/api/agent';
|
||||||
|
|
||||||
defineOptions({ name: 'AgentLlmSettings' });
|
defineOptions({ name: 'AgentLlmSettings' });
|
||||||
|
|
||||||
const loading = ref(true);
|
|
||||||
const saving = ref(false);
|
|
||||||
const probingModels = ref(false);
|
|
||||||
const probedModels = ref<AgentVO.ProbedLlmModel[]>([]);
|
|
||||||
const manualModelId = ref('');
|
|
||||||
|
|
||||||
type EnabledModelRow = {
|
type EnabledModelRow = {
|
||||||
model: string;
|
model: string;
|
||||||
contextWindow: string;
|
contextWindow: string;
|
||||||
isDefault: boolean;
|
isDefault: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const llmForm = ref({
|
type ProviderDraft = {
|
||||||
|
id: number;
|
||||||
|
baseUrl: string;
|
||||||
|
apiKey: string;
|
||||||
|
apiKeyMasked: string | null;
|
||||||
|
displayName: string;
|
||||||
|
enabledModels: EnabledModelRow[];
|
||||||
|
probedModels: AgentVO.ProbedLlmModel[];
|
||||||
|
manualModelId: string;
|
||||||
|
probing: boolean;
|
||||||
|
savingCreds: boolean;
|
||||||
|
savingModels: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const loading = ref(true);
|
||||||
|
const providers = ref<ProviderDraft[]>([]);
|
||||||
|
const createOpen = ref(false);
|
||||||
|
const creating = ref(false);
|
||||||
|
const createForm = ref({
|
||||||
baseUrl: '',
|
baseUrl: '',
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
apiKeyMasked: '' as string | null,
|
|
||||||
configured: false,
|
|
||||||
displayName: '',
|
displayName: '',
|
||||||
});
|
});
|
||||||
const enabledModels = ref<EnabledModelRow[]>([]);
|
|
||||||
|
|
||||||
async function loadAll() {
|
function toDraft(p: AgentVO.LlmProvider): ProviderDraft {
|
||||||
loading.value = true;
|
return {
|
||||||
probedModels.value = [];
|
id: p.id,
|
||||||
manualModelId.value = '';
|
baseUrl: p.baseUrl || '',
|
||||||
try {
|
apiKey: '',
|
||||||
const s = await getAgentLlmSettingsApi();
|
apiKeyMasked: p.apiKeyMasked || null,
|
||||||
llmForm.value = {
|
displayName: p.displayName || '',
|
||||||
baseUrl: s.baseUrl || '',
|
enabledModels: (p.models || []).map((m) => ({
|
||||||
apiKey: '',
|
|
||||||
apiKeyMasked: s.apiKeyMasked || null,
|
|
||||||
configured: !!s.configured,
|
|
||||||
displayName: s.displayName || '',
|
|
||||||
};
|
|
||||||
enabledModels.value = (s.models || []).map((m) => ({
|
|
||||||
model: m.model,
|
model: m.model,
|
||||||
contextWindow:
|
contextWindow:
|
||||||
m.contextWindow != null && m.contextWindow > 0
|
m.contextWindow != null && m.contextWindow > 0
|
||||||
? String(m.contextWindow)
|
? String(m.contextWindow)
|
||||||
: '',
|
: '',
|
||||||
isDefault: !!m.isDefault,
|
isDefault: !!m.isDefault,
|
||||||
}));
|
})),
|
||||||
|
probedModels: [],
|
||||||
|
manualModelId: '',
|
||||||
|
probing: false,
|
||||||
|
savingCreds: false,
|
||||||
|
savingModels: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAll() {
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
const res = await listAgentLlmProvidersApi();
|
||||||
|
providers.value = (res.items || []).map(toDraft);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '加载模型配置失败');
|
message.error(e?.message || '加载提供商失败');
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isModelEnabled(id: string) {
|
function isModelEnabled(d: ProviderDraft, id: string) {
|
||||||
return enabledModels.value.some((m) => m.model === id);
|
return d.enabledModels.some((m) => m.model === id);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleProbedModel(p: AgentVO.ProbedLlmModel, checked: boolean) {
|
function toggleProbedModel(
|
||||||
|
d: ProviderDraft,
|
||||||
|
p: AgentVO.ProbedLlmModel,
|
||||||
|
checked: boolean,
|
||||||
|
) {
|
||||||
if (checked) {
|
if (checked) {
|
||||||
if (isModelEnabled(p.id)) return;
|
if (isModelEnabled(d, p.id)) return;
|
||||||
enabledModels.value.push({
|
d.enabledModels.push({
|
||||||
model: p.id,
|
model: p.id,
|
||||||
contextWindow:
|
contextWindow:
|
||||||
p.contextWindow != null && p.contextWindow > 0
|
p.contextWindow != null && p.contextWindow > 0
|
||||||
? String(p.contextWindow)
|
? String(p.contextWindow)
|
||||||
: '',
|
: '',
|
||||||
isDefault: enabledModels.value.length === 0,
|
isDefault: false,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
const wasDefault = enabledModels.value.find(
|
d.enabledModels = d.enabledModels.filter((m) => m.model !== p.id);
|
||||||
(m) => m.model === p.id,
|
}
|
||||||
)?.isDefault;
|
}
|
||||||
enabledModels.value = enabledModels.value.filter((m) => m.model !== p.id);
|
|
||||||
if (wasDefault && enabledModels.value.length > 0) {
|
function setDefaultModel(d: ProviderDraft, modelId: string) {
|
||||||
enabledModels.value[0]!.isDefault = true;
|
for (const draft of providers.value) {
|
||||||
|
draft.enabledModels = draft.enabledModels.map((m) => ({
|
||||||
|
...m,
|
||||||
|
isDefault: draft.id === d.id && m.model === modelId,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeEnabledModel(d: ProviderDraft, modelId: string) {
|
||||||
|
const wasDefault = d.enabledModels.find((m) => m.model === modelId)?.isDefault;
|
||||||
|
d.enabledModels = d.enabledModels.filter((m) => m.model !== modelId);
|
||||||
|
if (!wasDefault) return;
|
||||||
|
for (const draft of providers.value) {
|
||||||
|
for (const m of draft.enabledModels) {
|
||||||
|
m.isDefault = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const draft of providers.value) {
|
||||||
|
if (draft.enabledModels.length > 0) {
|
||||||
|
draft.enabledModels[0]!.isDefault = true;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function setDefaultModel(modelId: string) {
|
function addManualModel(d: ProviderDraft) {
|
||||||
enabledModels.value = enabledModels.value.map((m) => ({
|
const id = d.manualModelId.trim();
|
||||||
...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) {
|
if (!id) {
|
||||||
message.warning('请输入模型 id');
|
message.warning('请输入模型 id');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isModelEnabled(id)) {
|
if (isModelEnabled(d, id)) {
|
||||||
message.warning('该模型已在启用列表中');
|
message.warning('该模型已在启用列表中');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
enabledModels.value.push({
|
d.enabledModels.push({
|
||||||
model: id,
|
model: id,
|
||||||
contextWindow: '',
|
contextWindow: '',
|
||||||
isDefault: enabledModels.value.length === 0,
|
isDefault: false,
|
||||||
});
|
});
|
||||||
manualModelId.value = '';
|
d.manualModelId = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
async function probeModels() {
|
async function probeModels(d: ProviderDraft) {
|
||||||
if (!llmForm.value.baseUrl.trim()) {
|
if (!d.baseUrl.trim()) {
|
||||||
message.warning('请先填写 Base URL');
|
message.warning('请先填写 Base URL');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const useStored =
|
const useStored =
|
||||||
!!llmForm.value.configured &&
|
!!d.apiKeyMasked &&
|
||||||
(!llmForm.value.apiKey.trim() ||
|
(!d.apiKey.trim() || d.apiKey.trim().startsWith('****'));
|
||||||
llmForm.value.apiKey.trim().startsWith('****'));
|
if (!useStored && !d.apiKey.trim()) {
|
||||||
if (!useStored && !llmForm.value.apiKey.trim()) {
|
|
||||||
message.warning('请填写 API Key,或先保存密钥后再用已存密钥探测');
|
message.warning('请填写 API Key,或先保存密钥后再用已存密钥探测');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
probingModels.value = true;
|
d.probing = true;
|
||||||
try {
|
try {
|
||||||
const res = await probeAgentLlmModelsApi({
|
const res = await probeAgentLlmModelsApi({
|
||||||
baseUrl: llmForm.value.baseUrl.trim(),
|
baseUrl: d.baseUrl.trim(),
|
||||||
apiKey: useStored ? undefined : llmForm.value.apiKey.trim(),
|
apiKey: useStored ? undefined : d.apiKey.trim(),
|
||||||
useStoredKey: useStored,
|
useStoredKey: useStored,
|
||||||
|
providerId: useStored ? d.id : undefined,
|
||||||
});
|
});
|
||||||
probedModels.value = res.items || [];
|
d.probedModels = res.items || [];
|
||||||
if (probedModels.value.length === 0) {
|
if (d.probedModels.length === 0) {
|
||||||
message.warning('未返回模型,可手动添加模型 id');
|
message.warning('未返回模型,可手动添加模型 id');
|
||||||
} else {
|
} else {
|
||||||
message.success(`已加载 ${probedModels.value.length} 个模型`);
|
message.success(`已加载 ${d.probedModels.length} 个模型`);
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '加载模型列表失败,可改为手动添加');
|
message.error(e?.message || '加载模型列表失败');
|
||||||
} finally {
|
} finally {
|
||||||
probingModels.value = false;
|
d.probing = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveSettings() {
|
async function saveCredentials(d: ProviderDraft) {
|
||||||
if (!llmForm.value.baseUrl.trim()) {
|
if (!d.baseUrl.trim()) {
|
||||||
message.warning('请填写 Base URL');
|
message.warning('请填写 Base URL');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (enabledModels.value.length === 0) {
|
d.savingCreds = true;
|
||||||
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 {
|
try {
|
||||||
const models = enabledModels.value.map((m) => {
|
const p = await updateAgentLlmProviderApi(d.id, {
|
||||||
|
baseUrl: d.baseUrl.trim(),
|
||||||
|
apiKey: d.apiKey.trim() || undefined,
|
||||||
|
displayName: d.displayName.trim(),
|
||||||
|
});
|
||||||
|
d.apiKeyMasked = p.apiKeyMasked || null;
|
||||||
|
d.apiKey = '';
|
||||||
|
d.baseUrl = p.baseUrl || d.baseUrl;
|
||||||
|
d.displayName = p.displayName || '';
|
||||||
|
message.success('凭证已保存');
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '保存凭证失败');
|
||||||
|
} finally {
|
||||||
|
d.savingCreds = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveModels(d: ProviderDraft) {
|
||||||
|
if (d.enabledModels.length === 0) {
|
||||||
|
message.warning('请至少启用一个模型');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
d.savingModels = true;
|
||||||
|
try {
|
||||||
|
const models = d.enabledModels.map((m) => {
|
||||||
const cw = m.contextWindow.trim();
|
const cw = m.contextWindow.trim();
|
||||||
let contextWindow: number | null | undefined;
|
let contextWindow: number | null | undefined;
|
||||||
if (cw === '') {
|
if (cw === '') {
|
||||||
@@ -204,28 +245,51 @@ async function saveSettings() {
|
|||||||
isDefault: m.isDefault,
|
isDefault: m.isDefault,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
const s = await updateAgentLlmSettingsApi({
|
const p = await upsertAgentLlmProviderModelsApi(d.id, models);
|
||||||
baseUrl: llmForm.value.baseUrl.trim(),
|
// 刷新全部,保证公司级默认只剩一条
|
||||||
apiKey: llmForm.value.apiKey.trim() || undefined,
|
await loadAll();
|
||||||
displayName: llmForm.value.displayName.trim() || undefined,
|
message.success(`「${p.displayName || p.baseUrl}」模型列表已保存`);
|
||||||
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) {
|
} catch (e: any) {
|
||||||
message.error(e?.message || '保存失败');
|
message.error(e?.message || '保存模型失败');
|
||||||
} finally {
|
} finally {
|
||||||
saving.value = false;
|
d.savingModels = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeProvider(id: number) {
|
||||||
|
try {
|
||||||
|
await deleteAgentLlmProviderApi(id);
|
||||||
|
providers.value = providers.value.filter((p) => p.id !== id);
|
||||||
|
message.success('已删除提供商');
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitCreate() {
|
||||||
|
if (!createForm.value.baseUrl.trim()) {
|
||||||
|
message.warning('请填写 Base URL');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!createForm.value.apiKey.trim()) {
|
||||||
|
message.warning('请填写 API Key');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
creating.value = true;
|
||||||
|
try {
|
||||||
|
const p = await createAgentLlmProviderApi({
|
||||||
|
baseUrl: createForm.value.baseUrl.trim(),
|
||||||
|
apiKey: createForm.value.apiKey.trim(),
|
||||||
|
displayName: createForm.value.displayName.trim() || undefined,
|
||||||
|
});
|
||||||
|
providers.value.push(toDraft(p));
|
||||||
|
createOpen.value = false;
|
||||||
|
createForm.value = { baseUrl: '', apiKey: '', displayName: '' };
|
||||||
|
message.success('提供商已创建,请继续勾选启用模型');
|
||||||
|
} catch (e: any) {
|
||||||
|
message.error(e?.message || '创建失败');
|
||||||
|
} finally {
|
||||||
|
creating.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -244,98 +308,122 @@ onMounted(() => {
|
|||||||
<Spin />
|
<Spin />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card title="公司模型 API(OpenAI Compatible)" :bordered="false">
|
<div class="flex items-center justify-between gap-3">
|
||||||
<p class="text-muted-foreground mb-4 text-sm">
|
<div>
|
||||||
填写 Base URL 与 API Key 后加载模型列表并勾选启用;指定一个默认模型供新对话使用。Key
|
<div class="text-base font-medium">模型提供商</div>
|
||||||
加密落库,界面仅显示掩码。上下文窗口多数厂商不会在 API
|
<p class="text-muted-foreground mt-1 text-sm">
|
||||||
返回,有则预填,可改或留空由 Agent 估计。
|
可配置多个 OpenAI Compatible 提供商;跨提供商允许同名模型。公司全局仅一个默认模型。
|
||||||
</p>
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button type="primary" @click="createOpen = true">添加提供商</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
v-if="!loading && providers.length === 0"
|
||||||
|
class="text-muted-foreground rounded-lg border border-dashed border-border px-4 py-10 text-center text-sm"
|
||||||
|
>
|
||||||
|
尚未配置提供商,点击右上角添加。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card
|
||||||
|
v-for="d in providers"
|
||||||
|
:key="d.id"
|
||||||
|
:title="d.displayName || d.baseUrl || `提供商 #${d.id}`"
|
||||||
|
:bordered="false"
|
||||||
|
>
|
||||||
|
<template #extra>
|
||||||
|
<Popconfirm
|
||||||
|
title="删除该提供商及其启用模型?"
|
||||||
|
ok-text="删除"
|
||||||
|
cancel-text="取消"
|
||||||
|
@confirm="removeProvider(d.id)"
|
||||||
|
>
|
||||||
|
<Button type="link" danger size="small">删除</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</template>
|
||||||
|
|
||||||
<Form layout="vertical">
|
<Form layout="vertical">
|
||||||
<FormItem label="Base URL" required>
|
<FormItem label="Base URL" required>
|
||||||
<Input
|
<Input
|
||||||
v-model:value="llmForm.baseUrl"
|
v-model:value="d.baseUrl"
|
||||||
placeholder="https://api.deepseek.com/v1"
|
placeholder="https://api.deepseek.com/v1"
|
||||||
/>
|
/>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
<FormItem
|
<FormItem
|
||||||
:label="
|
:label="
|
||||||
llmForm.configured
|
d.apiKeyMasked
|
||||||
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则用已存密钥探测/不改 Key)`
|
? `API Key(已配置 ${d.apiKeyMasked},留空不改)`
|
||||||
: 'API Key'
|
: 'API Key'
|
||||||
"
|
"
|
||||||
:required="!llmForm.configured"
|
|
||||||
>
|
>
|
||||||
<InputPassword
|
<InputPassword v-model:value="d.apiKey" placeholder="sk-..." />
|
||||||
v-model:value="llmForm.apiKey"
|
|
||||||
placeholder="sk-..."
|
|
||||||
/>
|
|
||||||
</FormItem>
|
</FormItem>
|
||||||
<FormItem label="提供商备注(可选)">
|
<FormItem label="提供商备注(可选)">
|
||||||
<Input
|
<Input v-model:value="d.displayName" placeholder="如 DeepSeek" />
|
||||||
v-model:value="llmForm.displayName"
|
|
||||||
placeholder="如 DeepSeek"
|
|
||||||
/>
|
|
||||||
</FormItem>
|
</FormItem>
|
||||||
|
<Button
|
||||||
|
type="default"
|
||||||
|
class="mb-4"
|
||||||
|
:loading="d.savingCreds"
|
||||||
|
@click="saveCredentials(d)"
|
||||||
|
>
|
||||||
|
保存凭证
|
||||||
|
</Button>
|
||||||
|
|
||||||
<FormItem label="模型列表">
|
<FormItem label="模型列表">
|
||||||
<div class="mb-2 flex flex-wrap gap-2">
|
<div class="mb-2 flex flex-wrap gap-2">
|
||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
ghost
|
ghost
|
||||||
:loading="probingModels"
|
:loading="d.probing"
|
||||||
@click="probeModels"
|
@click="probeModels(d)"
|
||||||
>
|
>
|
||||||
加载模型列表
|
加载模型列表
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="probedModels.length > 0"
|
v-if="d.probedModels.length > 0"
|
||||||
class="mb-3 max-h-40 space-y-1 overflow-y-auto rounded-md border border-border p-2"
|
class="mb-3 max-h-40 space-y-1 overflow-y-auto rounded-md border border-border p-2"
|
||||||
>
|
>
|
||||||
<label
|
<label
|
||||||
v-for="p in probedModels"
|
v-for="p in d.probedModels"
|
||||||
:key="p.id"
|
:key="p.id"
|
||||||
class="flex cursor-pointer items-center gap-2 text-sm"
|
class="flex cursor-pointer items-center gap-2 text-sm"
|
||||||
>
|
>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
:checked="isModelEnabled(p.id)"
|
:checked="isModelEnabled(d, p.id)"
|
||||||
@update:checked="(v: boolean) => toggleProbedModel(p, v)"
|
@update:checked="(v: boolean) => toggleProbedModel(d, p, v)"
|
||||||
/>
|
/>
|
||||||
<span class="min-w-0 flex-1 truncate">{{ p.id }}</span>
|
<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>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="mb-2 flex gap-2">
|
<div class="mb-2 flex gap-2">
|
||||||
<Input
|
<Input
|
||||||
v-model:value="manualModelId"
|
v-model:value="d.manualModelId"
|
||||||
class="flex-1"
|
class="flex-1"
|
||||||
placeholder="手动添加模型 id,如 deepseek-chat"
|
placeholder="手动添加模型 id"
|
||||||
@press-enter="addManualModel"
|
@press-enter="addManualModel(d)"
|
||||||
/>
|
/>
|
||||||
<Button @click="addManualModel">添加</Button>
|
<Button @click="addManualModel(d)">添加</Button>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="enabledModels.length === 0"
|
v-if="d.enabledModels.length === 0"
|
||||||
class="text-muted-foreground text-xs"
|
class="text-muted-foreground text-xs"
|
||||||
>
|
>
|
||||||
尚未启用模型。请加载列表勾选,或手动添加。
|
尚未启用模型。勾选或手动添加后保存。
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="space-y-2">
|
<div v-else class="space-y-2">
|
||||||
<div
|
<div
|
||||||
v-for="m in enabledModels"
|
v-for="m in d.enabledModels"
|
||||||
:key="m.model"
|
:key="m.model"
|
||||||
class="rounded-md border border-border px-2 py-2 text-sm"
|
class="rounded-md border border-border px-2 py-2 text-sm"
|
||||||
>
|
>
|
||||||
<div class="mb-1 flex items-center gap-2">
|
<div class="mb-1 flex items-center gap-2">
|
||||||
<Radio
|
<Radio
|
||||||
:checked="m.isDefault"
|
:checked="m.isDefault"
|
||||||
@change="setDefaultModel(m.model)"
|
@change="setDefaultModel(d, m.model)"
|
||||||
>
|
>
|
||||||
默认
|
公司默认
|
||||||
</Radio>
|
</Radio>
|
||||||
<span class="min-w-0 flex-1 truncate font-medium">{{
|
<span class="min-w-0 flex-1 truncate font-medium">{{
|
||||||
m.model
|
m.model
|
||||||
@@ -344,7 +432,7 @@ onMounted(() => {
|
|||||||
type="link"
|
type="link"
|
||||||
size="small"
|
size="small"
|
||||||
danger
|
danger
|
||||||
@click="removeEnabledModel(m.model)"
|
@click="removeEnabledModel(d, m.model)"
|
||||||
>
|
>
|
||||||
移除
|
移除
|
||||||
</Button>
|
</Button>
|
||||||
@@ -357,11 +445,45 @@ onMounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</FormItem>
|
</FormItem>
|
||||||
<Button type="primary" :loading="saving" @click="saveSettings">
|
<Button
|
||||||
保存
|
type="primary"
|
||||||
|
:loading="d.savingModels"
|
||||||
|
@click="saveModels(d)"
|
||||||
|
>
|
||||||
|
保存启用模型
|
||||||
</Button>
|
</Button>
|
||||||
</Form>
|
</Form>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
v-model:open="createOpen"
|
||||||
|
title="添加提供商"
|
||||||
|
:confirm-loading="creating"
|
||||||
|
ok-text="创建"
|
||||||
|
destroy-on-close
|
||||||
|
@ok="submitCreate"
|
||||||
|
>
|
||||||
|
<Form layout="vertical" class="mt-2">
|
||||||
|
<FormItem label="Base URL" required>
|
||||||
|
<Input
|
||||||
|
v-model:value="createForm.baseUrl"
|
||||||
|
placeholder="https://api.deepseek.com/v1"
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
<FormItem label="API Key" required>
|
||||||
|
<InputPassword
|
||||||
|
v-model:value="createForm.apiKey"
|
||||||
|
placeholder="sk-..."
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
<FormItem label="备注(可选)">
|
||||||
|
<Input
|
||||||
|
v-model:value="createForm.displayName"
|
||||||
|
placeholder="如 DeepSeek"
|
||||||
|
/>
|
||||||
|
</FormItem>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
</Page>
|
</Page>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
Reference in New Issue
Block a user