Spaces:
Sleeping

File size: 11,199 Bytes
5b5a20d
 
 
d176097
5b5a20d
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
d176097
 
5b5a20d
 
d176097
 
 
 
 
5b5a20d
 
d176097
 
 
 
 
 
 
 
 
7070b94
 
 
 
d176097
7070b94
 
 
d176097
7070b94
 
 
 
 
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7070b94
d176097
7070b94
 
 
 
d176097
 
 
 
 
 
 
7070b94
 
 
 
 
 
 
 
d176097
 
 
 
5b5a20d
d176097
 
5b5a20d
 
d176097
 
 
5b5a20d
d176097
 
 
 
 
 
 
 
 
5b5a20d
 
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
d176097
 
 
 
 
 
 
 
 
 
5b5a20d
d176097
 
 
 
 
 
5b5a20d
d176097
 
 
 
 
 
 
 
5b5a20d
 
 
 
d176097
 
 
 
 
 
 
 
5b5a20d
d176097
5b5a20d
 
 
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
d176097
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
d176097
7070b94
 
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7070b94
 
 
 
 
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
"""
llm_client.py
-------------
Shared LLM client with instrumentation, adaptive timeout, and circuit breaker.

Model: Qwen/Qwen2.5-72B-Instruct via Hugging Face Inference API.
Requires HF_TOKEN environment variable.

Design references
-----------------
Adaptive timeout:
  The Fallacies of Distributed Computing (Deutsch, 1994) β€” network calls
  will fail; callers must not assume a fixed latency. Timeout is a
  function of expected payload, not a constant.

Circuit breaker pattern:
  Nygard, M. (2007). Release It! Design and Deploy Production-Ready
  Software. Pragmatic Bookshelf.
  β€” After N consecutive failures, open the circuit so callers fail fast
    rather than accumulating threads waiting on a dead service.

Exponential backoff with jitter:
  Marc Brooker (2015). "Exponential Backoff And Jitter." AWS Architecture Blog.
  β€” Prevents thundering-herd retry storms under load.

Stats / observability:
  Sigelman et al. (2010). Dapper: A Large-Scale Distributed Systems
  Tracing Infrastructure. Google Technical Report.
  β€” Every meaningful call should carry timing and size metadata.
"""

from __future__ import annotations

import os
import time
import random
import threading
from dataclasses import dataclass, field
from typing import Optional

from huggingface_hub import InferenceClient

MODEL       = "Qwen/Qwen2.5-72B-Instruct"
TEMPERATURE = 0.1

# Timeout bounds (seconds)
_TIMEOUT_MIN     = 45
_TIMEOUT_MAX     = 300
_CHARS_PER_SEC   = 800   # empirical chars-per-second at Qwen 72B on HF inference

# Circuit breaker
# Threshold raised to 8 so parallel section runs (up to 6 sections Γ— 1 retry)
# don't trip the breaker due to a single burst of transient rate-limit errors.
_CB_FAILURE_THRESHOLD = 8
_CB_RESET_SECS        = 90  # seconds before trying again

# Retry policy β€” more retries with longer first backoff to survive HF rate limits
_MAX_RETRIES     = 4
_RETRY_BASE_SECS = 8   # first backoff 8s β†’ 16s β†’ 32s (+ jitter)

# Transient codes that trigger backoff (not circuit failure)
# 429 = rate limit β€” always retry with backoff, never count as circuit failure
_TRANSIENT_CODES       = ("504", "503", "502", "429", "timeout", "Timeout",
                           "rate limit", "Rate limit", "overloaded")
_RATE_LIMIT_CODES      = ("429", "rate limit", "Rate limit")


# ---------------------------------------------------------------------------
# Return type
# ---------------------------------------------------------------------------

@dataclass
class LLMCallStats:
    """Instrumentation record for a single LLM call."""
    model:              str
    temperature:        float
    system_chars:       int
    user_chars:         int
    response_chars:     int
    estimated_in_tok:   int       # rough: chars / 4
    estimated_out_tok:  int
    timeout_used_s:     int
    wall_time_s:        float
    retries:            int
    success:            bool
    error:              Optional[str] = None

    @property
    def estimated_total_tok(self) -> int:
        return self.estimated_in_tok + self.estimated_out_tok


# ---------------------------------------------------------------------------
# Circuit breaker (per-process singleton)
# ---------------------------------------------------------------------------

class _CircuitBreaker:
    """
    Three-state finite state machine:
      CLOSED   β€” normal operation
      OPEN     β€” refusing calls (too many consecutive failures)
      HALF_OPENβ€” one probe call allowed to test recovery
    """
    def __init__(self):
        self._lock         = threading.Lock()
        self._failures     = 0
        self._state        = "CLOSED"   # CLOSED | OPEN | HALF_OPEN
        self._opened_at: Optional[float] = None

    def allow_call(self) -> bool:
        with self._lock:
            if self._state == "CLOSED":
                return True
            if self._state == "OPEN":
                if time.monotonic() - self._opened_at >= _CB_RESET_SECS:
                    self._state = "HALF_OPEN"
                    print(f"[LLM] Circuit half-open β€” probe call allowed.")
                    return True
                return False
            # HALF_OPEN
            return True

    def record_success(self):
        with self._lock:
            self._failures = 0
            if self._state != "CLOSED":
                print(f"[LLM] Circuit closed β€” service recovered.")
            self._state = "CLOSED"

    def record_failure(self, is_rate_limit: bool = False):
        with self._lock:
            # Rate-limit errors are expected under load β€” don't count toward circuit opening
            if is_rate_limit:
                print(f"[LLM] Rate-limit hit β€” not counting toward circuit breaker.")
                return
            self._failures += 1
            if self._failures >= _CB_FAILURE_THRESHOLD and self._state != "OPEN":
                self._state     = "OPEN"
                self._opened_at = time.monotonic()
                print(f"[LLM] Circuit OPENED after {self._failures} consecutive failures. "
                      f"Will retry in {_CB_RESET_SECS}s.")

    def reset(self):
        """Reset the circuit breaker β€” call at the start of each user-initiated pipeline run."""
        with self._lock:
            self._failures  = 0
            self._state     = "CLOSED"
            self._opened_at = None
        print("[LLM] Circuit breaker reset for new run.")

    @property
    def state(self) -> str:
        return self._state


_circuit_breaker = _CircuitBreaker()
_client: Optional[InferenceClient] = None


# ---------------------------------------------------------------------------
# Client factory
# ---------------------------------------------------------------------------

def _get_client(timeout_s: int) -> InferenceClient:
    """Create a new client per call so timeout is respected per-request."""
    token = os.environ.get("HF_TOKEN")
    if not token:
        raise RuntimeError(
            "HF_TOKEN environment variable is not set. "
            "Get a token at huggingface.co/settings/tokens."
        )
    return InferenceClient(model=MODEL, token=token, timeout=timeout_s)


# ---------------------------------------------------------------------------
# Adaptive timeout
# ---------------------------------------------------------------------------

def compute_timeout(system_prompt: str, user_prompt: str, max_tokens: int) -> int:
    """
    Scale timeout to expected payload size.

    Formula:
      timeout = input_chars / chars_per_sec + max_tokens / tok_per_sec + buffer
    where chars_per_sec and tok_per_sec are empirical constants for Qwen 72B on HF.

    Clipped to [_TIMEOUT_MIN, _TIMEOUT_MAX].
    """
    input_chars  = len(system_prompt) + len(user_prompt)
    # Estimate generation time: ~40 tokens/sec for 72B on HF shared inference
    gen_secs     = max_tokens / 40
    # Estimate prefill time: ~800 chars/sec
    prefill_secs = input_chars / _CHARS_PER_SEC
    raw = prefill_secs + gen_secs + 15   # 15s network + queuing buffer
    return int(min(max(raw, _TIMEOUT_MIN), _TIMEOUT_MAX))


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def call_llm(system_prompt: str, user_prompt: str, max_tokens: int = 4000) -> str:
    """Backwards-compatible wrapper: returns response text only."""
    text, _ = call_llm_timed(system_prompt, user_prompt, max_tokens)
    return text


def call_llm_timed(
    system_prompt: str,
    user_prompt:   str,
    max_tokens:    int = 4000,
) -> tuple[str, LLMCallStats]:
    """
    Call the LLM and return (response_text, stats).

    Implements:
      - Adaptive timeout based on payload size
      - Exponential backoff with jitter on transient errors
      - Circuit breaker to fail fast when service is down
    """
    if not _circuit_breaker.allow_call():
        raise RuntimeError(
            f"LLM circuit breaker is OPEN (too many consecutive failures). "
            f"Will auto-reset in {_CB_RESET_SECS}s. Check HF service status."
        )

    timeout_s = compute_timeout(system_prompt, user_prompt, max_tokens)
    messages  = [
        {"role": "system", "content": system_prompt},
        {"role": "user",   "content": user_prompt},
    ]

    sys_chars  = len(system_prompt)
    user_chars = len(user_prompt)
    est_in     = (sys_chars + user_chars) // 4

    t0 = time.perf_counter()
    last_error: Optional[str] = None

    for attempt in range(_MAX_RETRIES):
        try:
            client   = _get_client(timeout_s)
            response = client.chat.completions.create(
                messages=messages,
                max_tokens=max_tokens,
                temperature=TEMPERATURE,
            )
            text = response.choices[0].message.content
            wall = round(time.perf_counter() - t0, 2)
            _circuit_breaker.record_success()

            stats = LLMCallStats(
                model=MODEL, temperature=TEMPERATURE,
                system_chars=sys_chars, user_chars=user_chars,
                response_chars=len(text),
                estimated_in_tok=est_in,
                estimated_out_tok=len(text) // 4,
                timeout_used_s=timeout_s,
                wall_time_s=wall,
                retries=attempt,
                success=True,
            )
            return text, stats

        except Exception as exc:
            last_error = str(exc)
            is_transient = any(code in last_error for code in _TRANSIENT_CODES)

            if attempt < _MAX_RETRIES - 1 and is_transient:
                # Exponential backoff with Β±25% jitter (Brooker 2015)
                base_wait = _RETRY_BASE_SECS * (2 ** attempt)
                wait      = base_wait * (0.75 + random.random() * 0.5)
                print(f"[LLM] Transient error (attempt {attempt + 1}/{_MAX_RETRIES}), "
                      f"retrying in {wait:.1f}s… ({last_error[:80]})")
                time.sleep(wait)
                continue

            is_rate_limit = any(c in last_error for c in _RATE_LIMIT_CODES)
            _circuit_breaker.record_failure(is_rate_limit=is_rate_limit)
            wall = round(time.perf_counter() - t0, 2)
            stats = LLMCallStats(
                model=MODEL, temperature=TEMPERATURE,
                system_chars=sys_chars, user_chars=user_chars,
                response_chars=0,
                estimated_in_tok=est_in, estimated_out_tok=0,
                timeout_used_s=timeout_s,
                wall_time_s=wall,
                retries=attempt + 1,
                success=False,
                error=last_error,
            )
            raise RuntimeError(
                f"LLM call failed after {attempt + 1} attempt(s): {last_error}"
            ) from exc

    # Should not reach here
    raise RuntimeError(f"LLM call exhausted retries: {last_error}")


def circuit_state() -> str:
    """Expose circuit breaker state for the UI transparency panel."""
    return _circuit_breaker.state


def reset_circuit() -> None:
    """Reset circuit breaker before a new user-initiated pipeline run."""
    _circuit_breaker.reset()