Skip to content

The spending cap

limen_agents.llm.budget

A spending cap on paid models, checked before every call and fed after it.

Every client calls :meth:Budget.check before a call that may be paid, and :meth:Budget.record after every call, local or not, with its tokens. Over the cap :meth:~Budget.check raises :class:BudgetExceededError: callers treat it as any model failure and fall back to their deterministic text.

:class:MonthlyBudget is the cap of Limen: a monthly limit in dollars over a :class:SpendStore the application provides (a table, a file). If the spend cannot be read the call does not start: a cap that opens when its store is down is no cap.

BudgetExceededError

Bases: RuntimeError

The cap is reached, or the spend cannot be read.

Budget

Bases: Protocol

What a chat client asks before and tells after a call.

check async

check(model: str) -> None

Raise :class:BudgetExceededError if a call to model must not start.

record async

record(*, origin: str, model: str, input_tokens: int, output_tokens: int, batch: bool = False, reference: str | None = None) -> Decimal

Write the call down and return its cost (zero for a local model).

NoBudget

No cap and no record: every call goes.

SpendStore

Bases: Protocol

Where the spend of the month lives.

MonthlyBudget

A monthly cap in dollars over a :class:SpendStore.

The spend is read again at most every cache_s seconds: a briefing makes several calls in a row, each worth cents.

record async

record(*, origin: str, model: str, input_tokens: int, output_tokens: int, batch: bool = False, reference: str | None = None) -> Decimal

Write the call down; an error here does not lose the answer, already paid.

first_of_next_month

first_of_next_month(day: date) -> date

The day the monthly cap opens again.