> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tensorone.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Usage Tracking

> Track and monitor resource usage, compute consumption, and service utilization across your TensorOne account

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

**Period Details**

**startDate** `string`

Period start date (ISO 8601)

**endDate** `string`

Period end date (ISO 8601)

**billingCycle** `string`

Current billing cycle: `monthly`, `quarterly`, `annual`

**daysInPeriod** `integer`

Total days in the billing period

**daysElapsed** `integer`

Days elapsed in current period

**summary** `object`

Usage summary totals

**Usage Summary**

**totalCost** `number`

Total cost for the period

**totalGpuHours** `number`

Total GPU compute hours consumed

**totalApiRequests** `integer`

Total API requests made

**totalStorageGB** `number`

Total storage used in GB

**totalBandwidthGB** `number`

Total bandwidth consumed in GB

**currency** `string`

Currency code for cost values

**breakdown** `array`

Detailed usage breakdown by resource type

**Resource Usage**

**resourceType** `string`

Type of resource (clusters, endpoints, etc.)

**usage** `object`

Usage metrics for this resource type

**Usage Metrics**

**quantity** `number`

Usage quantity (hours, requests, GB, etc.)

**unit** `string`

Unit of measurement

**cost** `number`

Cost for this resource type

**percentage** `number`

Percentage of total usage

**timeSeries** `array`

Time series data for usage over the period

**Time Series Point**

**timestamp** `string`

Data point timestamp

**value** `number`

Usage value at this time

**cost** `number`

Cost at this time point

**topResources** `array`

Individual resources with highest usage

**regional** `array`

Usage breakdown by region

**Regional Usage**

**region** `string`

Region identifier

**usage** `object`

Regional usage metrics

**cost** `number`

Regional cost total

**percentage** `number`

Percentage of total regional usage

**projections** `object`

Usage projections (if requested)

**Usage Projections**

**projectedCost** `number`

Projected cost for end of current period

**projectedUsage** `object`

Projected usage metrics

**confidence** `number`

Projection confidence score (0.0-1.0)

**trend** `string`

Usage trend: `increasing`, `decreasing`, `stable`

**alerts** `array`

Usage-related alerts and thresholds

**Usage Alert**

**type** `string`

Alert type: `budget_exceeded`, `unusual_spike`, `quota_approaching`

**severity** `string`

Alert severity: `low`, `medium`, `high`, `critical`

**message** `string`

Alert description

**threshold** `number`

Threshold value that triggered alert

**currentValue** `number`

Current usage value

## Example

```bash cURL
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"
```

```python Python
import requests
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime, timedelta

def get_usage_data(time_range="current_month", resource_types=None, include_projections=False):
    params = {
        'timeRange': time_range,
        'granularity': 'daily',
        'includeProjections': include_projections,
        'includeCosts': True,
        'currency': 'USD'
    }
    
    if resource_types:
        params['resourceType'] = resource_types
    
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/usage",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response.json()

# Get current month usage
usage_data = get_usage_data(
    time_range="current_month",
    resource_types=["clusters", "ai-services", "endpoints"],
    include_projections=True
)

print("💰 Usage Summary - Current Month")
print("=" * 40)

# Display summary
summary = usage_data['summary']
period = usage_data['period']

print(f"Period: {period['startDate']} to {period['endDate']}")
print(f"Days Elapsed: {period['daysElapsed']}/{period['daysInPeriod']}")
print(f"\nTotal Cost: ${summary['totalCost']:,.2f} {summary['currency']}")
print(f"GPU Hours: {summary['totalGpuHours']:,.1f}")
print(f"API Requests: {summary['totalApiRequests']:,}")
print(f"Storage: {summary['totalStorageGB']:,.1f} GB")
print(f"Bandwidth: {summary['totalBandwidthGB']:,.1f} GB")

# Resource breakdown
print(f"\n📊 Resource Breakdown:")
print("-" * 30)

for resource in usage_data['breakdown']:
    resource_type = resource['resourceType'].title()
    usage_info = resource['usage']
    cost = usage_info['cost']
    percentage = usage_info['percentage']
    quantity = usage_info['quantity']
    unit = usage_info['unit']
    
    print(f"{resource_type}: ${cost:,.2f} ({percentage:.1f}%)")
    print(f"  Usage: {quantity:,.1f} {unit}")
    
    # Show top resources
    if resource.get('topResources'):
        print(f"  Top consumers:")
        for top_resource in resource['topResources'][:3]:
            print(f"    • {top_resource['name']}: {top_resource['usage']:,.1f} {unit}")

# Regional breakdown
if usage_data.get('regional'):
    print(f"\n🌍 Regional Distribution:")
    print("-" * 25)
    
    for region in usage_data['regional']:
        region_name = region['region']
        region_cost = region['cost']
        region_pct = region['percentage']
        print(f"{region_name}: ${region_cost:,.2f} ({region_pct:.1f}%)")

# Projections and alerts
if usage_data.get('projections'):
    proj = usage_data['projections']
    print(f"\n🔮 End-of-Month Projection:")
    print(f"Projected Cost: ${proj['projectedCost']:,.2f}")
    print(f"Confidence: {proj['confidence']:.0%}")
    print(f"Trend: {proj['trend'].title()}")

# Check for alerts
if usage_data.get('alerts'):
    print(f"\n⚠️  Usage Alerts ({len(usage_data['alerts'])}):")
    for alert in usage_data['alerts']:
        severity_icon = {
            'critical': '🔴',
            'high': '🟠', 
            'medium': '🟡',
            'low': '🟢'
        }.get(alert['severity'], '⚪')
        
        print(f"  {severity_icon} {alert['message']}")
        print(f"     Current: {alert['currentValue']}, Threshold: {alert['threshold']}")

# Create usage visualization
def plot_usage_trends(usage_data):
    """Plot usage trends over time"""
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
    
    # Daily cost trend
    cost_data = []
    dates = []
    
    for resource in usage_data['breakdown']:
        if resource['timeSeries']:
            for point in resource['timeSeries']:
                date = datetime.fromisoformat(point['timestamp'].replace('Z', '+00:00')).date()
                if date not in [d['date'] for d in cost_data]:
                    cost_data.append({'date': date, 'cost': 0})
                
                # Find the date entry and add cost
                for entry in cost_data:
                    if entry['date'] == date:
                        entry['cost'] += point['cost']
                        break
    
    if cost_data:
        cost_data.sort(key=lambda x: x['date'])
        dates = [entry['date'] for entry in cost_data]
        costs = [entry['cost'] for entry in cost_data]
        
        ax1.plot(dates, costs, marker='o', linewidth=2, markersize=4)
        ax1.set_title('Daily Cost Trend')
        ax1.set_ylabel('Cost ($)')
        ax1.grid(True, alpha=0.3)
        ax1.tick_params(axis='x', rotation=45)
    
    # Resource type distribution
    resource_names = []
    resource_costs = []
    
    for resource in usage_data['breakdown']:
        resource_names.append(resource['resourceType'].title())
        resource_costs.append(resource['usage']['cost'])
    
    colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7']
    wedges, texts, autotexts = ax2.pie(
        resource_costs, 
        labels=resource_names, 
        colors=colors[:len(resource_names)],
        autopct='%1.1f%%',
        startangle=90
    )
    ax2.set_title('Cost Distribution by Resource Type')
    
    plt.tight_layout()
    plt.show()

# Uncomment to show plots
# plot_usage_trends(usage_data)

# Get detailed usage for specific time range
def get_custom_usage_report(start_date, end_date):
    """Get usage for custom date range"""
    usage = get_usage_data("custom")
    
    # Update with custom dates
    custom_params = {
        'timeRange': 'custom',
        'startDate': start_date,
        'endDate': end_date,
        'granularity': 'daily',
        'groupBy': ['resource', 'region']
    }
    
    response = requests.get(
        "https://api.tensorone.ai/v2/billing/usage",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=custom_params
    )
    
    return response.json()

# Example: Get last 7 days usage
last_week_start = (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d')
yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')

# weekly_usage = get_custom_usage_report(last_week_start, yesterday)
# print(f"Last 7 days total cost: ${weekly_usage['summary']['totalCost']:,.2f}")
```

```javascript JavaScript
const getUsageData = async (options = {}) => {
  const params = new URLSearchParams({
    timeRange: options.timeRange || 'current_month',
    granularity: options.granularity || 'daily',
    includeProjections: options.includeProjections || false,
    includeCosts: options.includeCosts !== false
  });

  if (options.resourceType) {
    const resourceTypes = Array.isArray(options.resourceType) ? options.resourceType : [options.resourceType];
    resourceTypes.forEach(type => params.append('resourceType[]', type));
  }

  if (options.groupBy) {
    const groupBy = Array.isArray(options.groupBy) ? options.groupBy : [options.groupBy];
    groupBy.forEach(group => params.append('groupBy[]', group));
  }

  const response = await fetch(`https://api.tensorone.ai/v2/billing/usage?${params}`, {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });

  return await response.json();
};

// Get current month usage with projections
getUsageData({
  timeRange: 'current_month',
  resourceType: ['clusters', 'ai-services'],
  includeProjections: true,
  groupBy: ['resource', 'region']
}).then(data => {
  console.log('💰 Usage Dashboard');
  console.log('==================');
  
  const summary = data.summary;
  const period = data.period;
  
  console.log(`Period: ${period.startDate} to ${period.endDate}`);
  console.log(`Progress: ${period.daysElapsed}/${period.daysInPeriod} days`);
  console.log(`\nTotal Cost: $${summary.totalCost.toLocaleString()}`);
  console.log(`GPU Hours: ${summary.totalGpuHours.toLocaleString()}`);
  console.log(`API Requests: ${summary.totalApiRequests.toLocaleString()}`);
  
  // Resource breakdown
  console.log('\n📊 Resource Breakdown:');
  data.breakdown.forEach(resource => {
    const name = resource.resourceType.charAt(0).toUpperCase() + resource.resourceType.slice(1);
    const cost = resource.usage.cost;
    const percentage = resource.usage.percentage;
    console.log(`${name}: $${cost.toLocaleString()} (${percentage.toFixed(1)}%)`);
  });
  
  // Projections
  if (data.projections) {
    const proj = data.projections;
    console.log('\n🔮 Month-End Projection:');
    console.log(`Projected Cost: $${proj.projectedCost.toLocaleString()}`);
    console.log(`Confidence: ${(proj.confidence * 100).toFixed(0)}%`);
    console.log(`Trend: ${proj.trend}`);
  }
  
  // Alerts
  if (data.alerts && data.alerts.length > 0) {
    console.log(`\n⚠️ Usage Alerts (${data.alerts.length}):`);
    data.alerts.forEach(alert => {
      const severityIcon = {
        'critical': '🔴',
        'high': '🟠',
        'medium': '🟡',
        'low': '🟢'
      }[alert.severity] || '⚪';
      
      console.log(`${severityIcon} ${alert.message}`);
    });
  }
});

// Export usage data for external analysis
const exportUsageData = async (timeRange, format = 'csv') => {
  const params = new URLSearchParams({
    timeRange,
    format, // csv, json, xlsx
    includeDetails: true
  });

  const response = await fetch(`https://api.tensorone.ai/v2/billing/usage/export?${params}`, {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });

  if (format === 'json') {
    return await response.json();
  } else {
    return await response.blob();
  }
};

// Usage analytics
const analyzeUsagePatterns = async () => {
  const [currentMonth, lastMonth] = await Promise.all([
    getUsageData({ timeRange: 'current_month' }),
    getUsageData({ timeRange: 'last_month' })
  ]);

  const currentCost = currentMonth.summary.totalCost;
  const lastCost = lastMonth.summary.totalCost;
  const costChange = ((currentCost - lastCost) / lastCost) * 100;

  console.log('\n📈 Usage Analysis:');
  console.log(`Current Month: $${currentCost.toLocaleString()}`);
  console.log(`Last Month: $${lastCost.toLocaleString()}`);
  console.log(`Change: ${costChange > 0 ? '+' : ''}${costChange.toFixed(1)}%`);

  return {
    currentMonth: currentCost,
    lastMonth: lastCost,
    percentageChange: costChange
  };
};

// Run analysis
analyzeUsagePatterns();
```

```json Response
{
  "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 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 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 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 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

> [!NOTE]
>
> 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.

> [!TIP]
>
> Use usage projections and forecasts to plan capacity and budget for upcoming periods. Set up automated alerts to catch unusual usage patterns early.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.