API
Analytics

Analytics API

The Analytics API provides comprehensive usage statistics, performance metrics, and insights for your Dispersl AI agent workflows.

Overview

The Analytics API enables you to:

  • Monitor usage patterns: Track API calls, token consumption, and agent activity
  • Analyze performance: Review task success rates, execution times, and efficiency metrics
  • Understand costs: Monitor token usage and associated costs across different models
  • Generate reports: Create detailed analytics reports for teams and projects
  • Optimize workflows: Identify bottlenecks and improvement opportunities

Endpoints

Get Usage Statistics

GET /analytics/usage

Retrieves comprehensive usage statistics for the authenticated user.

Query Parameters

  • period (optional): Time period for statistics (day, week, month, year) - default: month
  • from_date (optional): Start date for custom period (ISO 8601 format)
  • to_date (optional): End date for custom period (ISO 8601 format)

Headers

Authorization: Bearer YOUR_API_KEY

Response

{
  "status": "success",
  "message": "Usage statistics retrieved successfully",
  "data": {
    "period": "month",
    "from_date": "2024-01-01T00:00:00Z",
    "to_date": "2024-01-31T23:59:59Z",
    "summary": {
      "total_tasks": 45,
      "completed_tasks": 42,
      "failed_tasks": 3,
      "success_rate": 93.3,
      "total_steps": 180,
      "total_tokens": 125000,
      "total_api_calls": 890,
      "average_task_duration": "2h 30m"
    },
    "by_agent": {
      "code_agent": {
        "tasks": 18,
        "steps": 72,
        "tokens": 45000,
        "success_rate": 94.4
      },
      "test_agent": {
        "tasks": 12,
        "steps": 48,
        "tokens": 28000,
        "success_rate": 91.7
      },
      "git_agent": {
        "tasks": 8,
        "steps": 32,
        "tokens": 15000,
        "success_rate": 100.0
      },
      "document_agent": {
        "tasks": 7,
        "steps": 28,
        "tokens": 37000,
        "success_rate": 85.7
      }
    },
    "by_model": {
      "anthropic/claude-3-sonnet": {
        "tasks": 25,
        "tokens": 75000,
        "average_tokens_per_task": 3000,
        "success_rate": 96.0
      },
      "openai/gpt-4": {
        "tasks": 15,
        "tokens": 35000,
        "average_tokens_per_task": 2333,
        "success_rate": 93.3
      },
      "deepseek/deepseek-r1": {
        "tasks": 5,
        "tokens": 15000,
        "average_tokens_per_task": 3000,
        "success_rate": 80.0
      }
    },
    "daily_breakdown": [
      {
        "date": "2024-01-01",
        "tasks": 2,
        "tokens": 5500,
        "api_calls": 28
      },
      {
        "date": "2024-01-02",
        "tasks": 1,
        "tokens": 2800,
        "api_calls": 15
      }
    ]
  }
}

Get Performance Metrics

GET /analytics/performance

Retrieves detailed performance metrics and trends.

Query Parameters

  • period (optional): Time period for metrics (day, week, month, year) - default: month
  • metric (optional): Specific metric to focus on (duration, success_rate, token_efficiency)

Headers

Authorization: Bearer YOUR_API_KEY

Response

{
  "status": "success",
  "message": "Performance metrics retrieved successfully",
  "data": {
    "period": "month",
    "metrics": {
      "task_completion_rate": {
        "current": 93.3,
        "previous": 89.2,
        "trend": "up",
        "change": 4.1
      },
      "average_task_duration": {
        "current": "2h 30m",
        "previous": "2h 45m",
        "trend": "down",
        "change": "-15m"
      },
      "token_efficiency": {
        "current": 2.78,
        "previous": 3.12,
        "trend": "up",
        "change": 0.34,
        "unit": "tokens_per_minute"
      },
      "error_rate": {
        "current": 6.7,
        "previous": 10.8,
        "trend": "down",
        "change": -4.1
      }
    },
    "performance_by_agent": {
      "code_agent": {
        "avg_duration": "3h 15m",
        "success_rate": 94.4,
        "token_efficiency": 2.45
      },
      "test_agent": {
        "avg_duration": "1h 45m",
        "success_rate": 91.7,
        "token_efficiency": 3.20
      },
      "git_agent": {
        "avg_duration": "45m",
        "success_rate": 100.0,
        "token_efficiency": 4.15
      },
      "document_agent": {
        "avg_duration": "2h 30m",
        "success_rate": 85.7,
        "token_efficiency": 2.10
      }
    }
  }
}

Get Cost Analysis

GET /analytics/costs

Retrieves detailed cost analysis and token usage breakdown.

Query Parameters

  • period (optional): Time period for cost analysis (day, week, month, year) - default: month
  • currency (optional): Currency for cost display (USD, EUR, GBP) - default: USD

Headers

Authorization: Bearer YOUR_API_KEY

Response

{
  "status": "success",
  "message": "Cost analysis retrieved successfully",
  "data": {
    "period": "month",
    "currency": "USD",
    "total_cost": 187.50,
    "total_tokens": 125000,
    "average_cost_per_task": 4.17,
    "cost_by_model": {
      "anthropic/claude-3-sonnet": {
        "tokens": 75000,
        "cost": 112.50,
        "cost_per_token": 0.0015,
        "percentage": 60.0
      },
      "openai/gpt-4": {
        "tokens": 35000,
        "cost": 52.50,
        "cost_per_token": 0.0015,
        "percentage": 28.0
      },
      "deepseek/deepseek-r1": {
        "tokens": 15000,
        "cost": 22.50,
        "cost_per_token": 0.0015,
        "percentage": 12.0
      }
    },
    "cost_by_agent": {
      "code_agent": {
        "cost": 67.50,
        "percentage": 36.0
      },
      "test_agent": {
        "cost": 42.00,
        "percentage": 22.4
      },
      "document_agent": {
        "cost": 55.50,
        "percentage": 29.6
      },
      "git_agent": {
        "cost": 22.50,
        "percentage": 12.0
      }
    },
    "daily_costs": [
      {
        "date": "2024-01-01",
        "cost": 8.25,
        "tokens": 5500
      },
      {
        "date": "2024-01-02",
        "cost": 4.20,
        "tokens": 2800
      }
    ]
  }
}

Analytics Dashboards

Usage Dashboard

async function createUsageDashboard() {
  const response = await fetch('/api/analytics/usage?period=month', {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });
  
  const analytics = await response.json();
  const data = analytics.data;
  
  return {
    totalTasks: data.summary.total_tasks,
    successRate: data.summary.success_rate,
    totalTokens: data.summary.total_tokens,
    mostUsedAgent: Object.keys(data.by_agent).reduce((a, b) => 
      data.by_agent[a].tasks > data.by_agent[b].tasks ? a : b
    ),
    preferredModel: Object.keys(data.by_model).reduce((a, b) => 
      data.by_model[a].tasks > data.by_model[b].tasks ? a : b
    )
  };
}

Performance Trends

async function getPerformanceTrends() {
  const response = await fetch('/api/analytics/performance?period=month', {
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY'
    }
  });
  
  const performance = await response.json();
  const metrics = performance.data.metrics;
  
  return {
    completionRate: {
      value: metrics.task_completion_rate.current,
      trend: metrics.task_completion_rate.trend,
      change: metrics.task_completion_rate.change
    },
    avgDuration: {
      value: metrics.average_task_duration.current,
      trend: metrics.average_task_duration.trend,
      change: metrics.average_task_duration.change
    },
    tokenEfficiency: {
      value: metrics.token_efficiency.current,
      trend: metrics.token_efficiency.trend,
      change: metrics.token_efficiency.change
    }
  };
}

Key Performance Indicators (KPIs)

Task Success Metrics

  • Completion Rate: Percentage of tasks that complete successfully
  • Average Duration: Mean time to complete tasks
  • Error Rate: Percentage of tasks that fail
  • Retry Rate: Percentage of tasks that require retries

Resource Utilization

  • Token Efficiency: Tokens consumed per unit of work completed
  • Model Utilization: Distribution of usage across different AI models
  • Agent Utilization: Distribution of work across different agent types
  • Peak Usage Times: Identification of high-activity periods

Cost Optimization

  • Cost per Task: Average cost to complete a task
  • Token Cost Efficiency: Cost per token across different models
  • Budget Utilization: Percentage of allocated budget consumed
  • Cost Trends: Month-over-month cost changes

Best Practices

Monitoring Strategy

  1. Set up alerts: Monitor key metrics and set thresholds for notifications
  2. Regular reviews: Schedule weekly/monthly analytics reviews
  3. Trend analysis: Look for patterns and anomalies in usage data
  4. Cost optimization: Regularly review model usage and costs

Performance Optimization

  1. Agent selection: Use analytics to choose the most effective agents
  2. Model optimization: Select models based on cost-effectiveness and performance
  3. Task structuring: Optimize task breakdown based on success patterns
  4. Resource allocation: Distribute workload based on agent performance

Reporting

async function generateMonthlyReport() {
  const [usage, performance, costs] = await Promise.all([
    fetch('/api/analytics/usage?period=month'),
    fetch('/api/analytics/performance?period=month'),
    fetch('/api/analytics/costs?period=month')
  ].map(p => p.then(r => r.json())));
  
  return {
    summary: {
      totalTasks: usage.data.summary.total_tasks,
      successRate: usage.data.summary.success_rate,
      totalCost: costs.data.total_cost,
      avgTaskDuration: performance.data.metrics.average_task_duration.current
    },
    trends: {
      completionRateTrend: performance.data.metrics.task_completion_rate.trend,
      costTrend: costs.data.total_cost > 150 ? 'high' : 'normal',
      efficiencyTrend: performance.data.metrics.token_efficiency.trend
    },
    recommendations: generateRecommendations(usage, performance, costs)
  };
}

Error Responses

  • 400: Invalid query parameters or date format
  • 401: No Bearer token provided
  • 403: Insufficient permissions for analytics data
  • 500: Internal server error

Data Retention

  • Free Tier: 30 days of analytics data
  • Pro Tier: 90 days of analytics data
  • Enterprise Tier: 1 year of analytics data with custom retention options

Export Options

Export analytics data for external analysis:

# Export usage data as CSV
curl -X GET "https://api.dispersl.com/v1/analytics/usage/export?format=csv&period=month" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -o usage_analytics.csv
 
# Export performance metrics as JSON
curl -X GET "https://api.dispersl.com/v1/analytics/performance/export?format=json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -o performance_metrics.json