Token Tracking and Currency Conversion System
Overview
This system tracks OpenAI token usage per user and provides a currency conversion mechanism between tokens and drops. Super admins can adjust conversion rates via sliders in the admin panel.
Features
-
Token Usage Tracking: Tracks tokens used for:
- Tone analysis (GPT-4o-mini)
- Image generation (DALL-E 3 for entry backgrounds)
- Tone pack image generation (DALL-E 3)
-
Cost Calculation: Automatically calculates USD cost based on OpenAI pricing:
- GPT-4o-mini: $0.15/1M input tokens, $0.60/1M output tokens
- DALL-E 3: $0.040 per standard image, $0.080 per HD image
-
Monthly Aggregation: Tracks token usage per calendar month per user
-
Conversion Rates: Super admins can set conversion rates between tokens and drops using sliders
-
Admin Dashboard: Shows token usage and drops balance for each user
Database Schema
Tables
token_usage: Records all token usage with cost, type, and referencescurrency_conversion_rates: Stores conversion rates with effective datesprofiles.drops_balance: Current drops balance (existing)
Functions
get_user_token_usage_monthly(user_id, year, month): Returns monthly token usage summary
API Endpoints
Admin Conversion Rates
GET /api/admin/conversion/rates- Get current conversion ratesPOST /api/admin/conversion/rates- Update conversion rate (super admin only)
Admin Users (Updated)
GET /api/admin/users- Now includesdrops_balanceandtoken_usageper user
Token Tracking Implementation
Tone Analysis
Tracks tokens when:
- Creating journal entries (auto-detect mood)
- Updating journal entries (auto-detect mood)
- Manual tone analysis via
/api/ai/analyze-tone
Image Generation
Tracks usage when:
- Generating entry background images (
/api/ai/generate-background) - Generating tone pack images (
/api/tone-packs/:id/generate-images)
Admin Panel Features
Users Table
New columns:
- Drops: Current drops balance (🍯 icon)
- Tokens (This Month): Shows:
- Total tokens used
- Total cost in USD
- Breakdown by type (Tone, Images, Packs)
Conversion Rates Tab
- Slider to adjust tokens→drops conversion rate
- Current rate display
- Rate history table
- Update button to save new rates
Usage
Setting Conversion Rates
- Go to Admin Panel → Conversion Rates
- Adjust the slider or enter a value
- Click "Update Conversion Rate"
- The new rate becomes effective immediately
Viewing Token Usage
- Go to Admin Panel → Users
- View the "Tokens (This Month)" column
- See breakdown by usage type
Future Enhancements
- Backfill historical token costs from OpenAI API
- Automatic rate updates based on OpenAI pricing API
- Token usage charts/graphs
- Export token usage reports
- Set different rates for different usage types
- Token budget alerts
Pricing Reference
Current OpenAI pricing (as of implementation):
- GPT-4o-mini: $0.15/1M input, $0.60/1M output
- DALL-E 3: $0.040 standard, $0.080 HD
These should be updated when OpenAI changes pricing or when an API/scraper is implemented.