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

100 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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, 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, 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)
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,
model: str | None = None,
) -> None:
key_model = model or config.model
payload = {
"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, key_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
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