mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 03:09:19 +08:00
feat: 模型管理独立页与会话级选模型
This commit is contained in:
+33
-31
@@ -20,20 +20,22 @@
|
||||
|
||||
| 层 | 职责 | 不做什么 |
|
||||
|----|------|----------|
|
||||
| `apps/web` 聊天页 | UI、会话列表、流式展示;公司 LLM 配置表单(调 Server) | 不编排 LLM、不调 MCP、不持有明文长期 Key(仅提交时传一次) |
|
||||
| `apps/agent` | 会话/记忆/编排/流式 API、调 MCP、注入租户 LLM 凭证 | 不持久业务单据、不实现业务规则、**不存模型 Key** |
|
||||
| `apps/web` 聊天页 | UI、会话列表、流式展示、**会话级选模型** | 不编排 LLM、不调 MCP、不持有明文 Key |
|
||||
| `apps/web` 模型管理页 | 凭证 CRUD、启用模型列表、记忆管理(`agent:llm-settings`) | 不发聊天 |
|
||||
| `apps/agent` | 会话/记忆/编排/流式 API、调 MCP、按会话模型注入凭证 | 不持久业务单据、不实现业务规则、**不存模型 Key** |
|
||||
| `apps/server` | MySQL 存公司模型配置;MCP `@McpTool`;内部 llm-runtime | 不存聊天记录(对话在 Agent Mongo) |
|
||||
|
||||
### 1.3 数据流
|
||||
|
||||
```text
|
||||
[ web-antd 聊天页 ]
|
||||
[ web-antd ]
|
||||
│ JWT
|
||||
├─► Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key)
|
||||
└─► Agent /api/agent/sessions|chat|memories (Mongo 会话/记忆)
|
||||
├─► 模型管理页 → Server GET/PUT /api/company/agent-llm-settings (MySQL 加密 Key)
|
||||
├─► 聊天页 → Server GET /api/company/agent-llm-models (启用列表,无 Key)
|
||||
└─► 聊天页 → Agent /api/agent/sessions|chat|memories (Mongo;会话含 llm_model)
|
||||
│
|
||||
├─ Redis agent:llm:rt:{companyId} 或 Server /api/internal/agent/llm-runtime
|
||||
├─ ChatOpenAI(base_url, api_key, model) 按租户注入
|
||||
├─ Redis agent:llm:rt:{companyId}:{model} 或 Server /api/internal/agent/llm-runtime?model=
|
||||
├─ ChatOpenAI(base_url, api_key, model) 按会话模型注入
|
||||
└─ MCP /mcp + X-Agent-Company-Id / X-Agent-User-Id → BI tools
|
||||
```
|
||||
|
||||
@@ -67,11 +69,11 @@
|
||||
|
||||
约束:
|
||||
|
||||
1. **真相源**:MySQL `agent_company_llm_settings`(见 `apps/server/sql/design/agent/`);`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。
|
||||
2. **缓存**:Redis `agent:llm:rt:{company_id}` → `{base_url, api_key, model, …}`,TTL;配置变更时 DEL;**Agent 与 Server 须同 Redis DB**。
|
||||
3. **注入**:Agent 只读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`)。
|
||||
4. **权限**:更新需公司 owner(或超管);权限码 `agent:llm-settings`。
|
||||
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发。
|
||||
1. **真相源**:MySQL `agent_company_llm_provider` + `agent_company_llm_model`;`api_key` **AES-GCM 加密**(`ecom.agent.llm.secret` 或派生自 `jwt.secret`)。
|
||||
2. **缓存**:Redis `agent:llm:rt:{company_id}:{model}` → `{base_url, api_key, model, context_window, …}`,TTL;配置变更时按公司前缀 DEL;**Agent 与 Server 须同 Redis DB**。
|
||||
3. **注入**:Agent 按**会话 `llm_model`** 读 Redis / 内部接口明文;**禁止**下发完整 Key 给前端(读接口只返回 `apiKeyMasked`;聊天仅 `GET /agent-llm-models`)。
|
||||
4. **权限**:写配置靠 `agent:llm-settings`(不限 owner);聊天选模靠 `agent:chat`。
|
||||
5. **缺省**:未配置时聊天返回明确错误;`LLM_FALLBACK_*` 仅本地开发(且仅在无指定 model 时)。
|
||||
|
||||
---
|
||||
|
||||
@@ -119,6 +121,7 @@ apps/agent/
|
||||
| `title` | 可空,首轮后可自动生成 |
|
||||
| `status` | `active` / `archived` / `deleted` |
|
||||
| `summary` | 会话滚动摘要(可选) |
|
||||
| `llm_model` | 会话选用的模型 id(公司启用列表内);空则对话时回落默认并回写 |
|
||||
| `created_at`, `updated_at`, `last_message_at` | |
|
||||
|
||||
唯一索引:`(company_id, user_id, thread_id)`
|
||||
@@ -181,7 +184,11 @@ apps/agent/
|
||||
| `agent_company_llm_provider` | 公司一套 `base_url` + 加密 Key(UNIQUE company) |
|
||||
| `agent_company_llm_model` | 已启用模型多行;`is_default=1` 供 Agent 注入 |
|
||||
|
||||
浏览器:`GET/PUT /api/company/agent-llm-settings`;`POST .../probe-models` 代理 `{baseUrl}/v1/models`(不落库)。Agent 内部:`/api/internal/agent/llm-runtime` 返回**默认模型**明文(含 `contextWindow`)。
|
||||
浏览器:
|
||||
- `GET/PUT /api/company/agent-llm-settings` + `POST .../probe-models`(需 `agent:llm-settings`)
|
||||
- `GET /api/company/agent-llm-models`:启用列表 `{ items: [{ model, label, contextWindow, isDefault }] }`(需 `agent:chat`,无 Key)
|
||||
|
||||
Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&model=` —— `model` 空取默认;有值须在启用列表中,否则 400;返回明文凭证 + `contextWindow`。
|
||||
|
||||
### 4.3 与 LangGraph 的关系
|
||||
|
||||
@@ -211,17 +218,17 @@ apps/agent/
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/sessions` | 当前用户会话列表 |
|
||||
| POST | `/sessions` | 新建会话 |
|
||||
| PATCH | `/sessions/{thread_id}` | 改标题/归档 |
|
||||
| GET | `/sessions` | 当前用户会话列表(含 `llmModel`) |
|
||||
| POST | `/sessions` | 新建会话(可带 `llmModel`;缺省写公司默认) |
|
||||
| PATCH | `/sessions/{thread_id}` | 改标题 / `llmModel` |
|
||||
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE) |
|
||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话 `llm_model` 解析 runtime |
|
||||
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
||||
| DELETE | `/memories/{id}` | 用户删除某条记忆 |
|
||||
|
||||
SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状态条,不进正文)/ `done` / `error`。工具名经 `agent/tools/labels.py` 映射为中文 label。
|
||||
|
||||
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型列表);`POST .../probe-models` 拉提供商模型目录(不经 Agent)。
|
||||
公司 LLM 配置在 **Server**:`GET/PUT /api/company/agent-llm-settings`(凭证 + 启用模型);`POST .../probe-models`;聊天只读 `GET /api/company/agent-llm-models`。
|
||||
|
||||
鉴权:`Authorization: Bearer <用户 JWT>`;Agent 用与 server 共享的 `JWT_SECRET` 校验 HS512。JWT:`sub` = userId,claim `companyId` 等与 Java `JwtUtils` 一致。
|
||||
|
||||
@@ -242,25 +249,20 @@ SSE 事件:`token`(正文,可落库)/ `tool`(`{phase,name,label}` 状
|
||||
|
||||
### 7.1 页面
|
||||
|
||||
- 路由示例:`/agent/chat`
|
||||
- 菜单:一级「智能助手」
|
||||
- 另:公司配置入口「模型 API」(或聊天页设置抽屉)维护 OpenAI Compatible 凭证
|
||||
- 聊天:`/agent/chat`,菜单「智能助手」(仅 `agent:chat`)
|
||||
- 模型管理:`/agent/llm-settings`,一级菜单「模型管理」(仅 `agent:llm-settings`)
|
||||
- 聊天顶栏:`Select` 切换当前会话模型(PATCH `llmModel`);新对话草稿本地暂存,创建时带上
|
||||
- 布局:**左会话列表 + 右消息区 + 底输入**;全页 `flex` + `min-h-0` 滚动(遵守现有 Spin/滚动规范)
|
||||
|
||||
### 7.2 组件(自建,不引入 AI UI 库)
|
||||
|
||||
```text
|
||||
views/agent/chat/
|
||||
index.vue # 页壳
|
||||
components/
|
||||
SessionSidebar.vue
|
||||
MessageList.vue
|
||||
MessageBubble.vue
|
||||
ChatComposer.vue
|
||||
ToolCallBlock.vue # 可选:折叠展示 tool 结果
|
||||
composables/
|
||||
useAgentChat.ts # 流式消费、本地消息缓冲
|
||||
api/agent/ # 调 Agent 服务,非调 Java /api
|
||||
index.vue # 聊天:会话列表 + 消息 + 顶栏选模型
|
||||
catalog-cite*.vue/ts # 店铺/商品引用输入
|
||||
views/agent/llm-settings/
|
||||
index.vue # 模型管理:凭证 / 启用列表 / 记忆
|
||||
api/agent/ # 调 Agent + Server 公司 LLM API
|
||||
```
|
||||
|
||||
### 7.3 配置
|
||||
|
||||
+13
-10
@@ -34,16 +34,6 @@ async def current_actor(
|
||||
return parse_actor(settings, token)
|
||||
|
||||
|
||||
async def session_service(settings: Settings = Depends(get_settings)) -> SessionService:
|
||||
db = await get_db(settings)
|
||||
return SessionService(MongoSessionRepository(db))
|
||||
|
||||
|
||||
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
||||
db = await get_db(settings)
|
||||
return MemoryService(settings, MongoMemoryRepository(db))
|
||||
|
||||
|
||||
async def llm_runtime_service(
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> LlmRuntimeService:
|
||||
@@ -51,6 +41,19 @@ async def llm_runtime_service(
|
||||
return LlmRuntimeService(settings, cache, ServerLlmRuntimeGateway(settings))
|
||||
|
||||
|
||||
async def session_service(
|
||||
settings: Settings = Depends(get_settings),
|
||||
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
||||
) -> SessionService:
|
||||
db = await get_db(settings)
|
||||
return SessionService(MongoSessionRepository(db), llm_runtime=llm_svc)
|
||||
|
||||
|
||||
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
||||
db = await get_db(settings)
|
||||
return MemoryService(settings, MongoMemoryRepository(db))
|
||||
|
||||
|
||||
async def chat_service(
|
||||
settings: Settings = Depends(get_settings),
|
||||
sessions: SessionService = Depends(session_service),
|
||||
|
||||
@@ -15,10 +15,12 @@ router = APIRouter(prefix="/sessions", tags=["sessions"])
|
||||
|
||||
class CreateSessionBody(BaseModel):
|
||||
title: str | None = None
|
||||
llmModel: str | None = None
|
||||
|
||||
|
||||
class RenameBody(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
class PatchSessionBody(BaseModel):
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
llmModel: str | None = None
|
||||
|
||||
|
||||
def _session_vo(s) -> dict:
|
||||
@@ -26,6 +28,7 @@ def _session_vo(s) -> dict:
|
||||
"threadId": s.thread_id,
|
||||
"title": s.title,
|
||||
"status": s.status.value,
|
||||
"llmModel": s.llm_model,
|
||||
"createdAt": s.created_at.isoformat() + "Z",
|
||||
"updatedAt": s.updated_at.isoformat() + "Z",
|
||||
"lastMessageAt": s.last_message_at.isoformat() + "Z" if s.last_message_at else None,
|
||||
@@ -47,19 +50,28 @@ async def create_session(
|
||||
actor: Actor = Depends(current_actor),
|
||||
svc: SessionService = Depends(session_service),
|
||||
):
|
||||
s = await svc.create(actor, body.title)
|
||||
s = await svc.create(actor, body.title, llm_model=body.llmModel)
|
||||
return ok(_session_vo(s))
|
||||
|
||||
|
||||
@router.patch("/{thread_id}")
|
||||
async def rename_session(
|
||||
async def patch_session(
|
||||
thread_id: str,
|
||||
body: RenameBody,
|
||||
body: PatchSessionBody,
|
||||
actor: Actor = Depends(current_actor),
|
||||
svc: SessionService = Depends(session_service),
|
||||
):
|
||||
if body.title is None and body.llmModel is None:
|
||||
raise HTTPException(status_code=400, detail="无有效更新字段")
|
||||
try:
|
||||
s = await svc.rename(actor, thread_id, body.title)
|
||||
s = None
|
||||
if body.title is not None:
|
||||
s = await svc.rename(actor, thread_id, body.title)
|
||||
if body.llmModel is not None:
|
||||
s = await svc.update_llm_model(actor, thread_id, body.llmModel)
|
||||
assert s is not None
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
except LookupError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
return ok(_session_vo(s))
|
||||
|
||||
@@ -52,7 +52,13 @@ class ChatService:
|
||||
raise ValueError("消息不能为空")
|
||||
|
||||
session = await self._sessions.require_owned(actor, thread_id)
|
||||
llm = await self._llm_runtime.resolve_runtime(actor.company_id)
|
||||
llm = await self._llm_runtime.resolve_runtime(
|
||||
actor.company_id, model=session.llm_model
|
||||
)
|
||||
# 会话未记模型或回落后写回,保证列表/选框有稳定值
|
||||
if not session.llm_model or session.llm_model != llm.model:
|
||||
session.llm_model = llm.model
|
||||
await self._session_repo.update(session)
|
||||
just_saved = await self._memory.maybe_capture_from_user(
|
||||
actor, thread_id=thread_id, text=text
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""租户 LLM 运行时解析:Redis(Server 写入)→ Server 内部 API → 本地 fallback。"""
|
||||
"""租户 LLM 运行时解析:Redis → Server 内部 API → 本地 fallback。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -20,21 +20,28 @@ class LlmRuntimeService:
|
||||
self._cache = cache
|
||||
self._gateway = gateway
|
||||
|
||||
async def resolve_runtime(self, company_id: int) -> LlmRuntimeConfig:
|
||||
cached = await self._cache.get(company_id)
|
||||
async def resolve_runtime(
|
||||
self, company_id: int, model: str | None = None
|
||||
) -> LlmRuntimeConfig:
|
||||
want = (model or "").strip() or None
|
||||
cached = await self._cache.get(company_id, want)
|
||||
if cached is not None and cached.api_key:
|
||||
return cached
|
||||
|
||||
remote = await self._gateway.fetch(company_id)
|
||||
remote = await self._gateway.fetch(company_id, want)
|
||||
if remote is not None and remote.api_key and remote.base_url and remote.model:
|
||||
await self._cache.set(
|
||||
company_id, remote, self._settings.llm_cache_ttl_seconds
|
||||
company_id,
|
||||
remote,
|
||||
self._settings.llm_cache_ttl_seconds,
|
||||
model=remote.model,
|
||||
)
|
||||
return remote
|
||||
|
||||
if (
|
||||
self._settings.llm_fallback_enabled
|
||||
and self._settings.llm_fallback_api_key
|
||||
and not want
|
||||
):
|
||||
return LlmRuntimeConfig(
|
||||
base_url=self._settings.llm_fallback_base_url.rstrip("/"),
|
||||
@@ -45,5 +52,8 @@ class LlmRuntimeService:
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="当前公司尚未配置模型 API,请先在智能助手设置中填写 OpenAI Compatible 凭证",
|
||||
detail=(
|
||||
"当前公司尚未配置模型 API,或所选模型未启用;"
|
||||
"请在「模型管理」中配置凭证并启用模型"
|
||||
),
|
||||
)
|
||||
|
||||
@@ -5,22 +5,41 @@ from __future__ import annotations
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from application.llm_settings_service import LlmRuntimeService
|
||||
from domain.models import Actor, Session, SessionStatus
|
||||
from domain.ports import SessionRepository
|
||||
|
||||
|
||||
class SessionService:
|
||||
def __init__(self, sessions: SessionRepository) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
sessions: SessionRepository,
|
||||
llm_runtime: LlmRuntimeService | None = None,
|
||||
) -> None:
|
||||
self._sessions = sessions
|
||||
self._llm_runtime = llm_runtime
|
||||
|
||||
async def create(self, actor: Actor, title: str | None = None) -> Session:
|
||||
async def create(
|
||||
self,
|
||||
actor: Actor,
|
||||
title: str | None = None,
|
||||
llm_model: str | None = None,
|
||||
) -> Session:
|
||||
now = datetime.utcnow()
|
||||
model = (llm_model or "").strip() or None
|
||||
if not model and self._llm_runtime is not None:
|
||||
try:
|
||||
rt = await self._llm_runtime.resolve_runtime(actor.company_id)
|
||||
model = rt.model or None
|
||||
except Exception:
|
||||
model = None
|
||||
session = Session(
|
||||
thread_id=str(uuid.uuid4()),
|
||||
company_id=actor.company_id,
|
||||
user_id=actor.user_id,
|
||||
title=(title or "新对话").strip() or "新对话",
|
||||
status=SessionStatus.ACTIVE,
|
||||
llm_model=model,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
@@ -40,6 +59,16 @@ class SessionService:
|
||||
session.title = title.strip() or session.title
|
||||
return await self._sessions.update(session)
|
||||
|
||||
async def update_llm_model(
|
||||
self, actor: Actor, thread_id: str, llm_model: str
|
||||
) -> Session:
|
||||
model = (llm_model or "").strip()
|
||||
if not model:
|
||||
raise ValueError("模型不能为空")
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
session.llm_model = model
|
||||
return await self._sessions.update(session)
|
||||
|
||||
async def archive(self, actor: Actor, thread_id: str) -> Session:
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
session.status = SessionStatus.ARCHIVED
|
||||
|
||||
@@ -58,6 +58,8 @@ class Session:
|
||||
title: str = "新对话"
|
||||
status: SessionStatus = SessionStatus.ACTIVE
|
||||
summary: str | None = None
|
||||
# 会话选用的模型 id;空则对话时回落公司默认
|
||||
llm_model: str | None = None
|
||||
created_at: datetime = field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = field(default_factory=datetime.utcnow)
|
||||
last_message_at: datetime | None = None
|
||||
|
||||
@@ -63,20 +63,30 @@ class MemoryRepository(ABC):
|
||||
|
||||
class LlmRuntimeCache(ABC):
|
||||
@abstractmethod
|
||||
async def get(self, company_id: int) -> LlmRuntimeConfig | None: ...
|
||||
async def get(
|
||||
self, company_id: int, model: str | None = None
|
||||
) -> LlmRuntimeConfig | None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None: ...
|
||||
async def set(
|
||||
self,
|
||||
company_id: int,
|
||||
config: LlmRuntimeConfig,
|
||||
ttl_seconds: int,
|
||||
model: str | None = None,
|
||||
) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def delete(self, company_id: int) -> None: ...
|
||||
async def delete(self, company_id: int, model: str | None = None) -> None: ...
|
||||
|
||||
|
||||
class LlmRuntimeGateway(ABC):
|
||||
"""从 Server 拉取运行时模型配置(MySQL 真相源)。"""
|
||||
|
||||
@abstractmethod
|
||||
async def fetch(self, company_id: int) -> LlmRuntimeConfig | None: ...
|
||||
async def fetch(
|
||||
self, company_id: int, model: str | None = None
|
||||
) -> LlmRuntimeConfig | None: ...
|
||||
|
||||
|
||||
class ChatStreamer(ABC):
|
||||
|
||||
@@ -14,21 +14,23 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
"""GET /api/internal/agent/llm-runtime?companyId=…(Agent Bearer)。"""
|
||||
"""GET /api/internal/agent/llm-runtime?companyId=&model=(Agent Bearer)。"""
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self._settings = settings
|
||||
|
||||
async def fetch(self, company_id: int) -> LlmRuntimeConfig | None:
|
||||
async def fetch(
|
||||
self, company_id: int, model: str | None = None
|
||||
) -> LlmRuntimeConfig | None:
|
||||
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
|
||||
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
|
||||
params: dict[str, str | int] = {"companyId": company_id}
|
||||
if model:
|
||||
params["model"] = model
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
resp = await client.get(
|
||||
url, params={"companyId": company_id}, headers=headers
|
||||
)
|
||||
resp = await client.get(url, params=params, headers=headers)
|
||||
if resp.status_code == 400:
|
||||
# 未配置
|
||||
return None
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
@@ -46,7 +48,11 @@ class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
||||
context_window=_optional_positive_int(data.get("contextWindow")),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("拉取 Server LLM runtime 失败 company_id=%s", company_id)
|
||||
logger.exception(
|
||||
"拉取 Server LLM runtime 失败 company_id=%s model=%s",
|
||||
company_id,
|
||||
model,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
"title": session.title,
|
||||
"status": session.status.value,
|
||||
"summary": session.summary,
|
||||
"llm_model": session.llm_model,
|
||||
"created_at": session.created_at,
|
||||
"updated_at": session.updated_at,
|
||||
"last_message_at": session.last_message_at,
|
||||
@@ -79,6 +80,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
"title": session.title,
|
||||
"status": session.status.value,
|
||||
"summary": session.summary,
|
||||
"llm_model": session.llm_model,
|
||||
"updated_at": session.updated_at,
|
||||
"last_message_at": session.last_message_at,
|
||||
}
|
||||
@@ -95,6 +97,7 @@ class MongoSessionRepository(SessionRepository):
|
||||
title=doc.get("title") or "新对话",
|
||||
status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value),
|
||||
summary=doc.get("summary"),
|
||||
llm_model=doc.get("llm_model"),
|
||||
created_at=_dt(doc.get("created_at")),
|
||||
updated_at=_dt(doc.get("updated_at")),
|
||||
last_message_at=doc.get("last_message_at"),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Redis 缓存租户 LLM 运行时配置。"""
|
||||
"""Redis 缓存租户 LLM 运行时配置(按公司+模型)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,23 +16,40 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
self._r = client
|
||||
|
||||
@staticmethod
|
||||
def _key(company_id: int) -> str:
|
||||
def _key(company_id: int, model: str | None) -> str:
|
||||
if model:
|
||||
return f"agent:llm:rt:{company_id}:{model}"
|
||||
return f"agent:llm:rt:{company_id}"
|
||||
|
||||
async def get(self, company_id: int) -> LlmRuntimeConfig | None:
|
||||
raw = await self._r.get(self._key(company_id))
|
||||
async def get(
|
||||
self, company_id: int, model: str | None = None
|
||||
) -> LlmRuntimeConfig | None:
|
||||
raw = await self._r.get(self._key(company_id, model))
|
||||
if not raw and model:
|
||||
# 兼容旧缓存键(仅 companyId)
|
||||
raw = await self._r.get(self._key(company_id, None))
|
||||
if not raw:
|
||||
return None
|
||||
data = json.loads(raw)
|
||||
return LlmRuntimeConfig(
|
||||
cfg = LlmRuntimeConfig(
|
||||
base_url=data["base_url"],
|
||||
api_key=data["api_key"],
|
||||
model=data["model"],
|
||||
extra_headers=data.get("extra_headers") or {},
|
||||
context_window=_optional_int(data.get("context_window")),
|
||||
)
|
||||
if model and cfg.model and cfg.model != model:
|
||||
return None
|
||||
return cfg
|
||||
|
||||
async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None:
|
||||
async def set(
|
||||
self,
|
||||
company_id: int,
|
||||
config: LlmRuntimeConfig,
|
||||
ttl_seconds: int,
|
||||
model: str | None = None,
|
||||
) -> None:
|
||||
key_model = model or config.model
|
||||
payload = {
|
||||
"base_url": config.base_url,
|
||||
"api_key": config.api_key,
|
||||
@@ -40,10 +57,19 @@ class RedisLlmRuntimeCache(LlmRuntimeCache):
|
||||
"extra_headers": config.extra_headers,
|
||||
"context_window": config.context_window,
|
||||
}
|
||||
await self._r.set(self._key(company_id), json.dumps(payload), ex=ttl_seconds)
|
||||
await self._r.set(
|
||||
self._key(company_id, key_model),
|
||||
json.dumps(payload),
|
||||
ex=ttl_seconds,
|
||||
)
|
||||
|
||||
async def delete(self, company_id: int) -> None:
|
||||
await self._r.delete(self._key(company_id))
|
||||
async def delete(self, company_id: int, model: str | None = None) -> None:
|
||||
if model:
|
||||
await self._r.delete(self._key(company_id, model))
|
||||
return
|
||||
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
|
||||
if keys:
|
||||
await self._r.delete(*keys)
|
||||
|
||||
|
||||
_redis: redis.Redis | None = None
|
||||
|
||||
Reference in New Issue
Block a user