"""租户 LLM 运行时解析:Redis(Server 写入)→ Server 内部 API → 本地 fallback。""" from __future__ import annotations from fastapi import HTTPException, status from config.settings import Settings from domain.models import LlmRuntimeConfig from domain.ports import LlmRuntimeCache, LlmRuntimeGateway class LlmRuntimeService: def __init__( self, settings: Settings, cache: LlmRuntimeCache, gateway: LlmRuntimeGateway, ) -> None: self._settings = settings self._cache = cache self._gateway = gateway async def resolve_runtime(self, company_id: int) -> LlmRuntimeConfig: cached = await self._cache.get(company_id) if cached is not None and cached.api_key: return cached remote = await self._gateway.fetch(company_id) if remote is not None and remote.api_key and remote.base_url and remote.model: await self._cache.set( company_id, remote, self._settings.llm_cache_ttl_seconds ) return remote if ( self._settings.llm_fallback_enabled and self._settings.llm_fallback_api_key ): return LlmRuntimeConfig( base_url=self._settings.llm_fallback_base_url.rstrip("/"), api_key=self._settings.llm_fallback_api_key, model=self._settings.llm_fallback_model, ) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="当前公司尚未配置模型 API,请先在智能助手设置中填写 OpenAI Compatible 凭证", )