Create a Balance
Copy
import Limitry from '@limitry/sdk';
const client = new Limitry();
const balance = await client.balances.create({
customerId: "cust_123",
name: "AI Credits",
unit: "credits",
initialBalance: 10000,
minimumBalance: 0 // Can't go below 0
});
console.log(`Created balance: ${balance.id}`);
console.log(`Available: ${balance.availableBalance} ${balance.unit}`);
Balance Options
Minimum Balance
Copy
// No overdraft allowed (default)
const balance = await client.balances.create({
customerId: "cust_123",
name: "Credits",
unit: "credits",
initialBalance: 1000,
minimumBalance: 0
});
// availableBalance = 1000
// Reserve some credits
const balance = await client.balances.create({
customerId: "cust_123",
name: "Credits",
unit: "credits",
initialBalance: 1000,
minimumBalance: 100 // Keep 100 in reserve
});
// availableBalance = 900
// Allow overdraft
const balance = await client.balances.create({
customerId: "cust_123",
name: "Credits",
unit: "credits",
initialBalance: 1000,
minimumBalance: -500 // Allow 500 debt
});
// availableBalance = 1500
Check Balance Sufficiency
Check if a customer has sufficient balance before an operation:Copy
const result = await client.balances.checkSufficiency({
customerId: "cust_123",
name: "credits",
amount: 500
});
console.log(`Sufficient: ${result.sufficient}`);
console.log(`Available: ${result.availableBalance}`);
console.log(`Current: ${result.currentBalance}`);
if (!result.sufficient) {
const shortfall = result.requestedAmount - result.availableBalance;
console.log(`Need ${shortfall} more credits`);
}
Credit (Add Funds)
Copy
const result = await client.balances.credit({
customerId: "cust_123",
name: "credits",
amount: 5000,
description: "Monthly top-up",
reference: "stripe_pi_123" // Optional: link to payment
});
console.log(`Added: ${result.transaction.amount}`);
console.log(`New balance: ${result.balance.currentBalance}`);
Debit (Spend Credits)
Copy
const result = await client.balances.debit({
customerId: "cust_123",
name: "credits",
amount: 100,
description: "GPT-4 completion",
reference: "evt_xyz789" // Optional: link to event
});
if (result.success) {
console.log(`Spent: ${result.transaction.amount}`);
console.log(`Remaining: ${result.balance.currentBalance}`);
} else {
console.log(`Failed: ${result.error}`);
}
Debits are atomic — if there aren’t enough credits, the entire operation fails. No partial debits.
Get a Balance
Copy
const balance = await client.balances.retrieve("bal_abc123");
console.log(`Current balance: ${balance.currentBalance}`);
console.log(`Minimum balance: ${balance.minimumBalance}`);
console.log(`Unit: ${balance.unit}`);
List Balances
Copy
// List all balances for a customer
const balances = await client.balances.list({ customerId: "cust_123" });
for (const bal of balances.data) {
console.log(`${bal.name}: ${bal.availableBalance} ${bal.unit}`);
}
// List all balances
const balances = await client.balances.list();
// Pagination
const balances = await client.balances.list({ limit: 50 });
if (balances.hasMore) {
const nextPage = await client.balances.list({ cursor: balances.nextCursor });
}
Transaction History
Copy
const transactions = await client.balances.listTransactions({
balanceId: "bal_abc123",
limit: 50
});
for (const txn of transactions.data) {
const sign = txn.type === "credit" ? "+" : "-";
console.log(`${txn.createdAt}: ${sign}${txn.amount} ${txn.description}`);
console.log(` Balance after: ${txn.balanceAfter}`);
if (txn.reference) {
console.log(` Reference: ${txn.reference}`);
}
}
// Filter by type
const creditsOnly = await client.balances.listTransactions({
balanceId: "bal_abc123",
type: "credit"
});
const debitsOnly = await client.balances.listTransactions({
balanceId: "bal_abc123",
type: "debit"
});
Update a Balance
Copy
const balance = await client.balances.update("bal_abc123", {
name: "Updated balance name",
minimumBalance: 50 // Change reserve amount
});
Delete a Balance
Copy
const result = await client.balances.delete("bal_abc123");
if (result.success) {
console.log("Balance deleted");
}
Deleting a balance is permanent. All transaction history will be lost.
Example: Credit-Based Usage
Copy
async function processRequest(
customerId: string,
balanceId: string,
prompt: string
): Promise<string> {
// 1. Check balance
const balance = await client.balances.retrieve(balanceId);
const estimatedCost = Math.ceil(prompt.length / 4); // Rough token estimate
if (balance.availableBalance < estimatedCost) {
throw new Error("Insufficient credits");
}
// 2. Make the LLM call
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: prompt }]
});
// 3. Calculate actual cost
const actualCost = response.usage!.total_tokens;
// 4. Debit the balance
await client.balances.debit({
customerId,
name: "credits",
amount: actualCost,
description: `GPT-4: ${actualCost} tokens`
});
// 5. Record event for analytics
await client.events.record({
customerId,
eventType: "llm.completion",
values: { tokens: actualCost },
dimensions: { model: "gpt-4" }
});
return response.choices[0].message.content!;
}