"""OpenAI-compatible client for a network-hosted vLLM server. Responsibilities: * discover the model registry (GET /models) and freeze it into the run manifest * issue chat completions with bounded retries and global concurrency limiting * measure wall-clock latency and capture token usage for every call * never raise on model failure: return a structured error record instead, so the harness can log it as an F7-relevant event """ from __future__ import annotations import json import threading import time import urllib.request import urllib.error from dataclasses import dataclass, field, asdict from typing import Any, Optional @dataclass class CallResult: ok: bool text: str = "" error: str = "" latency_s: float = 0.0 prompt_tokens: int = 0 completion_tokens: int = 0 model: str = "" attempts: int = 0 raw: Optional[dict] = None @dataclass class LLMClient: base_url: str api_key: str = "EMPTY" timeout_s: float = 180.0 max_retries: int = 3 retry_backoff_s: float = 2.0 max_concurrency: int = 8 _sem: threading.Semaphore = field(init=False, repr=False) def __post_init__(self) -> None: self.base_url = self.base_url.rstrip("/") self._sem = threading.Semaphore(self.max_concurrency) # ---------------------------------------------------------------- models def list_models(self) -> list[dict[str, Any]]: req = urllib.request.Request( f"{self.base_url}/models", headers={"Authorization": f"Bearer {self.api_key}"}, ) with urllib.request.urlopen(req, timeout=self.timeout_s) as resp: payload = json.loads(resp.read().decode("utf-8")) return payload.get("data", []) # ------------------------------------------------------------------ chat def chat( self, model: str, messages: list[dict[str, str]], temperature: float = 0.7, top_p: float = 0.95, max_tokens: int = 1024, seed: Optional[int] = None, ) -> CallResult: body: dict[str, Any] = { "model": model, "messages": messages, "temperature": temperature, "top_p": top_p, "max_tokens": max_tokens, } if seed is not None: body["seed"] = seed data = json.dumps(body).encode("utf-8") last_err = "" for attempt in range(1, self.max_retries + 1): t0 = time.monotonic() try: with self._sem: req = urllib.request.Request( f"{self.base_url}/chat/completions", data=data, headers={ "Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}", }, method="POST", ) with urllib.request.urlopen(req, timeout=self.timeout_s) as resp: payload = json.loads(resp.read().decode("utf-8")) latency = time.monotonic() - t0 choice = payload["choices"][0] usage = payload.get("usage", {}) or {} return CallResult( ok=True, text=choice["message"].get("content") or "", latency_s=latency, prompt_tokens=int(usage.get("prompt_tokens", 0)), completion_tokens=int(usage.get("completion_tokens", 0)), model=model, attempts=attempt, raw=None, # set to payload for full-fidelity debugging runs ) except urllib.error.HTTPError as e: try: detail = e.read().decode("utf-8")[:500] except Exception: detail = "" last_err = f"HTTP {e.code}: {detail}" # 4xx other than 429 will not improve on retry if e.code < 500 and e.code != 429: break except Exception as e: # timeouts, connection resets, bad JSON last_err = f"{type(e).__name__}: {e}" time.sleep(self.retry_backoff_s * attempt) return CallResult( ok=False, error=last_err, latency_s=time.monotonic() - t0, model=model, attempts=self.max_retries, ) def to_dict(self, r: CallResult) -> dict: d = asdict(r) d.pop("raw", None) return d