Skip to main content

enforces budget

Project description

coreason-budget (The Controller)

Mission: Enforce Financial Operations (FinOps) guardrails for LLM usage.

This package acts as the "Controller," treating Compute (Tokens) as Cash. It enforces daily quotas and rejects requests immediately if limits are exceeded.

Features

  • Atomic Counting: Uses Redis for high-speed, atomic, thread-safe counters.
  • Hierarchical Quotas: Enforces limits at User, Project, and Global scopes.
  • Fail Closed: Security-first design; if the budget cannot be checked, the transaction is blocked.
  • Manual Integration: Designed to be integrated into your middleware with a "Check-then-Charge" lifecycle.

Installation

pip install coreason-budget

or with Poetry:

poetry add coreason-budget

Usage

The package exposes a BudgetManager that you integrate into your API flow.

1. Configuration

The system is configured via BudgetConfig or environment variables (COREASON_BUDGET_*).

from coreason_budget import BudgetManager, BudgetConfig, BudgetExceededError

# Initialize with Redis URL and Limits
config = BudgetConfig(
    redis_url="redis://localhost:6379",
    daily_user_limit_usd=10.0,
    daily_project_limit_usd=500.0,
    daily_global_limit_usd=5000.0
)
budget = BudgetManager(config)

2. The Check-Charge Lifecycle

The middleware operates in two phases: Pre-Flight Check and Post-Flight Charge.

# --- Phase 1: Pre-Flight Check ---
# Before calling the LLM, verify budget availability.
user_id = "user_123"
try:
    # Check if user can spend (optionally pass estimated_cost)
    await budget.check_availability(user_id)
except BudgetExceededError:
    # Block the request immediately
    return Response("Daily Limit Reached", status_code=429)

# --- Execute LLM ---
# Perform the inference call
response = await llm.generate(...)

# --- Phase 2: Post-Flight Charge ---
# Calculate precise cost based on provider metadata
cost = budget.pricing.calculate(
    model="gpt-4",
    input_tokens=response.usage.prompt_tokens,
    output_tokens=response.usage.completion_tokens
)

# Atomically record the spend
await budget.record_spend(
    user_id=user_id,
    cost=cost,
    project_id="project_launch_sim", # Optional
    model="gpt-4"                    # Optional, for logging
)
print(f"Transaction Cost: ${cost}")

Configuration Options

Environment Variable Description Default
COREASON_BUDGET_REDIS_URL Redis Connection URL Required
COREASON_BUDGET_DAILY_USER_LIMIT_USD Daily limit per user ($) 10.0
COREASON_BUDGET_DAILY_PROJECT_LIMIT_USD Daily limit per project ($) 500.0
COREASON_BUDGET_DAILY_GLOBAL_LIMIT_USD Global hard limit ($) 5000.0
COREASON_BUDGET_LOG_PATH Path to log file logs/app.log

Architecture

  • RedisLedger: Manages atomic increments and key expiration (UTC Midnight).
  • BudgetGuard: Enforces limits and raises BudgetExceededError.
  • PricingEngine: Calculates costs using liteLLM or configured overrides.

Development

  1. Install Dependencies:

    poetry install
    
  2. Run Tests:

    poetry run pytest
    
  3. Code Quality:

    poetry run pre-commit run --all-files
    

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

coreason_budget-0.1.0.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

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

coreason_budget-0.1.0-py3-none-any.whl (14.3 kB view details)

Uploaded Python 3

File details

Details for the file coreason_budget-0.1.0.tar.gz.

File metadata

  • Download URL: coreason_budget-0.1.0.tar.gz
  • Upload date:
  • Size: 11.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for coreason_budget-0.1.0.tar.gz
Algorithm Hash digest
SHA256 36d7b8cda4faa4e26ffdb5b0f720d71e287556a252b5ca92120ad170a8f22771
MD5 86c40302d1ee4fe82c318ac731a9023a
BLAKE2b-256 60af04f223eccf5f4c80d84b1d57731011325594578958b52cfac5d07d7a5b2c

See more details on using hashes here.

Provenance

The following attestation bundles were made for coreason_budget-0.1.0.tar.gz:

Publisher: publish.yml on CoReason-AI/coreason-budget

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file coreason_budget-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for coreason_budget-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f7b8d6c6d3bf24dabdecdfe976bd5d9d194fa1d3be5e014e6d94b5092a263dbf
MD5 d79de78f5ed4f906134af2060d5a5e5e
BLAKE2b-256 ac57df2c8815b5cc4d6353ec2d88996ab369bfc13a94e37776c6e9c99b97aa2e

See more details on using hashes here.

Provenance

The following attestation bundles were made for coreason_budget-0.1.0-py3-none-any.whl:

Publisher: publish.yml on CoReason-AI/coreason-budget

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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