Budget
A rolling-window spend ledger that fails closed, with per-key caps.
Usage
import { createBudgetLedger, kvBudgetStore, createExtractor } from "@dapplelight/signet-ai"
import { env } from "./env"
import { providers, schema, instructions } from "./ai"
const input = "Invoice total: 120"
const user = { id: "user_1" }
// Build where env exists (a request handler), not at module scope.
const ledger = createBudgetLedger(5, 86_400, {
store: kvBudgetStore(env.AI_KV), // omit for per-isolate memory
perKeyUsd: 0.5, // each user: $0.50 of the $5
})
const ai = createExtractor({ providers, ledger })
await ai.extract({ schema, input, instructions, budget: { key: user.id } })API
| Export | What it does |
|---|---|
createBudgetLedger(windowUsd, windowSeconds?, options?) | Ledger with spentUsd, remainingUsd, canSpend, record |
memoryBudgetStore() | Default store. Per isolate, empty after a cold start |
kvBudgetStore(kv, prefix?) | Shared store on Workers KV or a KeyValueLike. Approximate |
costOf(usage, pricing) | USD for one call from token usage and Pricing |
BudgetStore | Type: any object with spent and record (Redis, a database); add an atomic reserve to make the cap hold under parallel calls |
BudgetKv | Type: the KV namespace subset kvBudgetStore needs |
BudgetLedger, BudgetLedgerOptions | Types |
createBudgetLedger(windowUsd, windowSeconds, options)
| Option | Type | Default | |
|---|---|---|---|
windowUsd | number | required | Cap per window |
windowSeconds | number | 3600 | Rolling window length |
options.store | BudgetStore | memoryBudgetStore() | Where spend is kept |
options.perKeyUsd | number | none | Cap per budget.key in the same window |
The ledger fails closed: an exhausted window or an unreachable store refuses the call. A window that is exactly full refuses even a zero estimate. extract holds budget.maxCostUsd with reserve before the model call and settles it to the real cost after, so parallel calls near the cap cannot all pass. With 20 parallel calls at a ledger one call short of its cap, the memory and Durable Object stores let one through; KV let all 20 through. A call with no budget.maxCostUsd holds nothing, so set it.
Ledger methods
| Method | Returns |
|---|---|
spentUsd(now?, key?) | USD spent in the window, globally or for a key |
remainingUsd(now?) | USD left globally |
canSpend(estimateUsd, now?, key?) | { ok: true }, or { ok: false, limit: "global" | "key", retryAfterSeconds } when the global or the key window has no room. retryAfterSeconds is the time until the oldest spend leaves the window (a whole window if the store has no oldestAt) |
record(usd, now?, key?) | Adds spend; ignores values of 0 or less |
reserve(estimateUsd, now?, key?) | Checks and holds the estimate in one step. Returns the same refusal as canSpend, or { ok: true, settle(actualUsd) }. settle replaces the hold with the real cost (settle(0) releases it). On a store without reserve it falls back to canSpend |
kvBudgetStore is best-effort. It has no atomic check-and-add, so parallel calls can all pass the check (20 parallel calls at a cap one call short all got through), it uses a fixed window, and concurrent writes can lose a record. Use the Durable Object store when the cap must hold.
Examples
Pricing a flat-rate provider
import { costOf } from "@dapplelight/signet-ai"
costOf({ inputTokens: 1200, outputTokens: 300 }, { inputPerMTokens: 0.15, outputPerMTokens: 0.6 })
costOf(undefined, { perCallUsd: 0.0005 }) // 0.0005