mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 07:09:20 +08:00
62 lines
1.7 KiB
Python
62 lines
1.7 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) -> str:
|
|
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))
|
|
if not raw:
|
|
return None
|
|
data = json.loads(raw)
|
|
return LlmRuntimeConfig(
|
|
base_url=data["base_url"],
|
|
api_key=data["api_key"],
|
|
model=data["model"],
|
|
extra_headers=data.get("extra_headers") or {},
|
|
)
|
|
|
|
async def set(self, company_id: int, config: LlmRuntimeConfig, ttl_seconds: int) -> None:
|
|
payload = {
|
|
"base_url": config.base_url,
|
|
"api_key": config.api_key,
|
|
"model": config.model,
|
|
"extra_headers": config.extra_headers,
|
|
}
|
|
await self._r.set(self._key(company_id), json.dumps(payload), ex=ttl_seconds)
|
|
|
|
async def delete(self, company_id: int) -> None:
|
|
await self._r.delete(self._key(company_id))
|
|
|
|
|
|
_redis: redis.Redis | None = 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
|