Skip to main content

A thread-safe and async rate limiter for Gemini and OpenAI models.

Project description

llm-limiters

A lightweight, provider-aware rate-limiting library for LLM text, image, and live (streaming) models, supporting Gemini and OpenAI with tier-based quotas, fallbacks, and custom overrides.

Designed for:

  • API gateways
  • Backend services
  • Agent systems
  • Multi-model routing with hard quota enforcement

Features

  • Tier-based rate limiting (free, tier1, tier2, …)
  • Gemini and OpenAI support
  • Text, Image, and Live (WebSocket) limiters
  • RPM / TPM / RPD enforcement
  • Automatic cooldown on quota and 429 errors
  • Model-priority fallback
  • Custom per-model overrides
  • Thread-safe (sync and async)

Installation

pip install llm-limiters

Quick Start

Import

from llm_limiters import RateLimiter
from llm_limiters.live import LiveRateLimiter
from llm_limiters.image import ImageRateLimiter

Text Model Rate Limiting (Gemini + OpenAI)

Create a limiter

limiter = RateLimiter(tier="free")

Use with model fallback

@limiter.limit([
    "gemini-2.5-flash",
    "gpt-4o-mini"
])
def generate_text(prompt: str, model_name: str):
    return client.generate(
        model=model_name,
        prompt=prompt
    )
  • Enforces RPM, TPM, and RPD
  • Falls back to the next model when limits are reached
  • Applies cooldowns automatically on rate-limit errors

Image Generation Rate Limiting

Supports

  • Gemini Image / Imagen models
  • OpenAI gpt-image-1, gpt-image-1-mini

Image generation requires billing (no free tier).

Create an image limiter

image_limiter = ImageRateLimiter(tier="tier1")

Use with priority routing

@image_limiter.limit([
    "gpt-image-1-mini",
    "gpt-image-1",
    "gemini-2.5-flash-preview-image",
    "imagen-4.0-fast-generate"
])
def generate_image(prompt: str, model_name: str):
    if model_name.startswith("gpt-image"):
        return openai.images.generate(
            model=model_name,
            prompt=prompt
        )
    else:
        return gemini.images.generate(
            model=model_name,
            prompt=prompt
        )
  • RPM enforced for all image models
  • TPM enforced for OpenAI image models
  • RPD enforced for Gemini / Imagen models
  • Automatic cooldown on quota errors

Live / Streaming Rate Limiter (Async)

Designed for:

  • WebSockets
  • Audio and real-time Gemini Live models

Create a live limiter

live_limiter = LiveRateLimiter(tier="free")

Check availability before starting a session

allowed, reason = await live_limiter.check_availability(
    "gemini-2.0-flash-live-001"
)

if not allowed:
    raise Exception(reason)

Track usage

await live_limiter.acquire_session(model)
await live_limiter.record_token_usage(model, token_count)

Trigger cooldown on provider rate-limit

await live_limiter.trigger_cooldown(model, wait_seconds=60)

Custom Limits and Overrides

Custom limits can override tier defaults or add new models.

Override a single model

limiter = ImageRateLimiter(
    tier="tier2",
    custom_limits={
        "gpt-image-1": {
            "rpm": 100,
            "tpm": 500_000,
            "rpd": 0
        }
    }
)

Add a custom or internal model

limiter = ImageRateLimiter(
    tier="tier1",
    custom_limits={
        "internal-image-model": {
            "rpm": 20,
            "tpm": 0,
            "rpd": 100
        }
    }
)

Custom limits always take precedence over built-in tiers.

Error Handling

from llm_limiters import RateLimitExceededError, ModelNotFoundError
  • RateLimitExceededError — all models in the priority list are exhausted
  • ModelNotFoundError — requested model is not configured

Built-In Limits

Built-in limits are defined in constants.py and include:

  • Gemini text models
  • OpenAI text models
  • Gemini Live models
  • Gemini Image / Imagen models
  • OpenAI image models

Tier-2 and higher image limits are intentionally empty until discovered and overridden.

License

MIT License Copyright (c) 2025 Nagomi Jayamani

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

llm_limiters-0.1.5.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

llm_limiters-0.1.5-py3-none-any.whl (11.5 kB view details)

Uploaded Python 3

File details

Details for the file llm_limiters-0.1.5.tar.gz.

File metadata

  • Download URL: llm_limiters-0.1.5.tar.gz
  • Upload date:
  • Size: 10.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for llm_limiters-0.1.5.tar.gz
Algorithm Hash digest
SHA256 3c6198d17e5a838cfa54e1e1867a5d464a3e84e1556bdbc8bc3d8dfb32ca7f90
MD5 610269ba5ba8b8c5de91141bbebfbd30
BLAKE2b-256 94f1b37e7dec453f0ed9dd194910bc8c2fcb0fe254be3f45aa112666e1220524

See more details on using hashes here.

File details

Details for the file llm_limiters-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: llm_limiters-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 11.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for llm_limiters-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 3720247a60b7f117010bc74eecae51176a9dc39a55b8a2dd9ada5d6f01aaeb16
MD5 e0599d6258133e36f6fb09be1d8d82b7
BLAKE2b-256 f0d79845f7be6eecd7ac87965779304464be7c12c61d676479a4d3e4a8aa155b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page