> ## 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.

# Dashboard Management

> Create, manage, and customize monitoring dashboards for comprehensive visualization of TensorOne infrastructure metrics

Build custom monitoring dashboards with real-time metrics, visualizations, and insights to monitor your TensorOne infrastructure and applications effectively.

## Request Parameters

**dashboardId** `string`

Specific dashboard ID to retrieve. If not provided, returns list of available dashboards.

**includeData** `boolean` (default: false)

Whether to include current metric data with dashboard configuration

**timeRange** `string` (default: 1h)

Time range for dashboard data:

* `5m` - Last 5 minutes
* `15m` - Last 15 minutes
* `1h` - Last hour
* `6h` - Last 6 hours
* `24h` - Last 24 hours
* `7d` - Last 7 days
* `30d` - Last 30 days

**refresh** `boolean` (default: false)

Force refresh of cached dashboard data

**format** `string` (default: json)

Response format:

* `json` - JSON response
* `export` - Export format for sharing
* `embed` - Embeddable HTML format

**filters** `object`

Filters to apply to dashboard data:

* `regions` - Array of region codes
* `resourceIds` - Array of specific resource IDs
* `tags` - Array of tags to filter by

## Response

**dashboards** `array`

Array of dashboard objects (when no specific dashboardId provided)

**Dashboard Object**

**dashboardId** `string`

Unique dashboard identifier

**name** `string`

Dashboard name

**description** `string`

Dashboard description

**type** `string`

Dashboard type: `system`, `custom`, `template`

**category** `string`

Dashboard category: `infrastructure`, `application`, `business`, `security`

**layout** `object`

Dashboard layout configuration

**Layout**

**grid** `object`

Grid configuration (rows, columns)

**widgets** `array`

Array of widget configurations

**theme** `string`

Visual theme: `light`, `dark`, `auto`

**widgets** `array`

Dashboard widgets

**Widget**

**widgetId** `string`

Unique widget identifier

**title** `string`

Widget title

**type** `string`

Widget type: `metric`, `chart`, `table`, `gauge`, `heatmap`, `alert_list`

**position** `object`

Widget position and size in grid

**config** `object`

Widget-specific configuration

**dataSource** `object`

Data source configuration

**data** `object`

Current widget data (if includeData=true)

**permissions** `object`

Dashboard access permissions

**Permissions**

**owner** `string`

Dashboard owner user ID

**shared** `boolean`

Whether dashboard is shared

**viewers** `array`

Users with view access

**editors** `array`

Users with edit access

**public** `boolean`

Whether dashboard is publicly accessible

**metadata** `object`

Dashboard metadata

**Metadata**

**createdAt** `string`

Creation timestamp

**updatedAt** `string`

Last update timestamp

**version** `string`

Dashboard version

**tags** `array`

Dashboard tags

**autoRefresh** `integer`

Auto-refresh interval in seconds

**templates** `array`

Available dashboard templates

**Dashboard Template**

**templateId** `string`

Template identifier

**name** `string`

Template name

**description** `string`

Template description

**category** `string`

Template category

**preview** `string`

Preview image URL

## Example

```bash cURL
curl -X GET "https://api.tensorone.ai/v2/monitoring/dashboards" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -G \
  -d "includeData=true" \
  -d "timeRange=6h"
```

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

def get_dashboards(include_data=False, time_range="1h"):
    params = {
        'includeData': include_data,
        'timeRange': time_range
    }
    
    response = requests.get(
        "https://api.tensorone.ai/v2/monitoring/dashboards",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response.json()

def get_dashboard_data(dashboard_id, time_range="1h", filters=None):
    params = {
        'includeData': True,
        'timeRange': time_range
    }
    
    if filters:
        params['filters'] = json.dumps(filters)
    
    response = requests.get(
        f"https://api.tensorone.ai/v2/monitoring/dashboards/{dashboard_id}",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response.json()

# Get available dashboards
dashboards = get_dashboards(include_data=True, time_range="6h")

print("📊 Available Dashboards:")
print("=" * 30)

for dashboard in dashboards['dashboards']:
    print(f"\n🎯 {dashboard['name']} ({dashboard['type']})")
    print(f"   Category: {dashboard['category']}")
    print(f"   Widgets: {len(dashboard['widgets'])}")
    print(f"   Last Updated: {dashboard['metadata']['updatedAt']}")
    
    if dashboard['permissions']['shared']:
        print("   🔗 Shared dashboard")

# Get specific dashboard with data
infrastructure_dashboard = None
for dashboard in dashboards['dashboards']:
    if dashboard['category'] == 'infrastructure':
        infrastructure_dashboard = dashboard
        break

if infrastructure_dashboard:
    print(f"\n📈 Infrastructure Dashboard Analysis:")
    print("=" * 40)
    
    for widget in infrastructure_dashboard['widgets']:
        print(f"\n📊 {widget['title']} ({widget['type']})")
        
        if widget.get('data'):
            data = widget['data']
            
            if widget['type'] == 'metric':
                current_value = data.get('currentValue', 0)
                previous_value = data.get('previousValue', 0)
                change = ((current_value - previous_value) / previous_value) * 100 if previous_value > 0 else 0
                
                trend_icon = "📈" if change > 0 else "📉" if change < 0 else "➡️"
                print(f"   Current: {current_value} {trend_icon} {change:+.1f}%")
            
            elif widget['type'] == 'chart':
                if 'timeSeries' in data:
                    series_count = len(data['timeSeries'])
                    data_points = len(data['timeSeries'][0]['data']) if series_count > 0 else 0
                    print(f"   Series: {series_count}, Data Points: {data_points}")
            
            elif widget['type'] == 'table':
                if 'rows' in data:
                    print(f"   Rows: {len(data['rows'])}")

# Create custom dashboard visualization
def create_dashboard_summary(dashboard_data):
    """Create a summary visualization of dashboard metrics"""
    fig, axes = plt.subplots(2, 2, figsize=(15, 10))
    fig.suptitle('TensorOne Infrastructure Dashboard', fontsize=16)
    
    # Extract metric data from widgets
    cpu_data = []
    memory_data = []
    gpu_data = []
    timestamps = []
    
    for widget in dashboard_data['widgets']:
        if widget.get('data') and widget['type'] == 'chart':
            data = widget['data']
            if 'timeSeries' in data:
                for series in data['timeSeries']:
                    if 'cpu' in series['name'].lower():
                        cpu_data = series['data']
                        timestamps = series['timestamps']
                    elif 'memory' in series['name'].lower():
                        memory_data = series['data']
                    elif 'gpu' in series['name'].lower():
                        gpu_data = series['data']
    
    if timestamps and cpu_data:
        # Convert timestamps
        time_points = [datetime.fromisoformat(ts.replace('Z', '+00:00')) for ts in timestamps]
        
        # CPU utilization
        axes[0, 0].plot(time_points, cpu_data, 'b-', linewidth=2)
        axes[0, 0].set_title('CPU Utilization (%)')
        axes[0, 0].grid(True, alpha=0.3)
        axes[0, 0].set_ylim(0, 100)
        
        # Memory utilization
        if memory_data:
            axes[0, 1].plot(time_points, memory_data, 'g-', linewidth=2)
            axes[0, 1].set_title('Memory Utilization (%)')
            axes[0, 1].grid(True, alpha=0.3)
            axes[0, 1].set_ylim(0, 100)
        
        # GPU utilization
        if gpu_data:
            axes[1, 0].plot(time_points, gpu_data, 'r-', linewidth=2)
            axes[1, 0].set_title('GPU Utilization (%)')
            axes[1, 0].grid(True, alpha=0.3)
            axes[1, 0].set_ylim(0, 100)
        
        # Resource distribution pie chart
        current_cpu = cpu_data[-1] if cpu_data else 0
        current_memory = memory_data[-1] if memory_data else 0
        current_gpu = gpu_data[-1] if gpu_data else 0
        
        resources = ['CPU', 'Memory', 'GPU']
        utilization = [current_cpu, current_memory, current_gpu]
        colors = ['#FF6B6B', '#4ECDC4', '#45B7D1']
        
        axes[1, 1].pie(utilization, labels=resources, colors=colors, autopct='%1.1f%%')
        axes[1, 1].set_title('Current Resource Utilization')
    
    plt.tight_layout()
    plt.show()

# Uncomment to create visualization
# if infrastructure_dashboard:
#     create_dashboard_summary(infrastructure_dashboard)
```

```javascript JavaScript
const getDashboards = async (options = {}) => {
  const params = new URLSearchParams({
    includeData: options.includeData || false,
    timeRange: options.timeRange || '1h'
  });

  if (options.filters) {
    params.append('filters', JSON.stringify(options.filters));
  }

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

  return await response.json();
};

const createDashboard = async (dashboardConfig) => {
  const response = await fetch('https://api.tensorone.ai/v2/monitoring/dashboards', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(dashboardConfig)
  });

  return await response.json();
};

// Get dashboards with data
getDashboards({
  includeData: true,
  timeRange: '6h'
}).then(data => {
  console.log('📊 Dashboard Overview');
  console.log('====================');
  
  data.dashboards.forEach(dashboard => {
    console.log(`\n${dashboard.name} (${dashboard.type})`);
    console.log(`  Category: ${dashboard.category}`);
    console.log(`  Widgets: ${dashboard.widgets.length}`);
    console.log(`  Updated: ${dashboard.metadata.updatedAt}`);
    
    // Show widget summary
    const widgetTypes = {};
    dashboard.widgets.forEach(widget => {
      widgetTypes[widget.type] = (widgetTypes[widget.type] || 0) + 1;
    });
    
    console.log('  Widget Types:', Object.entries(widgetTypes)
      .map(([type, count]) => `${type}(${count})`)
      .join(', '));
  });
});

// Create a custom dashboard
const customDashboard = {
  name: 'GPU Cluster Monitoring',
  description: 'Monitor GPU cluster performance and utilization',
  category: 'infrastructure',
  layout: {
    grid: { rows: 3, columns: 4 },
    theme: 'dark'
  },
  widgets: [
    {
      title: 'GPU Utilization',
      type: 'gauge',
      position: { row: 0, col: 0, width: 2, height: 1 },
      config: {
        metric: 'gpu_utilization',
        thresholds: { warning: 80, critical: 95 },
        unit: '%'
      },
      dataSource: {
        resource: 'clusters',
        aggregation: 'avg'
      }
    },
    {
      title: 'Memory Usage Trend',
      type: 'chart',
      position: { row: 0, col: 2, width: 2, height: 1 },
      config: {
        chartType: 'line',
        metrics: ['memory_utilization'],
        timeRange: '1h'
      },
      dataSource: {
        resource: 'clusters',
        granularity: '1m'
      }
    }
  ],
  permissions: {
    shared: true,
    public: false
  },
  metadata: {
    tags: ['gpu', 'performance', 'monitoring'],
    autoRefresh: 30
  }
};

createDashboard(customDashboard).then(result => {
  console.log('Dashboard created:', result.dashboardId);
});
```

```json Response
{
  "dashboards": [
    {
      "dashboardId": "dashboard-infra-001",
      "name": "Infrastructure Overview",
      "description": "Comprehensive infrastructure monitoring dashboard",
      "type": "system",
      "category": "infrastructure",
      "layout": {
        "grid": {
          "rows": 4,
          "columns": 6
        },
        "widgets": 8,
        "theme": "dark"
      },
      "widgets": [
        {
          "widgetId": "widget-cpu-001",
          "title": "CPU Utilization",
          "type": "gauge",
          "position": {
            "row": 0,
            "col": 0,
            "width": 2,
            "height": 1
          },
          "config": {
            "metric": "cpu_utilization",
            "thresholds": {
              "warning": 70,
              "critical": 90
            },
            "unit": "%",
            "displayFormat": "percentage"
          },
          "dataSource": {
            "resource": "clusters",
            "aggregation": "avg",
            "timeRange": "5m"
          },
          "data": {
            "currentValue": 68.5,
            "previousValue": 65.2,
            "status": "normal",
            "trend": "increasing"
          }
        },
        {
          "widgetId": "widget-memory-chart-001",
          "title": "Memory Usage Trend",
          "type": "chart",
          "position": {
            "row": 0,
            "col": 2,
            "width": 4,
            "height": 2
          },
          "config": {
            "chartType": "line",
            "metrics": ["memory_utilization"],
            "yAxis": {
              "min": 0,
              "max": 100,
              "unit": "%"
            },
            "legend": true,
            "colors": ["#4ECDC4"]
          },
          "dataSource": {
            "resource": "clusters",
            "granularity": "1m",
            "timeRange": "1h"
          },
          "data": {
            "timeSeries": [
              {
                "name": "Memory Utilization",
                "data": [72.1, 73.5, 74.2, 75.8, 76.3],
                "timestamps": [
                  "2024-01-16T17:00:00Z",
                  "2024-01-16T17:01:00Z",
                  "2024-01-16T17:02:00Z",
                  "2024-01-16T17:03:00Z",
                  "2024-01-16T17:04:00Z"
                ]
              }
            ]
          }
        },
        {
          "widgetId": "widget-alerts-001",
          "title": "Active Alerts",
          "type": "alert_list",
          "position": {
            "row": 2,
            "col": 0,
            "width": 6,
            "height": 1
          },
          "config": {
            "maxItems": 5,
            "severityFilter": ["critical", "high"],
            "showResolved": false
          },
          "dataSource": {
            "resource": "alerts",
            "status": "active"
          },
          "data": {
            "alerts": [
              {
                "alertId": "alert-001",
                "title": "High GPU utilization on cluster-001",
                "severity": "high",
                "timestamp": "2024-01-16T17:45:00Z"
              }
            ],
            "totalCount": 3
          }
        }
      ],
      "permissions": {
        "owner": "admin@company.com",
        "shared": true,
        "viewers": ["team@company.com"],
        "editors": ["ops@company.com"],
        "public": false
      },
      "metadata": {
        "createdAt": "2024-01-15T10:00:00Z",
        "updatedAt": "2024-01-16T14:30:00Z",
        "version": "1.2",
        "tags": ["infrastructure", "monitoring", "system"],
        "autoRefresh": 30
      }
    }
  ],
  "templates": [
    {
      "templateId": "template-gpu-monitoring",
      "name": "GPU Cluster Monitoring",
      "description": "Pre-configured dashboard for GPU cluster monitoring",
      "category": "infrastructure",
      "preview": "https://assets.tensorone.ai/dashboard-previews/gpu-monitoring.png"
    },
    {
      "templateId": "template-cost-optimization",
      "name": "Cost Optimization Dashboard",
      "description": "Track costs and identify optimization opportunities",
      "category": "business",
      "preview": "https://assets.tensorone.ai/dashboard-previews/cost-optimization.png"
    }
  ]
}
```

## Dashboard Management Operations

### Create Custom Dashboard

```python Python
def create_custom_dashboard(name, description, widgets, category="custom"):
    """Create a new custom dashboard"""
    dashboard_config = {
        "name": name,
        "description": description,
        "category": category,
        "layout": {
            "grid": {"rows": 4, "columns": 6},
            "theme": "dark"
        },
        "widgets": widgets,
        "permissions": {
            "shared": False,
            "public": False
        },
        "metadata": {
            "tags": ["custom"],
            "autoRefresh": 60
        }
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/monitoring/dashboards",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=dashboard_config
    )
    
    return response.json()

# Define widgets for AI services dashboard
ai_widgets = [
    {
        "title": "AI Request Volume",
        "type": "metric",
        "position": {"row": 0, "col": 0, "width": 2, "height": 1},
        "config": {
            "metric": "request_count",
            "aggregation": "sum",
            "timeRange": "1h",
            "unit": "requests"
        },
        "dataSource": {
            "resource": "ai-services"
        }
    },
    {
        "title": "Response Time Distribution",
        "type": "chart",
        "position": {"row": 0, "col": 2, "width": 4, "height": 2},
        "config": {
            "chartType": "histogram",
            "metric": "response_time",
            "buckets": [0, 100, 500, 1000, 2000, 5000],
            "unit": "ms"
        },
        "dataSource": {
            "resource": "ai-services",
            "timeRange": "6h"
        }
    },
    {
        "title": "Service Health Heatmap",
        "type": "heatmap",
        "position": {"row": 2, "col": 0, "width": 6, "height": 2},
        "config": {
            "metric": "availability",
            "xAxis": "service",
            "yAxis": "region",
            "colorScale": "green-red"
        },
        "dataSource": {
            "resource": "ai-services",
            "granularity": "15m"
        }
    }
]

# Create AI services dashboard
ai_dashboard = create_custom_dashboard(
    "AI Services Performance",
    "Monitor AI service performance, response times, and availability",
    ai_widgets,
    "application"
)

print(f"Created dashboard: {ai_dashboard['dashboardId']}")
```

### Dashboard Templates

```python Python
def create_dashboard_from_template(template_id, name, customizations=None):
    """Create dashboard from template with customizations"""
    config = {
        "templateId": template_id,
        "name": name,
        "customizations": customizations or {}
    }
    
    response = requests.post(
        "https://api.tensorone.ai/v2/monitoring/dashboards/from-template",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=config
    )
    
    return response.json()

def get_dashboard_templates(category=None):
    """Get available dashboard templates"""
    params = {}
    if category:
        params['category'] = category
    
    response = requests.get(
        "https://api.tensorone.ai/v2/monitoring/dashboards/templates",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response.json()

# Get available templates
templates = get_dashboard_templates("infrastructure")

print("📋 Available Dashboard Templates:")
for template in templates['templates']:
    print(f"  • {template['name']} - {template['description']}")

# Create dashboard from GPU monitoring template
gpu_dashboard = create_dashboard_from_template(
    "template-gpu-monitoring",
    "Production GPU Clusters",
    customizations={
        "filters": {
            "regions": ["us-east-1", "us-west-2"],
            "tags": ["production"]
        },
        "theme": "dark",
        "autoRefresh": 30
    }
)

print(f"Created GPU dashboard: {gpu_dashboard['dashboardId']}")
```

### Dashboard Sharing and Collaboration

```python Python
def share_dashboard(dashboard_id, share_config):
    """Share dashboard with users or make public"""
    response = requests.post(
        f"https://api.tensorone.ai/v2/monitoring/dashboards/{dashboard_id}/share",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=share_config
    )
    
    return response.json()

def generate_embed_code(dashboard_id, options=None):
    """Generate embeddable code for dashboard"""
    params = {
        "theme": options.get("theme", "dark") if options else "dark",
        "autoRefresh": options.get("autoRefresh", 60) if options else 60,
        "showControls": options.get("showControls", True) if options else True
    }
    
    response = requests.get(
        f"https://api.tensorone.ai/v2/monitoring/dashboards/{dashboard_id}/embed",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response.json()

# Share dashboard with team
share_result = share_dashboard("dashboard-infra-001", {
    "shared": True,
    "viewers": ["team@company.com", "stakeholders@company.com"],
    "editors": ["devops@company.com"],
    "public": False,
    "permissions": {
        "allowExport": True,
        "allowDuplicate": True
    }
})

print(f"Dashboard shared: {share_result['shareUrl']}")

# Generate embed code for external use
embed_result = generate_embed_code("dashboard-infra-001", {
    "theme": "light",
    "autoRefresh": 120,
    "showControls": False
})

print("Embed code generated:")
print(embed_result['embedCode'])
```

## Advanced Dashboard Features

### Real-time Dashboard Updates

```python Python
import websocket
import json
import threading

class DashboardRealTimeUpdater:
    def __init__(self, api_key, dashboard_id):
        self.api_key = api_key
        self.dashboard_id = dashboard_id
        self.ws = None
        self.data_cache = {}
    
    def connect_websocket(self):
        """Connect to real-time dashboard updates"""
        ws_url = f"wss://api.tensorone.ai/v2/monitoring/dashboards/{self.dashboard_id}/realtime"
        
        def on_message(ws, message):
            data = json.loads(message)
            self.handle_update(data)
        
        def on_error(ws, error):
            print(f"WebSocket error: {error}")
        
        def on_close(ws, close_status_code, close_msg):
            print("WebSocket connection closed")
        
        def on_open(ws):
            print("Connected to dashboard real-time updates")
            # Send authentication
            auth_message = {
                "type": "auth",
                "token": self.api_key
            }
            ws.send(json.dumps(auth_message))
        
        self.ws = websocket.WebSocketApp(
            ws_url,
            on_open=on_open,
            on_message=on_message,
            on_error=on_error,
            on_close=on_close
        )
        
        # Run in background thread
        ws_thread = threading.Thread(target=self.ws.run_forever)
        ws_thread.daemon = True
        ws_thread.start()
    
    def handle_update(self, data):
        """Handle real-time dashboard updates"""
        if data['type'] == 'widget_update':
            widget_id = data['widgetId']
            widget_data = data['data']
            
            print(f"📊 Widget Update: {widget_id}")
            
            if widget_data['type'] == 'metric':
                current = widget_data['currentValue']
                previous = self.data_cache.get(widget_id, {}).get('currentValue', current)
                change = ((current - previous) / previous * 100) if previous > 0 else 0
                
                trend_icon = "📈" if change > 5 else "📉" if change < -5 else "➡️"
                print(f"  Value: {current} {trend_icon} {change:+.1f}%")
            
            elif widget_data['type'] == 'alert':
                alerts = widget_data.get('alerts', [])
                if alerts:
                    for alert in alerts[-3:]:  # Show last 3 alerts
                        severity_icon = {"critical": "🔴", "high": "🟠", "medium": "🟡"}.get(alert['severity'], "⚪")
                        print(f"  {severity_icon} {alert['title']}")
            
            # Update cache
            self.data_cache[widget_id] = widget_data
        
        elif data['type'] == 'dashboard_alert':
            print(f"🚨 Dashboard Alert: {data['message']}")

# Usage
updater = DashboardRealTimeUpdater("YOUR_API_KEY", "dashboard-infra-001")
updater.connect_websocket()

# Keep running to receive updates
# time.sleep(300)  # Run for 5 minutes
```

### Dashboard Analytics and Insights

```python Python
def get_dashboard_analytics(dashboard_id, time_range="7d"):
    """Get analytics about dashboard usage and performance"""
    response = requests.get(
        f"https://api.tensorone.ai/v2/monitoring/dashboards/{dashboard_id}/analytics",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params={"timeRange": time_range}
    )
    
    return response.json()

def generate_dashboard_insights(dashboard_id):
    """Generate AI-powered insights about dashboard data"""
    response = requests.get(
        f"https://api.tensorone.ai/v2/monitoring/dashboards/{dashboard_id}/insights",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    )
    
    return response.json()

# Get dashboard analytics
analytics = get_dashboard_analytics("dashboard-infra-001", "30d")

print("📈 Dashboard Analytics (Last 30 Days):")
print("=" * 40)
print(f"Views: {analytics['usage']['totalViews']}")
print(f"Unique Viewers: {analytics['usage']['uniqueViewers']}")
print(f"Avg Session Duration: {analytics['usage']['avgSessionDuration']}")
print(f"Most Viewed Widget: {analytics['widgets']['mostViewed']['title']}")

# Performance insights
if 'performance' in analytics:
    perf = analytics['performance']
    print(f"\nDashboard Performance:")
    print(f"  Load Time: {perf['avgLoadTime']}ms")
    print(f"  Data Freshness: {perf['avgDataFreshness']}s")
    print(f"  Update Frequency: {perf['updateFrequency']}/min")

# Get AI insights
insights = generate_dashboard_insights("dashboard-infra-001")

print(f"\n🧠 AI-Powered Insights:")
print("=" * 25)

for insight in insights['insights']:
    priority_icon = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(insight['priority'], "⚪")
    print(f"\n{priority_icon} {insight['title']}")
    print(f"   {insight['description']}")
    
    if insight.get('recommendation'):
        print(f"   💡 Recommendation: {insight['recommendation']}")
    
    if insight.get('impact'):
        print(f"   📊 Potential Impact: {insight['impact']}")

# Trend analysis
if 'trends' in insights:
    print(f"\n📊 Trend Analysis:")
    for trend in insights['trends']:
        direction_icon = "📈" if trend['direction'] == 'increasing' else "📉"
        print(f"  {direction_icon} {trend['metric']}: {trend['description']}")
        print(f"     Confidence: {trend['confidence']:.0%}")
```

### Dashboard Export and Backup

```python Python
def export_dashboard(dashboard_id, format_type="json", include_data=False):
    """Export dashboard configuration and optionally data"""
    params = {
        "format": format_type,  # json, yaml, pdf
        "includeData": include_data,
        "includeMetadata": True
    }
    
    response = requests.get(
        f"https://api.tensorone.ai/v2/monitoring/dashboards/{dashboard_id}/export",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        params=params
    )
    
    return response

def backup_all_dashboards():
    """Backup all user dashboards"""
    dashboards = get_dashboards()
    backups = []
    
    for dashboard in dashboards['dashboards']:
        if dashboard['type'] == 'custom':  # Only backup custom dashboards
            print(f"Backing up: {dashboard['name']}")
            
            backup = export_dashboard(
                dashboard['dashboardId'], 
                format_type="json", 
                include_data=False
            )
            
            if backup.status_code == 200:
                backup_data = backup.json()
                backup_data['exportTimestamp'] = datetime.utcnow().isoformat()
                backups.append(backup_data)
                
                # Save to file
                filename = f"dashboard_backup_{dashboard['dashboardId']}_{datetime.now().strftime('%Y%m%d')}.json"
                with open(filename, 'w') as f:
                    json.dump(backup_data, f, indent=2)
                
                print(f"  ✅ Saved to {filename}")
            else:
                print(f"  ❌ Failed to backup {dashboard['name']}")
    
    return backups

def restore_dashboard(backup_file):
    """Restore dashboard from backup"""
    with open(backup_file, 'r') as f:
        backup_data = json.load(f)
    
    # Remove system fields before restore
    dashboard_config = backup_data.copy()
    dashboard_config.pop('dashboardId', None)
    dashboard_config.pop('exportTimestamp', None)
    dashboard_config['name'] = f"{dashboard_config['name']} (Restored)"
    
    response = requests.post(
        "https://api.tensorone.ai/v2/monitoring/dashboards",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=dashboard_config
    )
    
    return response.json()

# Backup all custom dashboards
print("🔄 Starting dashboard backup...")
backups = backup_all_dashboards()
print(f"✅ Backed up {len(backups)} dashboards")

# Example: Restore from backup
# restored = restore_dashboard("dashboard_backup_dashboard-001_20240116.json")
# print(f"Restored dashboard: {restored['dashboardId']}")
```

## Best Practices

### Dashboard Design

* **Clear Hierarchy**: Use logical grouping and visual hierarchy
* **Appropriate Visualizations**: Choose the right chart type for your data
* **Color Consistency**: Use consistent color schemes and meanings
* **Responsive Layout**: Design for different screen sizes

### Performance Optimization

* **Efficient Queries**: Optimize data queries for fast loading
* **Appropriate Refresh Rates**: Balance real-time needs with system load
* **Data Aggregation**: Use appropriate aggregation levels for time ranges
* **Widget Optimization**: Avoid too many widgets on a single dashboard

### User Experience

* **Intuitive Navigation**: Make dashboards easy to navigate and understand
* **Contextual Information**: Provide tooltips and descriptions
* **Interactive Elements**: Use filters and drill-down capabilities
* **Mobile Friendly**: Ensure dashboards work well on mobile devices

### Maintenance

* **Regular Reviews**: Periodically review and update dashboards
* **Performance Monitoring**: Monitor dashboard load times and usage
* **User Feedback**: Collect and act on user feedback
* **Backup Strategy**: Regularly backup custom dashboards

> [!NOTE]
>
> Dashboard data is cached for up to 30 seconds to improve performance. Use the refresh parameter to force immediate data updates when needed.

> [!TIP]
>
> Use dashboard templates as starting points and customize them for your specific needs. Templates are regularly updated with best practices and new visualization options.


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