feat: 公司支持多模型提供商与会话消歧选型

This commit is contained in:
2026-09-20 16:35:06 +08:00
parent d7e4a987c1
commit 9350323ff2
30 changed files with 1031 additions and 448 deletions
+29 -25
View File
@@ -30,12 +30,13 @@
```text
[ web-antd ]
│ JWT
├─► 模型管理页 → Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key)
├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,无 Key)
└─► 聊天页 → Agent /api/agent/sessions|chat|memories (Mongo;会话含 llm_model)
├─► 模型管理页 → Server /api/company/agent-llm-providers* (多提供商 CRUD)
├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,含 providerId)
└─► 聊天页 → 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=
├─ ChatOpenAI(base_url, api_key, model) 按会话模型注入
├─ Redis agent:llm:rt:{companyId}:{providerId}:{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
```
@@ -69,11 +70,12 @@
约束:
1. **真相源**:MySQL `agent_company_llm_provider` + `agent_company_llm_model`;`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。
2. **缓存**:Redis `agent:llm:rt:{company_id}:{model}` → `{base_url, api_key, model, context_window, …}`,TTL;配置变更时按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。
3. **注入**:Agent 按**会话 `llm_model`** 读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`;聊天仅 `GET /agent-llm-models`)。
4. **权限**:写配置靠 `agent:llm-settings`(不限 owner);聊天选模靠 `agent:chat`。
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且仅在无指定 model 时)。
1. **真相源**:MySQL `agent_company_llm_provider`(多行/公司)+ `agent_company_llm_model`(挂 `provider_id`);`api_key` **AES-GCM 加密**。
2. **缓存**:Redis `agent:llm:rt:{company_id}:{provider_id}:{model}`;配置变更按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。
3. **注入**:Agent 按会话 **`llm_provider_id` + `llm_model`** 解析;跨提供商允许同名 model。
4. **权限**:写配置靠 `agent:llm-settings`;聊天选模靠 `agent:chat`。
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且未指定选型时)。
6. **启用列表写入**:按 `(provider_id, model)` **增量 upsert**(更新已有、插入新增、删除取消勾选),禁止整表删建,以免破坏会话引用。
---
@@ -121,7 +123,8 @@ apps/agent/
| `title` | 可空,首轮后可自动生成 |
| `status` | `active` / `archived` / `deleted` |
| `summary` | 会话滚动摘要(可选) |
| `llm_model` | 会话选用的模型 id(公司启用列表内);空则对话时回落默认并回写 |
| `llm_provider_id` | 会话选用的提供商 id |
| `llm_model` | 会话选用的模型 id;与 provider 一起消歧;空则对话时回落公司默认并回写 |
| `created_at`, `updated_at`, `last_message_at` | |
唯一索引:`(company_id, user_id, thread_id)`
@@ -177,18 +180,19 @@ apps/agent/
### 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_model` | 已启用模型多行;`is_default=1` 供 Agent 注入 |
| `agent_company_llm_provider` | 公司多套 `base_url` + 加密 Key |
| `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 /api/company/agent-llm-models`:启用列表 `{ items: [{ model, label, contextWindow, isDefault }] }`(需 `agent:chat`,无 Key)
- `GET/POST /api/company/agent-llm-providers`;`GET/PUT/DELETE .../providers/{id}`;`PUT .../providers/{id}/models`(增量 upsert)
- `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 的关系
@@ -218,17 +222,17 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&model=` —— `m
| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/sessions` | 当前用户会话列表(含 `llmModel`) |
| POST | `/sessions` | 新建会话(可带 `llmModel`;缺省写公司默认) |
| PATCH | `/sessions/{thread_id}` | 改标题 / `llmModel` |
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话 `llm_model` 解析 runtime |
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
| GET | `/memories` | 查看自己的记忆条目(可透明) |
| DELETE | `/memories/{id}` | 用户删除某条记忆 |
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型);`POST .../probe-models`;聊天只读 `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` 一致。
@@ -250,9 +254,9 @@ SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状
### 7.1 页面
- 聊天:`/agent/chat`,菜单「智能助手」(仅 `agent:chat`)
- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`)
- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`);多提供商卡片
- 我的记忆:`/agent/memories`,头像下拉入口(有 `agent:chat` 时显示;静态路由)
- 聊天顶栏:`Select` 切换当前会话模型(PATCH `llmModel`);新对话草稿本地暂存,创建时带上
- 聊天顶栏:按提供商分组 `Select`;切换即 PATCH `llmProviderId`+`llmModel`
- 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范)
### 7.2 组件(自建,不引入 AI UI 库)
@@ -262,7 +266,7 @@ views/agent/chat/
index.vue # 聊天:会话列表 + 消息 + 顶栏选模型
catalog-cite*.vue/ts # 店铺/商品引用输入
views/agent/llm-settings/
index.vue # 模型管理:凭证 / 启用列表
index.vue # 模型管理:多提供商 CRUD + 启用列表增量保存
views/agent/memories/
index.vue # 我的记忆:列表 / 删除(用户中心入口)
api/agent/ # 调 Agent + Server 公司 LLM API
+21 -4
View File
@@ -15,11 +15,13 @@ router = APIRouter(prefix="/sessions", tags=["sessions"])
class CreateSessionBody(BaseModel):
title: str | None = None
llmProviderId: int | None = None
llmModel: str | None = None
class PatchSessionBody(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=200)
llmProviderId: int | None = None
llmModel: str | None = None
@@ -28,6 +30,7 @@ def _session_vo(s) -> dict:
"threadId": s.thread_id,
"title": s.title,
"status": s.status.value,
"llmProviderId": s.llm_provider_id,
"llmModel": s.llm_model,
"createdAt": s.created_at.isoformat() + "Z",
"updatedAt": s.updated_at.isoformat() + "Z",
@@ -50,7 +53,12 @@ async def create_session(
actor: Actor = Depends(current_actor),
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))
@@ -61,14 +69,23 @@ async def patch_session(
actor: Actor = Depends(current_actor),
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="无有效更新字段")
try:
s = None
if body.title is not None:
s = await svc.rename(actor, thread_id, body.title)
if body.llmModel is not None:
s = await svc.update_llm_model(actor, thread_id, body.llmModel)
if body.llmModel is not None or body.llmProviderId is not None:
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
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
+11 -3
View File
@@ -53,11 +53,19 @@ class ChatService:
session = await self._sessions.require_owned(actor, thread_id)
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
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)
just_saved = await self._memory.maybe_capture_from_user(
actor, thread_id=thread_id, text=text
+12 -7
View File
@@ -21,32 +21,37 @@ class LlmRuntimeService:
self._gateway = gateway
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:
want = (model or "").strip() or None
cached = await self._cache.get(company_id, want)
want_model = (model or "").strip() or None
want_provider = provider_id
cached = await self._cache.get(company_id, want_provider, want_model)
if cached is not None and cached.api_key:
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:
await self._cache.set(
company_id,
remote,
self._settings.llm_cache_ttl_seconds,
model=remote.model,
)
return remote
if (
self._settings.llm_fallback_enabled
and self._settings.llm_fallback_api_key
and not want
and not want_model
and want_provider is None
):
return LlmRuntimeConfig(
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
api_key=self._settings.llm_fallback_api_key,
model=self._settings.llm_fallback_model,
provider_id=None,
context_window=None,
)
@@ -54,6 +59,6 @@ class LlmRuntimeService:
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
"当前公司尚未配置模型 API,或所选模型未启用;"
"请在「模型管理」中配置凭证并启用模型"
"请在「模型管理」中配置提供商并启用模型"
),
)
+22 -6
View File
@@ -23,22 +23,30 @@ class SessionService:
self,
actor: Actor,
title: str | None = None,
llm_provider_id: int | None = None,
llm_model: str | None = None,
) -> Session:
now = datetime.utcnow()
model = (llm_model or "").strip() or None
if not model and self._llm_runtime is not None:
provider_id = llm_provider_id
if (not model or provider_id is None) and self._llm_runtime is not None:
try:
rt = await self._llm_runtime.resolve_runtime(actor.company_id)
model = rt.model or None
rt = await self._llm_runtime.resolve_runtime(
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:
model = None
pass
session = Session(
thread_id=str(uuid.uuid4()),
company_id=actor.company_id,
user_id=actor.user_id,
title=(title or "新对话").strip() or "新对话",
status=SessionStatus.ACTIVE,
llm_provider_id=provider_id,
llm_model=model,
created_at=now,
updated_at=now,
@@ -59,13 +67,21 @@ class SessionService:
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def update_llm_model(
self, actor: Actor, thread_id: str, llm_model: str
async def update_llm_selection(
self,
actor: Actor,
thread_id: str,
*,
llm_provider_id: int,
llm_model: str,
) -> Session:
model = (llm_model or "").strip()
if not model:
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.llm_provider_id = int(llm_provider_id)
session.llm_model = model
return await self._sessions.update(session)
+3 -1
View File
@@ -58,7 +58,8 @@ class Session:
title: str = "新对话"
status: SessionStatus = SessionStatus.ACTIVE
summary: str | None = None
# 会话选用的模型 id;空则对话时回落公司默认
# 会话选用的提供商 + 模型(同名 model 靠 provider 消歧)
llm_provider_id: int | None = None
llm_model: str | None = None
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
@@ -105,6 +106,7 @@ class LlmRuntimeConfig:
base_url: str
api_key: str
model: str
provider_id: int | None = None
extra_headers: dict[str, str] = field(default_factory=dict)
# 租户配置的上下文窗口;None 表示由 Agent 按模型名估计
context_window: int | None = None
+10 -5
View File
@@ -64,7 +64,10 @@ class MemoryRepository(ABC):
class LlmRuntimeCache(ABC):
@abstractmethod
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: ...
@abstractmethod
@@ -73,11 +76,10 @@ class LlmRuntimeCache(ABC):
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
model: str | None = None,
) -> None: ...
@abstractmethod
async def delete(self, company_id: int, model: str | None = None) -> None: ...
async def delete(self, company_id: int) -> None: ...
class LlmRuntimeGateway(ABC):
@@ -85,7 +87,10 @@ class LlmRuntimeGateway(ABC):
@abstractmethod
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: ...
@@ -101,5 +106,5 @@ class ChatStreamer(ABC):
user_text: str,
system_prompt: str,
tools: list[Any] | None = None,
max_tool_result_chars: int = 8000,
max_tool_result_chars: int = 4000,
) -> AsyncIterator[StreamEvent]: ...
+11 -3
View File
@@ -14,17 +14,22 @@ logger = logging.getLogger(__name__)
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:
self._settings = settings
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:
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
params: dict[str, str | int] = {"companyId": company_id}
if provider_id is not None:
params["providerId"] = provider_id
if model:
params["model"] = model
try:
@@ -37,10 +42,12 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
data = body.get("data") if isinstance(body, dict) else None
if not isinstance(data, dict):
return None
pid = data.get("providerId")
return LlmRuntimeConfig(
base_url=str(data.get("baseUrl") or "").rstrip("/"),
api_key=str(data.get("apiKey") or ""),
model=str(data.get("model") or ""),
provider_id=int(pid) if pid is not None else provider_id,
extra_headers={
str(k): str(v)
for k, v in (data.get("extraHeaders") or {}).items()
@@ -49,8 +56,9 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
)
except Exception:
logger.exception(
"拉取 Server LLM runtime 失败 company_id=%s model=%s",
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
company_id,
provider_id,
model,
)
return None
@@ -27,6 +27,15 @@ def _dt(v: Any) -> datetime:
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):
def __init__(self, db: AsyncIOMotorDatabase) -> None:
self._col = db.agent_sessions
@@ -39,6 +48,7 @@ class MongoSessionRepository(SessionRepository):
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"created_at": session.created_at,
"updated_at": session.updated_at,
@@ -80,6 +90,7 @@ class MongoSessionRepository(SessionRepository):
"title": session.title,
"status": session.status.value,
"summary": session.summary,
"llm_provider_id": session.llm_provider_id,
"llm_model": session.llm_model,
"updated_at": session.updated_at,
"last_message_at": session.last_message_at,
@@ -97,6 +108,7 @@ class MongoSessionRepository(SessionRepository):
title=doc.get("title") or "新对话",
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
summary=doc.get("summary"),
llm_provider_id=_optional_int(doc.get("llm_provider_id")),
llm_model=doc.get("llm_model"),
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
@@ -1,4 +1,4 @@
"""Redis 缓存租户 LLM 运行时配置(按公司+模型)。"""
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
from __future__ import annotations
@@ -16,18 +16,23 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
self._r = client
@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:
return f"agent:llm:rt:{company_id}:{model}"
return f"agent:llm:rt:{company_id}"
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:
raw = await self._r.get(self._key(company_id, model))
if not raw and model:
# 兼容旧缓存键(仅 companyId)
raw = await self._r.get(self._key(company_id, None))
raw = await self._r.get(self._key(company_id, provider_id, model))
if not raw and provider_id is not None and model:
# 兼容旧键 companyId:model
raw = await self._r.get(self._key(company_id, None, model))
if not raw:
return None
data = json.loads(raw)
@@ -35,11 +40,14 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
base_url=data["base_url"],
api_key=data["api_key"],
model=data["model"],
provider_id=_optional_int(data.get("provider_id")) or provider_id,
extra_headers=data.get("extra_headers") or {},
context_window=_optional_int(data.get("context_window")),
)
if model and cfg.model and cfg.model != model:
return None
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
return None
return cfg
async def set(
@@ -47,10 +55,9 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
model: str | None = None,
) -> None:
key_model = model or config.model
payload = {
"provider_id": config.provider_id,
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
@@ -58,15 +65,12 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
"context_window": config.context_window,
}
await self._r.set(
self._key(company_id, key_model),
self._key(company_id, config.provider_id, config.model),
json.dumps(payload),
ex=ttl_seconds,
)
async def delete(self, company_id: int, model: str | None = None) -> None:
if model:
await self._r.delete(self._key(company_id, model))
return
async def delete(self, company_id: int) -> None:
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
if keys:
await self._r.delete(*keys)