Balance-based billing template for AI products. Customers prepay a balance, and each AI request automatically deducts the real cost (from the AI model catalog) plus your configured margin. Two plans (Starter, Pro) with different margins.
Stack: Next.js 16, AI SDK (Gateway), Better Auth, Drizzle ORM, PostgreSQL, Commet SDK
Quick Start
commet create my-app -t balance-ai
cd my-app
docker compose up -d
pnpm install
pnpm devWhat's Included
- Two plans with different balances and margins (Starter 50%, Pro 30%)
- Multi-model selector — switch between Claude, GPT, Gemini in one click
- Automatic token tracking via
tracked()middleware - AI model catalog pricing — real cost per model from Commet
- Balance deduction per request (cost + margin)
- Block on exhaustion — requests stop when balance runs out
- AI text generation demo with streaming
- Checkout flow with Commet-hosted payments
- Customer billing portal
How It Works
User sends prompt → AI Gateway → Response
↓
tracked() middleware reports:
- model, inputTokens, outputTokens
↓
Commet calculates:
- Real cost (from catalog)
- Margin (from plan config)
- Total deducted from balanceKey Files
lib/auth/auth.ts— Better Auth + Commet plugin with usage moduleapp/api/generate/route.ts— AI endpoint withtracked()middlewareapp/(dashboard)/dashboard/generate-form.tsx— Model selector + streamingapp/pricing/page.tsx— Dynamic pricing with checkoutapp/checkout/page.tsx— Checkout session creationlib/env.ts— Environment validation with t3-envlib/commet.ts— SDK initialization
Learn More
- Consumption Models — Balance model details
- AI Token Billing
- Customer Portal
