Files
ecom-dmb/apps/agent/infrastructure/llm/gateway.py
T

67 lines
2.2 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.
"""从 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
logger = logging.getLogger(__name__)
class ServerLlmRuntimeGateway(LlmRuntimeGateway):
"""GET /api/internal/agent/llm-runtime?companyId=&model=(Agent Bearer)。"""
def __init__(self, settings: Settings) -> None:
self._settings = settings
async def fetch(
self, company_id: int, 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 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
return LlmRuntimeConfig(
base_url=str(data.get("baseUrl") or "").rstrip("/"),
api_key=str(data.get("apiKey") or ""),
model=str(data.get("model") or ""),
extra_headers={
str(k): str(v)
for k, v in (data.get("extraHeaders") or {}).items()
},
context_window=_optional_positive_int(data.get("contextWindow")),
)
except Exception:
logger.exception(
"拉取 Server LLM runtime 失败 company_id=%s model=%s",
company_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