File size: 4,630 Bytes
7c188b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""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