Metadata-Version: 2.4
Name: coreason_budget
Version: 0.2.0
Summary: enforces budget
License: # The Prosperity Public License 3.0.0
         
         Contributor: CoReason, Inc.
         
         Source Code: https://github.com/CoReason-AI/coreason_budget
         
         ## Purpose
         
         This license allows you to use and share this software for noncommercial purposes for free and to try this software for commercial purposes for thirty days.
         
         ## Agreement
         
         In order to receive this license, you have to agree to its rules.  Those rules are both obligations under that agreement and conditions to your license.  Don't do anything with this software that triggers a rule you can't or won't follow.
         
         ## Notices
         
         Make sure everyone who gets a copy of any part of this software from you, with or without changes, also gets the text of this license and the contributor and source code lines above.
         
         ## Commercial Trial
         
         Limit your use of this software for commercial purposes to a thirty-day trial period.  If you use this software for work, your company gets one trial period for all personnel, not one trial per person.
         
         ## Contributions Back
         
         Developing feedback, changes, or additions that you contribute back to the contributor on the terms of a standardized public software license such as [the Blue Oak Model License 1.0.0](https://blueoakcouncil.org/license/1.0.0), [the Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0.html), [the MIT license](https://spdx.org/licenses/MIT.html), or [the two-clause BSD license](https://spdx.org/licenses/BSD-2-Clause.html) doesn't count as use for a commercial purpose.
         
         ## Personal Uses
         
         Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, doesn't count as use for a commercial purpose.
         
         ## Noncommercial Organizations
         
         Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution doesn't count as use for a commercial purpose regardless of the source of funding or obligations resulting from the funding.
         
         ## Defense
         
         Don't make any legal claim against anyone accusing this software, with or without changes, alone or with other technology, of infringing any patent.
         
         ## Copyright
         
         The contributor licenses you to do everything with this software that would otherwise infringe their copyright in it.
         
         ## Patent
         
         The contributor licenses you to do everything with this software that would otherwise infringe any patents they can license or become able to license.
         
         ## Reliability
         
         The contributor can't revoke this license.
         
         ## Excuse
         
         You're excused for unknowingly breaking [Notices](#notices) if you take all practical steps to comply within thirty days of learning you broke the rule.
         
         ## No Liability
         
         ***As far as the law allows, this software comes as is, without any warranty or condition, and the contributor won't be liable to anyone for any damages related to this software or this license, under any kind of legal claim.***
License-File: LICENSE
License-File: NOTICE
Author: Gowtham A Rao
Author-email: gowtham.rao@coreason.ai
Requires-Python: >=3.11
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Dist: litellm (>=1.80.11,<2.0.0)
Requires-Dist: loguru (>=0.7.2,<0.8.0)
Requires-Dist: pydantic (>=2.0)
Requires-Dist: pydantic-settings (>=2.12.0,<3.0.0)
Requires-Dist: redis (>=7.1.0,<8.0.0)
Project-URL: Documentation, https://github.com/CoReason-AI/coreason_budget
Project-URL: Homepage, https://github.com/CoReason-AI/coreason_budget
Project-URL: Repository, https://github.com/CoReason-AI/coreason_budget
Description-Content-Type: text/markdown

# 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

```bash
pip install coreason-budget
```

or with Poetry:

```bash
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_*`).

```python
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**.

```python
# --- 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:**
    ```bash
    poetry install
    ```

2.  **Run Tests:**
    ```bash
    poetry run pytest
    ```

3.  **Code Quality:**
    ```bash
    poetry run pre-commit run --all-files
    ```

