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
@@ -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)