feat: 模型管理独立页与会话级选模型

This commit is contained in:
2026-09-20 15:42:25 +08:00
parent ffb8d5f7dc
commit aac3424911
24 changed files with 845 additions and 523 deletions
+13 -7
View File
@@ -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