Thread lock 2
Browse files35 unmodified lines3637383940414243444546474849505110 unmodified lines62636465666735 unmodified lines# outbound OpenRouter calls behind a single lock and enforce a minimum gap# between them. Whichever request arrives second simply waits its turn.# ---------------------------------------------------------------------------MIN_INTERVAL_SECONDS = float(os.environ.get("OPENROUTER_MIN_INTERVAL", "2.0"))_or_lock = threading.Lock()_last_call_time = 0.0def call_openrouter(payload: dict, headers: dict, timeout: int = 20):"""Thread-safe, rate-limited call to OpenRouter's chat completions endpoint.Ensures at least MIN_INTERVAL_SECONDS has elapsed since the previousOpenRouter call (across ALL endpoints) before firing this one."""global _last_call_time10 unmodified linesresponse = requests.post(url, headers=headers, json=payload, timeout=timeout)_last_call_time = time.monotonic()return response35 unmodified lines363738394041424344454647484950515253545556575859606162636465666710 unmodified lines7879808182838485868788899091929335 unmodified lines# outbound OpenRouter calls behind a single lock and enforce a minimum gap# between them. Whichever request arrives second simply waits its turn.# ---------------------------------------------------------------------------MIN_INTERVAL_SECONDS = float(os.environ.get("OPENROUTER_MIN_INTERVAL", "6.0"))MAX_RETRIES = int(os.environ.get("OPENROUTER_MAX_RETRIES", "3"))RETRY_BACKOFF_SECONDS = float(os.environ.get("OPENROUTER_RETRY_BACKOFF", "5.0"))_or_lock = threading.Lock()_last_call_time = 0.0def _is_rate_limited(response: requests.Response) -> bool:"""Detect a 429 whether it comes as an HTTP status or embedded in a 200 body(OpenRouter sometimes returns 200 with {"error": {"code": 429, ...}})."""if response.status_code == 429:return Truetry:body = response.json()except ValueError:return Falsereturn isinstance(body, dict) and body.get("error", {}).get("code") == 429def call_openrouter(payload: dict, headers: dict, timeout: int = 20):"""Thread-safe, rate-limited call to OpenRouter's chat completions endpoint.- Ensures at least MIN_INTERVAL_SECONDS has elapsed since the previousOpenRouter call (across ALL endpoints) before firing this one.- If the provider still returns a 429 (as a status code or embedded in theJSON body), retries with exponential backoff up to MAX_RETRIES times."""global _last_call_time10 unmodified linesresponse = requests.post(url, headers=headers, json=payload, timeout=timeout)_last_call_time = time.monotonic()attempt = 0while _is_rate_limited(response) and attempt < MAX_RETRIES:backoff = RETRY_BACKOFF_SECONDS * (2 ** attempt)logger.warning(f"OpenRouter rate limited (attempt {attempt + 1}/{MAX_RETRIES}); "f"backing off {backoff:.1f}s before retry")time.sleep(backoff)response = requests.post(url, headers=headers, json=payload, timeout=timeout)_last_call_time = time.monotonic()attempt += 1return response
app.py+29-3