Files
ecom-dmb/apps/agent/application/llm_settings_service.py
T

65 lines
2.1 KiB
Python

"""租户 LLM 运行时解析:Redis → 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,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig:
want_model = (model or "").strip() or None
want_provider = provider_id
cached = await self._cache.get(company_id, want_provider, want_model)
if cached is not None and cached.api_key:
return cached
remote = await self._gateway.fetch(company_id, want_provider, want_model)
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
and not want_model
and want_provider is None
):
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,
provider_id=None,
context_window=None,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=(
"当前公司尚未配置模型 API,或所选模型未启用;"
"请在「模型管理」中配置提供商并启用模型"
),
)