farient-deckcheck / services /rate_limit.py
Xander Labide
Claude Opus 4.7 (1M context)
Initial commit β€” Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
8.58 kB
"""Sliding-window token rate limiter for OpenAI API calls.
The OpenAI API enforces a per-minute token budget (TPM) per model. When
parallel agents fire calls concurrently we can exceed the cap and start
collecting 429s. This module implements a process-local async limiter
that tracks tokens consumed in the last 60 seconds via a deque of
(timestamp, tokens) entries and blocks ``acquire`` until capacity is
available.
A single :class:`TokenRateLimiter` instance can manage multiple models
simultaneously (each model has its own deque + budget); callers pass
``model`` into ``acquire`` / ``record`` so the right window is consulted.
Why a custom sliding-window vs. a token-bucket?
-----------------------------------------------
The OpenAI quota itself is a sliding window β€” a token-bucket can either
under-utilise (when the window is loose) or over-shoot at the start of
a new window. Sliding-window is the closest model to the actual cap.
Estimates vs. actuals
---------------------
``acquire`` takes an *estimated* token count. After the call returns,
callers should invoke :meth:`record` with the actual ``response.usage.
total_tokens`` for accuracy. If actuals come in higher than estimates,
the next caller automatically waits longer; if lower, the next caller
gets through sooner.
Configuration
-------------
Defaults are tuned for the demo's models (GPT-4o ~30k TPM, gpt-4o-mini
~200k TPM) with 5k headroom to absorb estimate slippage. Override via
``OPENAI_TPM_BUDGET`` (gpt-4o) and ``OPENAI_TPM_BUDGET_MINI`` (mini).
"""
from __future__ import annotations
import asyncio
import logging
import os
import time
from collections import deque
from typing import Deque
logger = logging.getLogger(__name__)
# Sliding window length β€” the OpenAI cap is per-minute.
WINDOW_SECONDS: float = 60.0
# Per-call token estimates. These are upper bounds we observed on the
# Jacobs deck (33-slide audit produced ~2k tokens/slide review and
# ~12k for deck consistency). Override with environment vars.
def _int_env(key: str, default: int) -> int:
raw = os.environ.get(key, "")
if not raw:
return default
try:
return int(raw)
except ValueError:
logger.warning("Invalid %s=%r β€” falling back to %d", key, raw, default)
return default
SLIDE_REVIEW_EST_TOKENS: int = _int_env("OPENAI_SLIDE_REVIEW_EST_TOKENS", 2000)
DECK_CONSISTENCY_EST_TOKENS: int = _int_env(
"OPENAI_DECK_CONSISTENCY_EST_TOKENS", 12000
)
LEAD_AUDITOR_EST_TOKENS: int = _int_env("OPENAI_LEAD_AUDITOR_EST_TOKENS", 8000)
def _default_budget(model: str) -> int:
"""Resolve a TPM budget for *model*.
Looks up env overrides first; else falls back to a sensible per-family
default. The defaults intentionally leave 5k headroom under the public
OpenAI caps so estimate slippage doesn't trigger 429s.
"""
m = model.lower()
# Mini family: gpt-4o-mini, gpt-5-mini, etc. β€” typically 200k TPM.
if "mini" in m or "haiku" in m or "nano" in m:
return _int_env("OPENAI_TPM_BUDGET_MINI", 180_000)
# Default for full-size models (gpt-4o, gpt-5, etc.) β€” 30k TPM cap.
return _int_env("OPENAI_TPM_BUDGET", 25_000)
class TokenRateLimiter:
"""Async, multi-model sliding-window TPM limiter.
Thread-safe within a single asyncio event loop. Not safe across
processes β€” that's fine, the audit pipeline runs in one uvicorn worker.
Usage::
limiter = TokenRateLimiter()
await limiter.acquire(model="gpt-4o", tokens=2000)
# ... call OpenAI ...
limiter.record(model="gpt-4o", tokens=actual_total_tokens)
"""
def __init__(
self,
*,
budgets: dict[str, int] | None = None,
time_fn=time.monotonic,
sleep=asyncio.sleep,
) -> None:
# The optional ``budgets`` mapping lets tests inject a known map;
# production resolves on-demand via ``_default_budget``.
self._budget_overrides: dict[str, int] = dict(budgets or {})
self._windows: dict[str, Deque[tuple[float, int]]] = {}
self._lock = asyncio.Lock()
self._time_fn = time_fn
self._sleep = sleep
# -- public API ---------------------------------------------------------
def budget_for(self, model: str) -> int:
"""Return the TPM budget for *model* (override > default)."""
if model in self._budget_overrides:
return self._budget_overrides[model]
return _default_budget(model)
def current_usage(self, model: str) -> int:
"""Return tokens consumed in the last :data:`WINDOW_SECONDS`."""
window = self._windows.get(model)
if not window:
return 0
cutoff = self._time_fn() - WINDOW_SECONDS
# Lazy eviction β€” cheap because deques are O(1) at both ends.
while window and window[0][0] < cutoff:
window.popleft()
return sum(t for _, t in window)
async def acquire(self, *, model: str, tokens: int) -> None:
"""Block until *tokens* fits within the *model*'s sliding window.
Reserves the slot eagerly: once ``acquire`` returns, the caller
owns those tokens for the next 60 seconds. After the API call
completes, callers should invoke :meth:`record` to swap the
reservation for the actual usage.
"""
if tokens <= 0:
return
budget = self.budget_for(model)
wait_started_at: float | None = None
while True:
async with self._lock:
window = self._windows.setdefault(model, deque())
cutoff = self._time_fn() - WINDOW_SECONDS
while window and window[0][0] < cutoff:
window.popleft()
used = sum(t for _, t in window)
if used + tokens <= budget:
# Reserve the slot now so concurrent acquirers see it.
window.append((self._time_fn(), tokens))
if wait_started_at is not None:
waited = self._time_fn() - wait_started_at
if waited > 1.0:
logger.info(
"rate-limit: waited %.1fs for %dk tokens (model=%s)",
waited, tokens // 1000, model,
)
return
# Otherwise compute time until the oldest entry ages out.
if window:
oldest_ts = window[0][0]
sleep_for = max(0.05, (oldest_ts + WINDOW_SECONDS) - self._time_fn())
else:
# No history but the request alone exceeds budget β€” fail
# loud rather than wait forever.
raise ValueError(
f"rate-limit: single request ({tokens} tokens) "
f"exceeds budget ({budget}) for model {model!r}"
)
if wait_started_at is None:
wait_started_at = self._time_fn()
# Cap individual sleep slices so we recheck regularly (handles
# case where another caller's record() shrinks the window).
await self._sleep(min(sleep_for, 5.0))
def record(self, *, model: str, tokens: int) -> None:
"""Append a usage entry without blocking.
Use this when actual usage comes in higher than the estimate
passed to :meth:`acquire` β€” appending the *delta* keeps the window
accurate. If actual <= estimate, no need to call this.
"""
if tokens <= 0:
return
window = self._windows.setdefault(model, deque())
window.append((self._time_fn(), tokens))
# ---------------------------------------------------------------------------
# Process-global default
# ---------------------------------------------------------------------------
_default_limiter: TokenRateLimiter | None = None
def get_default_limiter() -> TokenRateLimiter:
"""Return the process-global :class:`TokenRateLimiter` (lazy)."""
global _default_limiter
if _default_limiter is None:
_default_limiter = TokenRateLimiter()
return _default_limiter
def reset_default_limiter() -> None:
"""Drop the process-global limiter (test seam)."""
global _default_limiter
_default_limiter = None
__all__ = [
"DECK_CONSISTENCY_EST_TOKENS",
"LEAD_AUDITOR_EST_TOKENS",
"SLIDE_REVIEW_EST_TOKENS",
"TokenRateLimiter",
"WINDOW_SECONDS",
"get_default_limiter",
"reset_default_limiter",
]