File size: 14,632 Bytes
eed1cab
5143557
 
 
 
eed1cab
5143557
 
 
 
 
eed1cab
 
 
 
 
 
 
 
5143557
 
 
eed1cab
5143557
 
 
eed1cab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5143557
 
 
 
 
 
 
 
 
 
eed1cab
 
5143557
 
 
 
 
eed1cab
 
 
5143557
eed1cab
 
 
 
5143557
 
 
eed1cab
 
5143557
eed1cab
 
 
 
5143557
eed1cab
 
 
 
 
 
 
5143557
 
 
eed1cab
5143557
 
eed1cab
 
 
 
 
5143557
 
 
 
 
 
 
 
 
 
eed1cab
5143557
 
 
 
eed1cab
5143557
eed1cab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5143557
 
eed1cab
5143557
 
 
 
 
 
 
 
 
 
eed1cab
 
 
5143557
 
 
 
 
 
eed1cab
 
 
5143557
 
 
 
 
 
eed1cab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""Minimal OpenAI-compatible clients for benchmark-only LLM baselines."""

from __future__ import annotations

import json
import logging
import time
from dataclasses import dataclass
from typing import cast

import httpx


class ProviderRequestError(RuntimeError):
    """Raised when a provider rejects a benchmark request payload."""


class ProviderRateLimitError(ProviderRequestError):
    """Raised when a provider asks us to wait longer than the configured cap."""


def _is_rate_limit_error(exc: BaseException) -> bool:
    """Return whether an exception is an HTTP 429 response."""
    return isinstance(exc, httpx.HTTPStatusError) and exc.response.status_code == 429


def _is_retryable_provider_error(exc: BaseException) -> bool:
    """Return whether an HTTP error is worth retrying for teacher collection."""
    return isinstance(exc, httpx.HTTPStatusError) and exc.response.status_code in {429, 503}


def _retry_after_s(exc: httpx.HTTPStatusError, *, fallback_s: float) -> float:
    """Return provider retry-after delay when present."""
    raw_retry_after = exc.response.headers.get("retry-after")
    if raw_retry_after is None:
        return fallback_s
    try:
        return max(float(raw_retry_after), fallback_s)
    except ValueError:
        return fallback_s


@dataclass(frozen=True, kw_only=True)
class GroqCompletion:
    """Completion payload plus conservative usage accounting."""

    text: str
    prompt_tokens: int
    completion_tokens: int
    warnings: tuple[str, ...]


class OpenAICompatBenchClient:
    """Sequential OpenAI-compatible client with fixed 429 retry and spacing."""

    def __init__(
        self,
        *,
        api_key: str,
        model: str,
        endpoint: str,
        provider: str,
        min_interval_s: float = 2.0,
        max_tokens: int = 512,
        max_retries: int = 5,
        max_retry_after_s: float = 120.0,
        timeout_s: float = 60.0,
    ) -> None:
        self._api_key = api_key
        self._model = model
        self._endpoint = endpoint
        self._provider = provider
        self._min_interval_s = min_interval_s
        self._max_tokens = max_tokens
        self._max_retries = max_retries
        self._max_retry_after_s = max_retry_after_s
        self._timeout_s = timeout_s
        self._last_success_at: float | None = None
        self._client = httpx.Client(
            timeout=self._timeout_s,
            headers={
                "Authorization": f"Bearer {self._api_key}",
                "Content-Type": "application/json",
            },
        )

    @property
    def model(self) -> str:
        """Return the configured provider model name."""
        return self._model

    @property
    def provider(self) -> str:
        """Return the configured provider identifier."""
        return self._provider

    def _respect_spacing(self) -> None:
        """Sleep long enough to keep requests sequential with a fixed gap."""
        if self._last_success_at is None:
            return
        elapsed = time.monotonic() - self._last_success_at
        remaining = self._min_interval_s - elapsed
        if remaining > 0:
            time.sleep(remaining)

    def _post(self, messages: list[dict[str, str]]) -> dict[str, object]:
        """Issue the underlying chat-completions request."""
        payload = {
            "model": self._model,
            "messages": messages,
            "temperature": 0.0,
            "max_tokens": self._max_tokens,
        }
        last_rate_limit_error: httpx.HTTPStatusError | None = None
        for attempt in range(self._max_retries):
            response: httpx.Response | None = None
            try:
                response = self._client.post(
                    self._endpoint,
                    json=payload,
                )
                response.raise_for_status()
            except httpx.HTTPStatusError as exc:
                if not _is_retryable_provider_error(exc) or attempt == self._max_retries - 1:
                    body = exc.response.text[:500].replace("\n", " ")
                    raise ProviderRequestError(
                        f"{self._provider} request rejected with HTTP "
                        f"{exc.response.status_code}: {body}"
                    ) from exc
                last_rate_limit_error = exc
                retry_s = _retry_after_s(exc, fallback_s=2.0 * (attempt + 1))
                if retry_s > self._max_retry_after_s:
                    body = exc.response.text[:500].replace("\n", " ")
                    raise ProviderRateLimitError(
                        f"{self._provider} rate limit retry-after {retry_s:.2f}s "
                        f"exceeds cap {self._max_retry_after_s:.2f}s: {body}"
                    ) from exc
                logging.getLogger("dataforge.bench.groq_client").warning(
                    "%s_rate_limit attempt=%d retry_after_s=%.2f",
                    self._provider,
                    attempt + 1,
                    retry_s,
                )
                time.sleep(retry_s)
                continue
            except httpx.TimeoutException as exc:
                raise TimeoutError(
                    f"{self._provider} request timed out after {self._timeout_s:.1f} seconds."
                ) from exc
            return dict(response.json())
        if last_rate_limit_error is not None:
            raise last_rate_limit_error
        raise RuntimeError(f"{self._provider} request failed without a response.")

    def complete(self, messages: list[dict[str, str]]) -> GroqCompletion:
        """Send one benchmark completion request to the configured provider."""
        self._respect_spacing()
        payload = self._post(messages)
        self._last_success_at = time.monotonic()

        warnings: list[str] = []
        usage = payload.get("usage", {})
        prompt_tokens = int(usage.get("prompt_tokens", 0)) if isinstance(usage, dict) else 0
        completion_tokens = int(usage.get("completion_tokens", 0)) if isinstance(usage, dict) else 0
        if not usage:
            warnings.append("missing_usage_payload")
            logging.getLogger("dataforge.bench.groq_client").warning(
                "%s_missing_usage_payload", self._provider
            )

        try:
            choices = cast(list[dict[str, object]], payload["choices"])
            message = cast(dict[str, object], choices[0]["message"])
            content = str(message["content"])
        except (KeyError, IndexError, TypeError) as exc:
            raise ValueError(
                f"Unexpected {self._provider} response payload: {json.dumps(payload)}"
            ) from exc
        return GroqCompletion(
            text=content,
            prompt_tokens=prompt_tokens,
            completion_tokens=completion_tokens,
            warnings=tuple(warnings),
        )


class GroqBenchClient(OpenAICompatBenchClient):
    """Sequential Groq client with fixed 429 retry and spacing."""

    def __init__(
        self,
        *,
        api_key: str,
        model: str = "llama-3.3-70b-versatile",
        min_interval_s: float = 2.0,
        max_tokens: int = 512,
        max_retries: int = 5,
        max_retry_after_s: float = 120.0,
        timeout_s: float = 60.0,
    ) -> None:
        super().__init__(
            api_key=api_key,
            model=model,
            endpoint="https://api.groq.com/openai/v1/chat/completions",
            provider="groq",
            min_interval_s=min_interval_s,
            max_tokens=max_tokens,
            max_retries=max_retries,
            max_retry_after_s=max_retry_after_s,
            timeout_s=timeout_s,
        )


class CerebrasBenchClient(OpenAICompatBenchClient):
    """Sequential Cerebras client with fixed 429 retry and spacing."""

    def __init__(
        self,
        *,
        api_key: str,
        model: str = "qwen-3-235b-a22b-instruct-2507",
        min_interval_s: float = 0.5,
        max_tokens: int = 512,
        max_retries: int = 5,
        max_retry_after_s: float = 120.0,
        timeout_s: float = 60.0,
    ) -> None:
        super().__init__(
            api_key=api_key,
            model=model,
            endpoint="https://api.cerebras.ai/v1/chat/completions",
            provider="cerebras",
            min_interval_s=min_interval_s,
            max_tokens=max_tokens,
            max_retries=max_retries,
            max_retry_after_s=max_retry_after_s,
            timeout_s=timeout_s,
        )


class GeminiBenchClient:
    """Sequential Gemini client adapted to the benchmark completion interface."""

    def __init__(
        self,
        *,
        api_key: str,
        model: str = "gemini-3.1-pro-preview",
        min_interval_s: float = 2.0,
        max_tokens: int = 512,
        max_retries: int = 5,
        max_retry_after_s: float = 120.0,
        timeout_s: float = 60.0,
    ) -> None:
        self._api_key = api_key
        self._model = model.removeprefix("models/")
        self._min_interval_s = min_interval_s
        self._max_tokens = max_tokens
        self._max_retries = max_retries
        self._max_retry_after_s = max_retry_after_s
        self._timeout_s = timeout_s
        self._last_success_at: float | None = None
        self._client = httpx.Client(
            timeout=self._timeout_s,
            headers={"Content-Type": "application/json"},
        )

    @property
    def model(self) -> str:
        """Return the configured Gemini model name."""
        return self._model

    @property
    def provider(self) -> str:
        """Return the provider identifier."""
        return "gemini"

    def _respect_spacing(self) -> None:
        """Sleep long enough to keep requests sequential with a fixed gap."""
        if self._last_success_at is None:
            return
        elapsed = time.monotonic() - self._last_success_at
        remaining = self._min_interval_s - elapsed
        if remaining > 0:
            time.sleep(remaining)

    def _payload(self, messages: list[dict[str, str]]) -> dict[str, object]:
        """Convert OpenAI-style chat messages to Gemini generateContent payload."""
        system_texts: list[str] = []
        contents: list[dict[str, object]] = []
        for message in messages:
            role = message.get("role", "user")
            content = message.get("content", "")
            if role == "system":
                system_texts.append(content)
                continue
            gemini_role = "model" if role == "assistant" else "user"
            contents.append({"role": gemini_role, "parts": [{"text": content}]})

        payload: dict[str, object] = {
            "contents": contents,
            "generationConfig": {
                "temperature": 0.0,
                "maxOutputTokens": self._max_tokens,
            },
        }
        if system_texts:
            payload["systemInstruction"] = {
                "parts": [{"text": "\n\n".join(system_texts)}],
            }
        return payload

    def _post(self, messages: list[dict[str, str]]) -> dict[str, object]:
        """Issue the underlying Gemini generateContent request."""
        endpoint = (
            f"https://generativelanguage.googleapis.com/v1beta/models/{self._model}:generateContent"
        )
        last_rate_limit_error: httpx.HTTPStatusError | None = None
        for attempt in range(self._max_retries):
            response: httpx.Response | None = None
            try:
                response = self._client.post(
                    endpoint,
                    params={"key": self._api_key},
                    json=self._payload(messages),
                )
                response.raise_for_status()
            except httpx.HTTPStatusError as exc:
                if not _is_retryable_provider_error(exc) or attempt == self._max_retries - 1:
                    body = exc.response.text[:500].replace("\n", " ")
                    raise ProviderRequestError(
                        f"gemini request rejected with HTTP {exc.response.status_code}: {body}"
                    ) from exc
                last_rate_limit_error = exc
                retry_s = _retry_after_s(exc, fallback_s=2.0 * (attempt + 1))
                if retry_s > self._max_retry_after_s:
                    body = exc.response.text[:500].replace("\n", " ")
                    raise ProviderRateLimitError(
                        f"gemini rate limit retry-after {retry_s:.2f}s "
                        f"exceeds cap {self._max_retry_after_s:.2f}s: {body}"
                    ) from exc
                logging.getLogger("dataforge.bench.groq_client").warning(
                    "gemini_rate_limit attempt=%d retry_after_s=%.2f",
                    attempt + 1,
                    retry_s,
                )
                time.sleep(retry_s)
                continue
            except httpx.TimeoutException as exc:
                raise TimeoutError(
                    f"gemini request timed out after {self._timeout_s:.1f} seconds."
                ) from exc
            return dict(response.json())
        if last_rate_limit_error is not None:
            raise last_rate_limit_error
        raise RuntimeError("gemini request failed without a response.")

    def complete(self, messages: list[dict[str, str]]) -> GroqCompletion:
        """Send one benchmark completion request to Gemini."""
        self._respect_spacing()
        payload = self._post(messages)
        self._last_success_at = time.monotonic()

        warnings: list[str] = []
        usage = payload.get("usageMetadata", {})
        prompt_tokens = int(usage.get("promptTokenCount", 0)) if isinstance(usage, dict) else 0
        completion_tokens = (
            int(usage.get("candidatesTokenCount", 0)) if isinstance(usage, dict) else 0
        )
        if not usage:
            warnings.append("missing_usage_payload")
            logging.getLogger("dataforge.bench.groq_client").warning("gemini_missing_usage_payload")

        try:
            candidates = cast(list[dict[str, object]], payload["candidates"])
            content = cast(dict[str, object], candidates[0]["content"])
            parts = cast(list[dict[str, object]], content["parts"])
            text = "".join(str(part.get("text", "")) for part in parts)
        except (KeyError, IndexError, TypeError) as exc:
            raise ValueError(f"Unexpected gemini response payload: {json.dumps(payload)}") from exc
        return GroqCompletion(
            text=text,
            prompt_tokens=prompt_tokens,
            completion_tokens=completion_tokens,
            warnings=tuple(warnings),
        )