Skip to main content

Overview

The AudioPod AI Credits API allows you to monitor your credit balance, track usage history, and purchase additional credits through our pay-as-you-go system. Credits are used to access all AudioPod AI services including Text to Speech, transcription, and music creation.

Key Features

  • Real-time Balance: Check current credit balance and usage
  • Usage Tracking: Detailed history of credit consumption by service
  • Pay-as-You-Go: Purchase credits as needed without subscriptions
  • Multiple Sources: Track subscription credits and PAYG credits separately
  • Cost Transparency: Clear credit costs for each service

Authentication

The Credits API supports two authentication methods:
  • Header: Authorization: Bearer your_jwt_token
  • Obtain via: /api/v1/auth/token endpoint with email/password
  • Best for: Web applications, temporary access

API Key Authentication

  • Header: Authorization: Bearer your_api_key
  • Obtain via: API Keys dashboard in your account
  • Best for: Server-to-server integration, production applications
For detailed API key management, see the API Key Management guide.

Get Credit Balance

Current Credit Information

Get current credit balance and account information.
  • Python
  • Node.js
  • Raw HTTP
  • cURL
from audiopod import Client

# Initialize client
client = Client()

# Get credit balance
credits = client.credits.get_credit_balance()

print(f"Total Available Credits: {credits.total_available_credits}")
print(f"Subscription Credits: {credits.balance}")
print(f"Pay-as-You-Go Credits: {credits.payg_balance}")
print(f"Total Credits Used: {credits.total_credits_used}")

if credits.next_reset_date:
    print(f"Next Reset Date: {credits.next_reset_date}")

# Check if you have enough credits for a service
if credits.total_available_credits < 1000:
    print("⚠️  Low on credits! Consider purchasing more.")

# Get usage history
usage_history = client.credits.get_usage_history()
print(f"\nRecent usage history ({len(usage_history)} entries):")

for usage in usage_history[:5]:  # Show last 5 entries
    print(f"- {usage['service_type']}: {usage['credits_used']} credits ({usage['created_at']})")
Response:
{
  "credits_balance": 1500,
  "payg_balance": 750,
  "total_available_credits": 2250,
  "last_reset_at": "2024-01-01T00:00:00Z",
  "total_credits_used": 3250,
  "total_payg_credits_purchased": 1000,
  "next_reset_date": "2024-02-01T00:00:00Z",
  "credits_per_month": 2000
}

Credit Usage History

Get Usage Logs

Retrieve detailed history of credit usage across all services.
  • GET
  • Python
GET /api/v1/credits/usage
Authorization: Bearer {api_key}
Response:
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "user_credits_id": "660f8400-e29b-41d4-a716-446655440111",
    "credits_used": 15,
    "service_type": "voice_cloning",
    "audio_duration": 180,
    "credit_source": "subscription",
    "created_at": "2024-01-15T10:30:00Z",
    "usage_metadata": {
      "voice_id": 123,
      "generation_type": "speech_synthesis",
      "language": "en",
      "quality": "high"
    }
  },
  {
    "id": "550e8400-e29b-41d4-a716-446655440001",
    "user_credits_id": "660f8400-e29b-41d4-a716-446655440111",
    "credits_used": 50,
    "service_type": "music_generation",
    "audio_duration": 30,
    "credit_source": "payg",
    "created_at": "2024-01-15T09:15:00Z",
    "usage_metadata": {
      "task_type": "text2music",
      "duration_seconds": 30,
      "quality": "premium"
    }
  },
  {
    "id": "550e8400-e29b-41d4-a716-446655440002",
    "user_credits_id": "660f8400-e29b-41d4-a716-446655440111",
    "credits_used": 30,
    "service_type": "transcription",
    "audio_duration": 300,
    "credit_source": "subscription",
    "created_at": "2024-01-14T16:45:00Z",
    "usage_metadata": {
      "model_type": "whisperx",
      "language": "en",
      "speaker_diarization": true
    }
  }
]

Service Credit Costs

Get Credit Multipliers

Get current credit costs for different services and features.
  • GET
  • Python
GET /api/v1/credits/multipliers
Authorization: Bearer {api_key}
Response:
{
  "voice_cloning_generation": 330,
  "voice_conversion": 990,
  "speech_translation": 3300,
  "translation": 1650,
  "speaker_diarization": 1650,
  "speaker_extraction": 1650,
  "denoise_audio": 330,
  "spectral_denoise": 660,
  "stem_extraction": 990,
  "music_generation": 1320,
  "transcription": 660,
  "video_download": 6
}

Pay-as-You-Go Credits

Get PAYG Information

Get information about pay-as-you-go credit purchasing options.
  • GET
  • Python
GET /api/v1/credits/payg/info
Authorization: Bearer {api_key}
Response:
{
  "credits_per_dollar": 7500,
  "min_amount_usd": 1,
  "max_amount_usd": 1000,
  "currency": "USD"
}

Create PAYG Checkout Session

Create a checkout session for purchasing pay-as-you-go credits.
  • POST
  • Python
  • cURL
POST /api/v1/credits/payg/create-checkout-session
Authorization: Bearer {api_key}
Content-Type: application/json

{
  "amount_usd": 25
}
Response:
{
  "session_id": "cs_test_1234567890abcdef",
  "credits_to_receive": 187500,
  "amount_usd": 25
}

Usage Analytics

Track Credit Consumption

Monitor credit usage patterns and optimize costs.
  • Python
from audiopod import Client
from datetime import datetime, timedelta
from collections import defaultdict

def analyze_credit_usage():
    """Comprehensive credit usage analysis with SDK"""
    
    client = Client()
    
    # Get current balance
    credits = client.credits.get_credit_balance()
    print(f"Current Balance: {credits.total_available_credits:,} credits")
    print(f"Monthly Reset: {credits.next_reset_date}")
    
    # Get detailed usage history
    usage_logs = client.credits.get_usage_history(limit=1000)
    
    # Analyze by service type
    service_analysis = defaultdict(lambda: {
        'total_credits': 0,
        'total_duration': 0,
        'usage_count': 0,
        'average_cost': 0
    })
    
    # Daily usage tracking
    daily_usage = defaultdict(int)
    
    for log in usage_logs:
        service = log['service_type']
        credits = log['credits_used']
        duration = log.get('audio_duration', 0)
        date = datetime.fromisoformat(log['created_at'].replace('Z', '+00:00')).date()
        
        # Service analysis
        service_analysis[service]['total_credits'] += credits
        service_analysis[service]['total_duration'] += duration
        service_analysis[service]['usage_count'] += 1
        
        # Daily usage
        daily_usage[date] += credits
    
    # Calculate averages
    for service in service_analysis:
        data = service_analysis[service]
        if data['usage_count'] > 0:
            data['average_cost'] = data['total_credits'] / data['usage_count']
    
    # Generate report
    print("\n📊 Credit Usage Analysis")
    print("=" * 50)
    
    print("\n🎯 Usage by Service:")
    for service, data in sorted(service_analysis.items(), key=lambda x: x[1]['total_credits'], reverse=True):
        print(f"  {service}:")
        print(f"    Total Credits: {data['total_credits']:,}")
        print(f"    Average per Use: {data['average_cost']:.1f}")
        print(f"    Usage Count: {data['usage_count']}")
        if data['total_duration'] > 0:
            print(f"    Total Duration: {data['total_duration']:.1f}s")
        print()
    
    # Show cost optimization tips
    print("💡 Optimization Tips:")
    most_used = max(service_analysis.items(), key=lambda x: x[1]['total_credits'])
    print(f"  • {most_used[0]} is your highest cost service ({most_used[1]['total_credits']} credits)")
    
    # Check for batch opportunities
    for service, data in service_analysis.items():
        if data['usage_count'] > 10 and data['average_cost'] < 100:
            print(f"  • Consider batching {service} requests to reduce API overhead")
    
    return service_analysis

# Run analysis
analysis = analyze_credit_usage()

Integration Examples

Real-time Balance Monitoring

class AudioPodCreditManager:
def __init__(self, api_key):
    self.api_key = api_key
    self.base_url = "https://api.audiopod.ai/api/v1"
    self.headers = {"Authorization": f"Bearer {api_key}"}

def get_balance(self):
    """Get current credit balance"""
    response = requests.get(
        f"{self.base_url}/credits",
        headers=self.headers
    )
    return response.json()

def check_sufficient_credits(self, service_type, duration_seconds=0):
    """Check if user has enough credits for a service"""
    # Get current balance
    balance = self.get_balance()
    available = balance['total_available_credits']
    
    # Get service costs
    multipliers_response = requests.get(
        f"{self.base_url}/credits/multipliers",
        headers=self.headers
    )
    costs = multipliers_response.json()
    
    # Calculate required credits
    if service_type == "voice_cloning_generation":
        required = (duration_seconds / 60) * costs['voice_cloning_generation']
    elif service_type == "transcription":
        required = (duration_seconds / 60) * costs['transcription']
    elif service_type == "music_generation":
        required = (duration_seconds / 30) * costs['music_generation']
    else:
        required = costs.get(service_type, 0)
    
    return {
        'sufficient': available >= required,
        'available': available,
        'required': required,
        'shortfall': max(0, required - available)
    }

def get_usage_summary(self, days=30):
    """Get usage summary for the last N days"""
    usage_response = requests.get(
        f"{self.base_url}/credits/usage",
        headers=self.headers
    )
    
    usage_logs = usage_response.json()
    
    # Filter by date range
    from datetime import datetime, timedelta
    cutoff_date = datetime.now() - timedelta(days=days)
    
    recent_usage = []
    for log in usage_logs:
        log_date = datetime.fromisoformat(log['created_at'].replace('Z', '+00:00'))
        if log_date >= cutoff_date:
            recent_usage.append(log)
    
    # Summarize
    total_credits = sum(log['credits_used'] for log in recent_usage)
    service_breakdown = {}
    
    for log in recent_usage:
        service = log['service_type']
        service_breakdown[service] = service_breakdown.get(service, 0) + log['credits_used']
    
    return {
        'period_days': days,
        'total_credits_used': total_credits,
        'service_breakdown': service_breakdown,
        'usage_count': len(recent_usage)
    }

# Usage example
credit_manager = AudioPodCreditManager("your_api_key")

# Check if user can afford a 2-minute Text to Speech
check = credit_manager.check_sufficient_credits("voice_cloning_generation", 120)
if check['sufficient']:
print("User has enough credits")
else:
print(f"Need {check['shortfall']} more credits")

# Get 30-day usage summary
summary = credit_manager.get_usage_summary(30)
print(f"Used {summary['total_credits_used']} credits in last 30 days")

Cost Estimation

def estimate_service_cost(service_type, **params):
    """Estimate credit cost for different services"""
    
    # Get current multipliers
    response = requests.get(
        "https://api.audiopod.ai/api/v1/credits/multipliers",
        headers={"Authorization": f"Bearer {api_key}"}
    )
    costs = response.json()
    
    estimates = {
        'voice_cloning_training': lambda: costs['voice_cloning_training'],  # Fixed cost
        'voice_cloning_generation': lambda: (params.get('duration', 60) / 60) * costs['voice_cloning_generation'],
        'transcription': lambda: (params.get('duration', 60) / 60) * costs['transcription'],
        'transcription_with_speakers': lambda: (params.get('duration', 60) / 60) * costs['transcription_with_diarization'],
        'music_generation': lambda: (params.get('duration', 30) / 30) * costs['music_generation'],
        'translation': lambda: (params.get('duration', 60) / 60) * costs['translation'],
        'text_to_speech': lambda: (params.get('characters', 1000) / 1000) * costs['text_to_speech']
    }
    
    if service_type in estimates:
        credits_needed = estimates[service_type]()
        usd_cost = credits_needed * 0.001  # $0.001 per credit
        
        return {
            'service': service_type,
            'credits_needed': int(credits_needed),
            'usd_cost': round(usd_cost, 4),
            'parameters': params
        }
    
    return None

# Examples
print(estimate_service_cost('voice_cloning_generation', duration=120))  # 2 minutes
print(estimate_service_cost('transcription', duration=1800))  # 30 minutes
print(estimate_service_cost('music_generation', duration=60))  # 1 minute
print(estimate_service_cost('text_to_speech', characters=5000))  # 5000 characters

Error Handling

Causes: - Not enough credits for requested service - Credit balance is zero Solutions: - Purchase additional PAYG credits - Check credit balance before requests - Upgrade to higher credit plan
Causes: - PAYG amount below minimum (1)PAYGamountabovemaximum(1) - PAYG amount above maximum (1000) Solutions: - Use amount between 11-1000 - Check PAYG info endpoint for current limits
Causes: - No credit usage history - User account newly created Solutions: - Use some services to generate usage history - Check after making API calls

Credit Management Best Practices

Monitor Usage Regularly

# Set up usage alerts
def setup_credit_alerts(api_key, warning_threshold=500, critical_threshold=100):
"""Monitor credits and alert when running low"""

balance = get_credit_balance(api_key)
available = balance['total_available_credits']

if available <= critical_threshold:
    send_alert(f"CRITICAL: Only {available} credits remaining!")
    # Auto-purchase more credits
    purchase_credits(api_key, amount_usd=50)
elif available <= warning_threshold:
    send_alert(f"WARNING: {available} credits remaining")

return available

# Optimize usage patterns
def optimize_credit_usage():
"""Tips for efficient credit usage"""
tips = [
    "Batch similar requests together",
    "Use appropriate quality settings for your use case", 
    "Cache results when possible to avoid re-processing",
    "Choose efficient models (faster-whisper vs whisperx)",
    "Monitor usage patterns to identify optimization opportunities"
]
return tips

Bulk Operations

def process_bulk_efficiently(files, operation_type):
    """Process multiple files efficiently"""
    
    # Check total credit requirement first
    total_credits_needed = 0
    for file_info in files:
        credits = estimate_service_cost(operation_type, **file_info)['credits_needed']
        total_credits_needed += credits
    
    # Verify sufficient credits
    balance = get_credit_balance(api_key)
    if balance['total_available_credits'] < total_credits_needed:
        print(f"Need {total_credits_needed - balance['total_available_credits']} more credits")
        return False
    
    # Process in optimal batches
    batch_size = 5  # Optimal batch size
    for i in range(0, len(files), batch_size):
        batch = files[i:i + batch_size]
        process_batch(batch, operation_type)
        
        return True

Next Steps