"""从 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=…(Agent Bearer)。""" def __init__(self, settings: Settings) -> None: self._settings = settings async def fetch(self, company_id: int) -> LlmRuntimeConfig | None: url = f"{self._settings.server_base_url.rstrip('/')}/api/internal/agent/llm-runtime" headers = {"Authorization": f"Bearer {self._settings.mcp_bearer_token}"} try: async with httpx.AsyncClient(timeout=15.0) as client: resp = await client.get( url, params={"companyId": company_id}, 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() }, ) except Exception: logger.exception("拉取 Server LLM runtime 失败 company_id=%s", company_id) return None