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.4.tar.gz (9.7 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.4-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: llm_limiters-0.1.4.tar.gz
  • Upload date:
  • Size: 9.7 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.4.tar.gz
Algorithm Hash digest
SHA256 9786bf6e63701124af4241987518236b087a93da479e830e8b42f1db9e25a20c
MD5 5dabce9c40bded55ad80bd487f25b705
BLAKE2b-256 9c576ec17b769f5a29a6e04b9d7c708e76719c6bec886e079a0f212172786b3a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: llm_limiters-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 10.1 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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 9340872ca6d314ad8159ed527a220342372be34a056677a6e26a91b05517ea41
MD5 0c88cec5f15e0cf7a6a7b6d763f05fa7
BLAKE2b-256 bfc8ee65253035f52cb2cf0aa381fe171bdf98e3c528f35b4b3a754b21f19f61

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