Skip to main content

Python API

bursar for Python is published as the bursar package on PyPI. Requires Python 3.11+.

Installation

pip install bursar

# With store backends
pip install "bursar[supabase]"
pip install "bursar[postgres]"
pip install "bursar[test]" # dev + testing

Core Classes

ClassDescription
PricingEnginePure calculation layer — evaluates expressions against usage metrics
CreditManagerOrchestrates the credit lifecycle (atomic calculate-then-charge)
MemoryStoreIn-memory store for testing
HttpxSupabaseStoreSupabase-backed store (fetch-based)
PostgresStoreDirect PostgreSQL store
UsageMetricsData class for usage dimensions
CostBreakdownStructured calculation result

Errors

All importable from bursar:

ExceptionRaised when
CreditErrorBase for all manager-domain errors
InsufficientCreditsErrorBalance floor would be breached
CapReachedErrorA deny spend cap would be exceeded
PricingNotLoadedErrordeduct() called before pricing is loaded
ConcurrencyLimitErrorreserve() would exceed max_concurrent leases
FeatureNotEntitledErrorOperation requires a plan feature the user lacks
LeaseExpiredErrorSettling/renewing an elapsed lease
LeaseNotFoundErrorLease id is missing, belongs to another user, or was released
StoreErrorBase for store-level errors (connection, timeout)
ConfigErrorInvalid pricing config structure or expression
ExpressionErrorExpression evaluation failure (div by zero, overflow)
CapabilityNotSupportedErrorAn optional CreditStore capability (analytics, transaction listing, or teams) was called on a store that didn't override its default implementation

Result Types

All result models are importable from bursar:

ModelReturned by
BalanceResultget_balance()
AddCreditsResultadd_credits()
DeductionResultdeduct(), deduct_fixed(), settle()
LeaseResultreserve(), renew()
ReleaseResultrelease()
CanAffordResultcan_afford()
AvailableResultget_available()
RefundResultrefund_credits()
SweepResultsweep_expired_credits()
TierBalancesResultget_credit_tiers()
SetUserPlanResultset_user_plan()
GetUserPlanResultget_user_plan()
CheckFeatureResultcheck_feature()
TeamDeductionResultdeduct_team()
SetupResultsetup()
SpendByUserRowspend_by_user()
SpendByModelRowspend_by_model()
TopUserRowtop_users()
DailySpendRowdaily_spend()
AggregateStatsRowaggregate_stats()
TransactionRowlist_user_transactions()

Input / Config Types

ModelDescription
PricingConfigDataPricing config schema (models, tools, search, cache, fixed, plans)
PlanDefinitionSubscription plan definition (allowance, allowance_period, features, billing policy)
OperationPolicyPer-operation financial-safety policy (billing mode, floors, concurrency)
TierDefinitionCredit tier definition (priority, expiry, default/overdraft flags)
LowBalanceConfigCreditManager(low_balance=...) config: thresholds + on_trigger
CreditMetadataFlexible metadata attached to transactions
SpendCapPer-user daily/monthly spend cap configuration

Quick Example

from bursar import CreditManager, UsageMetrics
from bursar.interface.supabase import HttpxSupabaseStore

store = HttpxSupabaseStore(url="https://project.supabase.co", key="service_role_key")
manager = CreditManager(store=store)
manager.load_pricing_from_store()

manager.add_credits("user_abc", 1000)

result = manager.deduct(
user_id="user_abc",
metrics=UsageMetrics(model="gpt-4", input_tokens=500, output_tokens=200),
idempotency_key="tx_001",
)
print(result.balance_after) # remaining credits