Skip to main content

Python middleware SDK for RateGuard

Project description

RateGuard Python SDK

RateGuard is a middleware-first API protection and observability SDK for Python apps.

It runs entirely in-process by default:

  • rate limiting
  • token budgets
  • circuit breaking
  • request events

No external service is required for standalone use. Configure an event endpoint only when you want RateGuard events delivered outside the process.

Install

pip install varbees-rateguard

Quick Start

from rateguard import BudgetExceeded, RateGuard

rg = RateGuard(preset="standard")
budget = rg.budget


async def call_provider(user_id: str) -> None:
    try:
        async with budget.enforce(user_id=user_id, hard_stop=True):
            # Call your LLM, API, worker, or provider here.
            pass

        budget.record(user_id=user_id, tokens=1200)
    except BudgetExceeded as exc:
        print(exc)
        raise

For provider SDKs that return token usage, enforce before the request and record the returned usage afterward:

async with rg.budget.enforce(user_id="me", hard_stop=True):
    response = await client.chat.completions.create(model="gpt-4o", messages=messages)
    rg.budget.record(user_id="me", tokens=response.usage.total_tokens)

FastAPI

from fastapi import Depends, FastAPI, Request
from rateguard import RateGuard

app = FastAPI()
rg = RateGuard(preset="standard")
app.add_middleware(rg.asgi_middleware)


@app.post("/chat")
async def chat(req: Request, _=Depends(rg.require)):
    return {"ok": True}

Flask / WSGI

from flask import Flask
from rateguard import RateGuard, RateGuardMiddleware

app = Flask(__name__)
rg = RateGuard(preset="standard")
app.wsgi_app = RateGuardMiddleware(app.wsgi_app, guard=rg.runtime)

Configuration

Key Type Default
preset dev / standard / high-throughput / streaming-llm / agent-orchestrator / llm-heavy / mcp-server / strict-upstream-protection dev
hard_stop bool True
monthly_limit int preset-derived
soft_stop_at float 0.8

Outbound LLM Tracking

from openai import OpenAI, AsyncOpenAI
from rateguard import RateGuard

rg = RateGuard(preset="streaming-llm")
client = OpenAI(http_client=rg.wrap_httpx_client())
aclient = AsyncOpenAI(http_client=rg.wrap_httpx_async_client())

rg.mcp_tools() and rg.mcp_call() expose all 7 pre-flight MCP tools for agent frameworks (includes attest_budget/verify_budget). serve_mcp(rg) runs a zero-dependency stdio JSON-RPC server over the same tools — drop it straight into a Claude Code/Cursor/Claude Desktop MCP config. Guardrails, loop detection, GenAI attribute helpers (including TTFT/TPOT), and Prometheus exposition helpers are exported for app-level wiring.

Also included

  • Budget attestation (pip install varbees-rateguard[attestation]) — Ed25519-signed delegation chains (new_root_budget_token, attest, verify_presentation), byte-identical signing payload with Go and Node so a token attested in one language verifies in another. cryptography is a lazy, optional import — install the attestation extra to use it.
  • Redis distributed limiter — atomic Lua GCRA script for rate limits shared across processes/instances, RedisPyClient/AsyncRedisPyClient wrap redis-py or bring your own client shaped like RedisLimiterClient.
  • Admin API — opt-in, unauthenticated-by-design ASGI app (AdminApp) exposing state/policy/MCP-tool-calls; bind privately.
  • Adaptive rate limiting — opt-in AIMD controller that auto-tunes the effective limit from observed upstream error rate.
  • Semantic response caching — bring your own Embedder; a cosine-similarity hit skips the network call, breaker, and budget entirely.
  • Lock-free sharded limiter — 64-way sharding with atomic CAS, available as ShardedLimiter.
  • Events/webhooksHTTPEventEmitter/WebSocketEventEmitter/ConsoleEventEmitter for shipping admission decisions out of process.

Docs

  • Go SDK: packages/sdk-go
  • Node SDK: packages/sdk-node
  • Full feature parity as of v0.2.0 — see the root README for the complete capability table.

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

varbees_rateguard-0.2.0.tar.gz (75.3 kB view details)

Uploaded Source

Built Distribution

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

varbees_rateguard-0.2.0-py3-none-any.whl (89.1 kB view details)

Uploaded Python 3

File details

Details for the file varbees_rateguard-0.2.0.tar.gz.

File metadata

  • Download URL: varbees_rateguard-0.2.0.tar.gz
  • Upload date:
  • Size: 75.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.4

File hashes

Hashes for varbees_rateguard-0.2.0.tar.gz
Algorithm Hash digest
SHA256 ecbf57e5dac286ea5a3377222158d8fdff57af0b9fc143f81e9a8ac6ab5d4f62
MD5 a4d79b000ab37d74d6056d830649fefd
BLAKE2b-256 a6879e6e6d38e07c1136efa9d5312167ad2d9b47d2267468c5e6fe8ae64592f6

See more details on using hashes here.

File details

Details for the file varbees_rateguard-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for varbees_rateguard-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d8bfc4cba49749e2e06f1c85a6d3cee8d4342d1b59b4a573e0fa79bd83181be2
MD5 ebde7846d68cf865456117cf8100b731
BLAKE2b-256 e538cc444d1e2374992c347bf2ec8fcd6378f085c891871e872742f067a4d714

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