Lara Monteagudo Tubau
fix: circuit breaker resilience, Drive save on every persist, remove local upload
7070b94 Download llm_client.py from pylxi/script: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/pylxi/script/resolve/main/llm_client.py
- Command line
-
hf download hf://spaces/pylxi/script/llm_client.py
-
curl -L -o llm_client.py https://huggingface.co/spaces/pylxi/script/resolve/main/llm_client.py
11.2 kB
| """ | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| 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 | |
| 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.") | |
| 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() | |