Files
ecom-dmb/apps/agent/infrastructure/persistence/redis/cache.py
T

104 lines
3.1 KiB
Python

"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
from __future__ import annotations
import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmRuntimeConfig
from domain.ports import LlmRuntimeCache
class RedisLlmRuntimeCache(LlmRuntimeCache):
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
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,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | 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)
cfg = LlmRuntimeConfig(
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(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None:
payload = {
"provider_id": config.provider_id,
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
"extra_headers": config.extra_headers,
"context_window": config.context_window,
}
await self._r.set(
self._key(company_id, config.provider_id, config.model),
json.dumps(payload),
ex=ttl_seconds,
)
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)
_redis: redis.Redis | None = None
def _optional_int(v) -> int | None:
if v is None:
return None
try:
n = int(v)
except (TypeError, ValueError):
return None
return n if n > 0 else None
def get_redis(settings: Settings) -> redis.Redis:
global _redis
if _redis is None:
_redis = redis.from_url(settings.redis_url, decode_responses=True)
return _redis
async def close_redis() -> None:
global _redis
if _redis is not None:
await _redis.aclose()
_redis = None