curl -X GET "https://api.tensorone.ai/v2/billing/usage" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -G \
  -d "timeRange=current_month" \
  -d "granularity=daily" \
  -d "includeProjections=true" \
  -d "resourceType[]=clusters&resourceType[]=ai-services"
{
  "period": {
    "startDate": "2024-01-01",
    "endDate": "2024-01-31",
    "billingCycle": "monthly",
    "daysInPeriod": 31,
    "daysElapsed": 16
  },
  "summary": {
    "totalCost": 1247.83,
    "totalGpuHours": 156.7,
    "totalApiRequests": 89543,
    "totalStorageGB": 2847.3,
    "totalBandwidthGB": 1256.8,
    "currency": "USD"
  },
  "breakdown": [
    {
      "resourceType": "clusters",
      "usage": {
        "quantity": 156.7,
        "unit": "gpu_hours",
        "cost": 784.50,
        "percentage": 62.9
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 8.3,
          "cost": 41.50
        },
        {
          "timestamp": "2024-01-15T00:00:00Z", 
          "value": 12.1,
          "cost": 60.50
        }
      ],
      "topResources": [
        {
          "resourceId": "cluster-gpu-a100-001",
          "name": "GPU Cluster A100-001",
          "usage": 45.2,
          "cost": 226.00
        },
        {
          "resourceId": "cluster-gpu-h100-002",
          "name": "GPU Cluster H100-002", 
          "usage": 38.7,
          "cost": 193.50
        }
      ]
    },
    {
      "resourceType": "ai-services",
      "usage": {
        "quantity": 89543,
        "unit": "requests",
        "cost": 268.63,
        "percentage": 21.5
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 5420,
          "cost": 16.26
        }
      ],
      "topResources": [
        {
          "resourceId": "text-to-image",
          "name": "Text-to-Image Generation",
          "usage": 34562,
          "cost": 103.69
        },
        {
          "resourceId": "text-to-speech", 
          "name": "Text-to-Speech Synthesis",
          "usage": 28341,
          "cost": 85.02
        }
      ]
    },
    {
      "resourceType": "storage",
      "usage": {
        "quantity": 2847.3,
        "unit": "gb_hours",
        "cost": 142.37,
        "percentage": 11.4
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 2847.3,
          "cost": 8.90
        }
      ],
      "topResources": []
    },
    {
      "resourceType": "bandwidth",
      "usage": {
        "quantity": 1256.8,
        "unit": "gb",
        "cost": 52.33,
        "percentage": 4.2
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 78.4,
          "cost": 3.27
        }
      ],
      "topResources": []
    }
  ],
  "regional": [
    {
      "region": "us-east-1",
      "usage": {
        "totalCost": 743.21,
        "gpuHours": 93.4,
        "apiRequests": 52847
      },
      "cost": 743.21,
      "percentage": 59.6
    },
    {
      "region": "us-west-2",
      "usage": {
        "totalCost": 312.84,
        "gpuHours": 38.9,
        "apiRequests": 23156
      },
      "cost": 312.84,
      "percentage": 25.1
    },
    {
      "region": "eu-west-1",
      "usage": {
        "totalCost": 191.78,
        "gpuHours": 24.4,
        "apiRequests": 13540
      },
      "cost": 191.78,
      "percentage": 15.4
    }
  ],
  "projections": {
    "projectedCost": 2418.67,
    "projectedUsage": {
      "gpuHours": 303.8,
      "apiRequests": 173650,
      "storageGB": 5515.2
    },
    "confidence": 0.87,
    "trend": "increasing"
  },
  "alerts": [
    {
      "type": "budget_exceeded",
      "severity": "medium",
      "message": "Monthly GPU usage has exceeded 80% of allocated budget",
      "threshold": 1000.00,
      "currentValue": 1247.83
    },
    {
      "type": "unusual_spike",
      "severity": "low",
      "message": "AI service requests increased by 45% compared to last week",
      "threshold": 25.0,
      "currentValue": 45.2
    }
  ]
}
Monitor detailed usage metrics for GPU clusters, serverless endpoints, AI services, and storage to understand consumption patterns and optimize costs.

Request Parameters

timeRange
string
default:"current_month"
Time period for usage data:
  • current_month - Current billing month
  • last_month - Previous billing month
  • current_quarter - Current quarter
  • last_quarter - Previous quarter
  • current_year - Current year
  • custom - Custom date range (requires startDate and endDate)
startDate
string
Start date for custom time range (ISO 8601 format: YYYY-MM-DD)
endDate
string
End date for custom time range (ISO 8601 format: YYYY-MM-DD)
resourceType
array
Filter by resource types:
  • clusters - GPU cluster usage
  • endpoints - Serverless endpoint usage
  • training - Model training jobs
  • ai-services - AI generation services
  • storage - Data storage usage
  • bandwidth - Data transfer usage
granularity
string
default:"daily"
Data granularity:
  • hourly - Hour-by-hour breakdown
  • daily - Daily usage totals
  • weekly - Weekly usage summaries
  • monthly - Monthly usage summaries
groupBy
array
Group usage data by:
  • resource - Group by individual resources
  • region - Group by geographical region
  • project - Group by project/team
  • service - Group by service type
  • user - Group by user (for team accounts)
includeProjections
boolean
default:"false"
Include usage projections and forecasts for the current billing period
includeCosts
boolean
default:"true"
Include cost calculations for usage metrics
currency
string
default:"USD"
Currency for cost calculations: USD, EUR, GBP, JPY, CAD, AUD

Response

period
object
Time period information
summary
object
Usage summary totals
breakdown
array
Detailed usage breakdown by resource type
regional
array
Usage breakdown by region
projections
object
Usage projections (if requested)
alerts
array
Usage-related alerts and thresholds

Example

curl -X GET "https://api.tensorone.ai/v2/billing/usage" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -G \
  -d "timeRange=current_month" \
  -d "granularity=daily" \
  -d "includeProjections=true" \
  -d "resourceType[]=clusters&resourceType[]=ai-services"
{
  "period": {
    "startDate": "2024-01-01",
    "endDate": "2024-01-31",
    "billingCycle": "monthly",
    "daysInPeriod": 31,
    "daysElapsed": 16
  },
  "summary": {
    "totalCost": 1247.83,
    "totalGpuHours": 156.7,
    "totalApiRequests": 89543,
    "totalStorageGB": 2847.3,
    "totalBandwidthGB": 1256.8,
    "currency": "USD"
  },
  "breakdown": [
    {
      "resourceType": "clusters",
      "usage": {
        "quantity": 156.7,
        "unit": "gpu_hours",
        "cost": 784.50,
        "percentage": 62.9
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 8.3,
          "cost": 41.50
        },
        {
          "timestamp": "2024-01-15T00:00:00Z", 
          "value": 12.1,
          "cost": 60.50
        }
      ],
      "topResources": [
        {
          "resourceId": "cluster-gpu-a100-001",
          "name": "GPU Cluster A100-001",
          "usage": 45.2,
          "cost": 226.00
        },
        {
          "resourceId": "cluster-gpu-h100-002",
          "name": "GPU Cluster H100-002", 
          "usage": 38.7,
          "cost": 193.50
        }
      ]
    },
    {
      "resourceType": "ai-services",
      "usage": {
        "quantity": 89543,
        "unit": "requests",
        "cost": 268.63,
        "percentage": 21.5
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 5420,
          "cost": 16.26
        }
      ],
      "topResources": [
        {
          "resourceId": "text-to-image",
          "name": "Text-to-Image Generation",
          "usage": 34562,
          "cost": 103.69
        },
        {
          "resourceId": "text-to-speech", 
          "name": "Text-to-Speech Synthesis",
          "usage": 28341,
          "cost": 85.02
        }
      ]
    },
    {
      "resourceType": "storage",
      "usage": {
        "quantity": 2847.3,
        "unit": "gb_hours",
        "cost": 142.37,
        "percentage": 11.4
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 2847.3,
          "cost": 8.90
        }
      ],
      "topResources": []
    },
    {
      "resourceType": "bandwidth",
      "usage": {
        "quantity": 1256.8,
        "unit": "gb",
        "cost": 52.33,
        "percentage": 4.2
      },
      "timeSeries": [
        {
          "timestamp": "2024-01-16T00:00:00Z",
          "value": 78.4,
          "cost": 3.27
        }
      ],
      "topResources": []
    }
  ],
  "regional": [
    {
      "region": "us-east-1",
      "usage": {
        "totalCost": 743.21,
        "gpuHours": 93.4,
        "apiRequests": 52847
      },
      "cost": 743.21,
      "percentage": 59.6
    },
    {
      "region": "us-west-2",
      "usage": {
        "totalCost": 312.84,
        "gpuHours": 38.9,
        "apiRequests": 23156
      },
      "cost": 312.84,
      "percentage": 25.1
    },
    {
      "region": "eu-west-1",
      "usage": {
        "totalCost": 191.78,
        "gpuHours": 24.4,
        "apiRequests": 13540
      },
      "cost": 191.78,
      "percentage": 15.4
    }
  ],
  "projections": {
    "projectedCost": 2418.67,
    "projectedUsage": {
      "gpuHours": 303.8,
      "apiRequests": 173650,
      "storageGB": 5515.2
    },
    "confidence": 0.87,
    "trend": "increasing"
  },
  "alerts": [
    {
      "type": "budget_exceeded",
      "severity": "medium",
      "message": "Monthly GPU usage has exceeded 80% of allocated budget",
      "threshold": 1000.00,
      "currentValue": 1247.83
    },
    {
      "type": "unusual_spike",
      "severity": "low",
      "message": "AI service requests increased by 45% compared to last week",
      "threshold": 25.0,
      "currentValue": 45.2
    }
  ]
}

Advanced Usage Analytics

Cost Optimization Analysis

Python
def analyze_cost_optimization_opportunities():
    """Identify opportunities to reduce costs"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/usage/optimization",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params={
            "timeRange": "last_month",
            "includeRecommendations": True,
            "analysisDepth": "detailed"
        }
    )
    
    return response.json()

def generate_cost_report():
    """Generate comprehensive cost analysis report"""
    optimization_data = analyze_cost_optimization_opportunities()
    
    print("💡 Cost Optimization Report")
    print("=" * 35)
    
    # Potential savings
    if 'potentialSavings' in optimization_data:
        savings = optimization_data['potentialSavings']
        total_savings = savings['totalMonthly']
        print(f"Potential Monthly Savings: ${total_savings:,.2f}")
        print()
        
        # Savings by category
        for category in savings['byCategory']:
            print(f"📊 {category['name']}:")
            print(f"   Current Cost: ${category['currentCost']:,.2f}")
            print(f"   Potential Savings: ${category['savings']:,.2f} ({category['percentage']:.1f}%)")
            print(f"   Recommendation: {category['recommendation']}")
            print()
    
    # Optimization recommendations
    if 'recommendations' in optimization_data:
        print("🎯 Optimization Recommendations:")
        print("-" * 35)
        
        for i, rec in enumerate(optimization_data['recommendations'][:5], 1):
            impact_icon = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(rec['impact'], "⚪")
            
            print(f"{i}. {impact_icon} {rec['title']}")
            print(f"   Impact: {rec['impact']} - ${rec['potentialSavings']:,.2f}/month")
            print(f"   Description: {rec['description']}")
            print(f"   Effort: {rec['implementationEffort']}")
            print()
    
    # Waste identification
    if 'wasteAnalysis' in optimization_data:
        waste = optimization_data['wasteAnalysis']
        print(f"🗑️  Identified Waste: ${waste['totalWaste']:,.2f}/month")
        
        for waste_item in waste['items']:
            print(f"   • {waste_item['description']}: ${waste_item['amount']:,.2f}")

# Run cost optimization analysis
generate_cost_report()

Usage Forecasting

Python
def get_usage_forecast(forecast_period="3_months"):
    """Get usage and cost forecasts"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/usage/forecast",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params={
            "forecastPeriod": forecast_period,
            "includeScenarios": True,
            "confidenceInterval": 0.95
        }
    )
    
    return response.json()

def analyze_usage_trends():
    """Analyze usage trends and forecasts"""
    forecast_data = get_usage_forecast("6_months")
    
    print("🔮 Usage Forecast Analysis")
    print("=" * 30)
    
    baseline = forecast_data['baseline']
    print(f"Current Monthly Average: ${baseline['avgMonthlyCost']:,.2f}")
    print(f"Growth Rate: {baseline['growthRate']:+.1f}% per month")
    print()
    
    # Monthly projections
    print("📅 Monthly Projections:")
    for month in forecast_data['monthlyProjections']:
        month_name = month['month']
        projected_cost = month['projectedCost']
        confidence = month['confidence']
        
        print(f"  {month_name}: ${projected_cost:,.2f} (confidence: {confidence:.0%})")
    
    # Scenario analysis
    if 'scenarios' in forecast_data:
        print(f"\n📊 Scenario Analysis:")
        scenarios = forecast_data['scenarios']
        
        for scenario_name, scenario_data in scenarios.items():
            print(f"  {scenario_name.title()} Case:")
            print(f"    6-month total: ${scenario_data['sixMonthTotal']:,.2f}")
            print(f"    Peak month: ${scenario_data['peakMonth']:,.2f}")
            print(f"    Probability: {scenario_data['probability']:.0%}")
            print()
    
    # Growth drivers
    if 'growthDrivers' in forecast_data:
        print("📈 Key Growth Drivers:")
        for driver in forecast_data['growthDrivers']:
            print(f"  • {driver['factor']}: +{driver['impact']:,.2f}/month")
            print(f"    {driver['description']}")

analyze_usage_trends()

Team Usage Monitoring

Python
def get_team_usage_breakdown():
    """Get usage breakdown by team/project"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/usage",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params={
            "timeRange": "current_month",
            "groupBy": ["project", "user"],
            "includeTeamMetrics": True
        }
    )
    
    return response.json()

def generate_team_usage_report():
    """Generate team usage accountability report"""
    team_data = get_team_usage_breakdown()
    
    print("👥 Team Usage Report")
    print("=" * 25)
    
    if 'teamBreakdown' in team_data:
        teams = team_data['teamBreakdown']
        
        # Sort teams by cost
        teams_sorted = sorted(teams, key=lambda x: x['totalCost'], reverse=True)
        
        print("Top Teams by Cost:")
        print("-" * 20)
        
        for i, team in enumerate(teams_sorted[:10], 1):
            team_name = team['teamName']
            team_cost = team['totalCost']
            team_percentage = team['percentage']
            member_count = team['memberCount']
            avg_per_member = team_cost / member_count if member_count > 0 else 0
            
            print(f"{i:2d}. {team_name}")
            print(f"    Total: ${team_cost:,.2f} ({team_percentage:.1f}%)")
            print(f"    Members: {member_count}")
            print(f"    Avg/Member: ${avg_per_member:,.2f}")
            print()
        
        # Resource utilization by team
        print("Resource Utilization by Team:")
        print("-" * 32)
        
        for team in teams_sorted[:5]:
            print(f"\n🏢 {team['teamName']}:")
            
            resources = team.get('resourceUsage', {})
            for resource, usage in resources.items():
                print(f"  {resource.title()}: {usage['quantity']:,.1f} {usage['unit']} (${usage['cost']:,.2f})")
    
    # Individual user breakdown
    if 'userBreakdown' in team_data:
        users = team_data['userBreakdown']
        top_users = sorted(users, key=lambda x: x['totalCost'], reverse=True)[:10]
        
        print(f"\n👤 Top Users by Cost:")
        print("-" * 20)
        
        for i, user in enumerate(top_users, 1):
            user_name = user['userName']
            user_cost = user['totalCost']
            user_team = user.get('team', 'N/A')
            
            print(f"{i:2d}. {user_name} ({user_team}): ${user_cost:,.2f}")

generate_team_usage_report()

Usage Alerts and Budgets

Budget Management

Python
def set_usage_budget(budget_amount, alert_thresholds, resource_types=None):
    """Set monthly usage budget with alerts"""
    budget_config = {
        "monthlyBudget": budget_amount,
        "currency": "USD",
        "alertThresholds": alert_thresholds,  # e.g., [50, 75, 90, 100]
        "resourceTypes": resource_types or ["all"],
        "notificationChannels": ["email", "webhook"],
        "actions": {
            "at_90_percent": "send_warning",
            "at_100_percent": ["send_alert", "notify_admin"],
            "at_110_percent": ["send_critical", "auto_limit"]
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/billing/budgets",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=budget_config
    )
    
    return response.json()

def monitor_budget_status():
    """Monitor current budget status"""
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/budgets/status",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    
    budget_status = response.json()
    
    print("💰 Budget Status Monitor")
    print("=" * 25)
    
    for budget in budget_status['budgets']:
        budget_name = budget.get('name', 'Default Budget')
        budget_amount = budget['monthlyBudget']
        spent_amount = budget['currentSpent']
        percentage_used = (spent_amount / budget_amount) * 100
        remaining = budget_amount - spent_amount
        days_left = budget['daysRemainingInPeriod']
        
        status_icon = "🔴" if percentage_used >= 100 else "🟡" if percentage_used >= 75 else "🟢"
        
        print(f"{status_icon} {budget_name}")
        print(f"  Budget: ${budget_amount:,.2f}")
        print(f"  Spent: ${spent_amount:,.2f} ({percentage_used:.1f}%)")
        print(f"  Remaining: ${remaining:,.2f}")
        print(f"  Days Left: {days_left}")
        
        if percentage_used > 0 and days_left > 0:
            daily_burn_rate = spent_amount / (30 - days_left) if days_left < 30 else 0
            projected_total = spent_amount + (daily_burn_rate * days_left)
            print(f"  Projected Total: ${projected_total:,.2f}")
        
        print()

# Set up budget alerts
budget_result = set_usage_budget(
    budget_amount=2000.00,
    alert_thresholds=[50, 75, 90, 100],
    resource_types=["clusters", "ai-services"]
)

print(f"Budget created: {budget_result.get('budgetId', 'N/A')}")

# Monitor budget status
monitor_budget_status()

Best Practices

Usage Monitoring

  • Regular Reviews: Check usage patterns weekly to identify trends
  • Budget Alerts: Set up proactive alerts before reaching limits
  • Resource Tagging: Use consistent tagging for better cost allocation
  • Granular Tracking: Monitor usage at resource and team levels

Cost Optimization

  • Right-sizing: Regularly review and adjust resource allocations
  • Scheduling: Use scheduling for non-critical workloads
  • Reserved Capacity: Consider reserved instances for predictable workloads
  • Waste Elimination: Identify and eliminate unused resources

Team Management

  • Cost Allocation: Implement clear cost allocation policies
  • Usage Guidelines: Provide teams with usage best practices
  • Regular Reporting: Share usage reports with stakeholders
  • Accountability: Assign cost responsibility to appropriate teams
Usage data is updated every hour and billing calculations are finalized daily. Real-time usage tracking may show slight delays compared to actual resource consumption.
Use usage projections and forecasts to plan capacity and budget for upcoming periods. Set up automated alerts to catch unusual usage patterns early.