@supernal/api-usage-tracker
v0.1.0
Published
API usage tracking, cost calculation, and billing utilities
Readme
@supernal/api-usage-tracker
A comprehensive API usage tracking, cost calculation, and billing utilities package for the Supernal platform. This package provides dynamic pricing calculations, secure API key management, and detailed usage tracking with support for both platform-managed and user-provided (BYOK) API keys.
Features
- 🔢 Dynamic Cost Calculation - Real-time pricing based on actual provider rates
- 🔐 Secure API Key Vault - AES-256-GCM encryption for user API keys
- 📊 Usage Tracking - Detailed usage metrics with cost attribution
- 💰 Multi-Provider Pricing - Support for OpenAI, Cartesia, Azure, ElevenLabs, Google
- 🔄 BYOK Support - Let users bring their own API keys with zero platform fees
- 📈 Tiered Pricing - Handle volume-based pricing tiers automatically
Installation
npm install @supernal/api-usage-tracker
# or
pnpm add @supernal/api-usage-trackerQuick Start
1. Initialize the Package
import { ApiKeyVault } from '@supernal/api-usage-tracker'
// Initialize the API key vault with your encryption secret
ApiKeyVault.initialize(process.env.API_KEY_ENCRYPTION_SECRET)2. Track API Usage
import { UsageTracker } from '@supernal/api-usage-tracker'
// Track platform key usage
const event = await UsageTracker.trackTTSUsage({
userId: 'user123',
provider: 'openai',
model: 'tts-1',
characters: 1000,
cached: false,
keyType: 'platform'
})
console.log(`Cost: $${event.cost.toFixed(4)}`)3. Calculate Costs
import { TTSPricingCalculator } from '@supernal/api-usage-tracker'
// Calculate cost for specific usage
const { cost, perCharacter } = TTSPricingCalculator.calculateCost(
'openai',
'tts-1',
100000 // 100k characters
)
// Compare providers
const comparison = TTSPricingCalculator.compareProviders(100000, [
{ provider: 'openai', model: 'tts-1' },
{ provider: 'cartesia', model: 'sonic' },
{ provider: 'azure', model: 'neural' }
])API Reference
TTSPricingCalculator
calculateCost(provider, model, characters, monthlyUsage?)
Calculate the cost for TTS synthesis.
const { cost, perCharacter } = TTSPricingCalculator.calculateCost(
'openai',
'tts-1',
50000,
1000000 // Optional: monthly usage for tier calculation
)calculateWithMarkup(baseCost, markupPercent?)
Add platform markup to base cost.
const { total, markup, base } = TTSPricingCalculator.calculateWithMarkup(
new Decimal(10),
20 // 20% markup
)estimateMonthlyCost(provider, model, monthlyCharacters, cacheHitRate?)
Estimate monthly costs with caching benefits.
const estimate = TTSPricingCalculator.estimateMonthlyCost(
'openai',
'tts-1',
1000000, // 1M chars/month
0.7 // 70% cache hit rate
)compareProviders(characters, providers)
Compare costs across multiple providers.
const comparison = TTSPricingCalculator.compareProviders(100000, [
{ provider: 'openai', model: 'tts-1' },
{ provider: 'openai', model: 'tts-1-hd' },
{ provider: 'cartesia', model: 'sonic' }
])
// Returns sorted by cost (cheapest first)UsageTracker
trackTTSUsage(params)
Track a TTS usage event.
const event = await UsageTracker.trackTTSUsage({
userId: 'user123',
provider: 'openai',
model: 'tts-1',
characters: 1000,
cached: false,
keyType: 'platform', // or 'user' for BYOK
userApiKeyId: 'uak_123' // For BYOK
})getUserSummary(userId, startDate, endDate)
Get usage summary for a user.
const summary = await UsageTracker.getUserSummary(
'user123',
new Date('2024-01-01'),
new Date('2024-01-31')
)estimateCost(params)
Estimate cost before synthesis.
const estimate = UsageTracker.estimateCost({
provider: 'openai',
model: 'tts-1',
text: 'Hello world',
keyType: 'platform'
})ApiKeyVault
initialize(encryptionKey)
Initialize the vault with an encryption key.
ApiKeyVault.initialize('your-32-character-encryption-key')storeUserKey(params)
Store a user's API key securely.
const userKey = await ApiKeyVault.storeUserKey({
userId: 'user123',
name: 'Production OpenAI Key',
provider: 'openai',
keyType: 'openai',
key: 'sk-...',
metadata: {
model: 'tts-1',
rateLimit: 100
}
})getUserKey(userId, keyId)
Retrieve and decrypt a user's API key.
const decryptedKey = await ApiKeyVault.getUserKey('user123', 'uak_123')validateKey(provider, keyType, key)
Validate an API key with its provider.
const { valid, error } = await ApiKeyVault.validateKey(
'openai',
'openai',
'sk-...'
)Pricing Data
The package includes real-world pricing for major TTS providers:
| Provider | Model | Price per Million Characters | |----------|-------|------------------------------| | OpenAI | tts-1 | $15.00 | | OpenAI | tts-1-hd | $30.00 | | Cartesia | sonic | $2.50 | | Azure | neural | $4.00 - $16.00 (tiered) | | ElevenLabs | multilingual_v2 | $180.00 - $330.00 (tiered) | | Google | wavenet | $16.00 |
Security
- Encryption: All API keys encrypted using AES-256-GCM
- Key Derivation: Uses scrypt for key derivation
- Unique IVs: Each encryption uses a unique initialization vector
- Hash Storage: Stores SHA256 hash for duplicate detection
Usage Examples
Complete BYOK Flow
// 1. Store user's API key
const storedKey = await ApiKeyVault.storeUserKey({
userId: 'user123',
name: 'My OpenAI Key',
provider: 'openai',
keyType: 'openai',
key: 'sk-...'
})
// 2. Use the key for TTS
const audio = await ttsService.synthesize(
'Hello world',
{
provider: 'openai',
voice: 'alloy',
useUserKey: true,
userApiKeyId: storedKey.id
},
'user123'
)
// 3. Track usage (automatically done, but zero cost)
// Cost will be 0 for user keysCost Optimization Analysis
// Analyze potential savings
const monthlyUsage = 5000000 // 5M characters
// Without caching
const fullCost = TTSPricingCalculator.calculateCost(
'openai', 'tts-1', monthlyUsage
)
// With caching
const estimate = TTSPricingCalculator.estimateMonthlyCost(
'openai', 'tts-1', monthlyUsage, 0.7
)
console.log(`Monthly cost without cache: $${fullCost.cost.toFixed(2)}`)
console.log(`Monthly cost with cache: $${estimate.withCache.toFixed(2)}`)
console.log(`Monthly savings: $${estimate.savings.toFixed(2)}`)Testing
# Run tests
pnpm test
# Run tests with coverage
pnpm test -- --coverage
# Run tests in watch mode
pnpm test:watchContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This package is part of the Supernal platform and is subject to the Supernal license agreement.
