mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 03:19:18 +08:00
79 lines
2.7 KiB
Python
79 lines
2.7 KiB
Python
"""从 Server 内部接口拉取 LLM 运行时配置。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
import httpx
|
|
|
|
from config.settings import Settings
|
|
from domain.models import LlmRuntimeConfig
|
|
from domain.ports import LlmRuntimeGateway
|
|
from infrastructure.llm.api_style import normalize_api_style
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
|
|
"""GET /api/internal/agent/llm-runtime?companyId=&providerId=&model=。"""
|
|
|
|
def __init__(self, settings: Settings) -> None:
|
|
self._settings = settings
|
|
|
|
async def fetch(
|
|
self,
|
|
company_id: int,
|
|
provider_id: int | None = None,
|
|
model: str | None = None,
|
|
) -> LlmRuntimeConfig | None:
|
|
url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime"
|
|
headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"}
|
|
params: dict[str, str | int] = {"companyId": company_id}
|
|
if provider_id is not None:
|
|
params["providerId"] = provider_id
|
|
if model:
|
|
params["model"] = model
|
|
try:
|
|
async with httpx.AsyncClient(timeout=15.0) as client:
|
|
resp = await client.get(url, params=params, headers=headers)
|
|
if resp.status_code == 400:
|
|
return None
|
|
resp.raise_for_status()
|
|
body = resp.json()
|
|
data = body.get("data") if isinstance(body, dict) else None
|
|
if not isinstance(data, dict):
|
|
return None
|
|
pid = data.get("providerId")
|
|
return LlmRuntimeConfig(
|
|
base_url=str(data.get("baseUrl") or "").rstrip("/"),
|
|
api_key=str(data.get("apiKey") or ""),
|
|
model=str(data.get("model") or ""),
|
|
provider_id=int(pid) if pid is not None else provider_id,
|
|
extra_headers={
|
|
str(k): str(v)
|
|
for k, v in (data.get("extraHeaders") or {}).items()
|
|
},
|
|
context_window=_optional_positive_int(data.get("contextWindow")),
|
|
api_style=normalize_api_style(
|
|
None if data.get("apiStyle") is None else str(data.get("apiStyle"))
|
|
),
|
|
)
|
|
except Exception:
|
|
logger.exception(
|
|
"拉取 Server LLM runtime 失败 company_id=%s provider_id=%s model=%s",
|
|
company_id,
|
|
provider_id,
|
|
model,
|
|
)
|
|
return None
|
|
|
|
|
|
def _optional_positive_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
|