Back to Home
Credits System
Set up and manage the credit-based usage system for metering AI features and API calls.
Optional usage-based billing. Enable with features.credits: true.
Configuration
src/config/credits.ts
TypeScript
export const creditsConfig = {
costs: {
api_call: 1,
generation: 10,
image_generation: 25,
analysis: 5,
export: 2,
},
planAllocations: {
free: 50,
starter: 500,
pro: 2000,
enterprise: 10000,
},
initialCredits: 50,
lowBalanceThreshold: 0.2, // 20% triggers warning
packages: [
{ id: 'credits_100', credits: 100, priceInPaise: 9900 },
{ id: 'credits_500', credits: 500, priceInPaise: 39900 },
{ id: 'credits_1000', credits: 1000, priceInPaise: 69900 },
],
};Usage
TypeScript
import { getBalance, hasCredits, deductCredits, addCredits } from '@/lib/credits';
const tenant = await getTenantContext();
// Check balance
const balance = await getBalance(tenant);
// Check before expensive operation
if (!await hasCredits(tenant, 10)) {
return { error: 'Insufficient credits' };
}
// Deduct atomically
const result = await deductCredits(tenant, 10, 'generation', { model: 'gpt-4' });
if (result.success) {
// remainingCredits available in result
}
// Add credits (after purchase)
await addCredits(tenant, 500, 'purchase:credits_500', { orderId: 'abc123' });Low Balance Notifications
When credits drop below the threshold (default: 20% of plan allocation), an Inngest event is fired and an email notification is sent to the user or org owner.