> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/darkzOGx/youtube-automation-agent/llms.txt
> Use this file to discover all available pages before exploring further.

# AnalyticsOptimizationAgent

> AI-powered analytics and performance optimization agent

## Overview

The `AnalyticsOptimizationAgent` analyzes video performance using YouTube Analytics API and generates actionable insights for optimization. It tracks views, retention, engagement, CTR, demographics, traffic sources, and provides comprehensive performance scoring.

## Constructor

<ParamField path="db" type="Database" required>
  Database instance for analytics history
</ParamField>

<ParamField path="credentials" type="Credentials" required>
  Credentials manager with YouTube Analytics API access
</ParamField>

```javascript theme={null}
const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');

const agent = new AnalyticsOptimizationAgent(db, credentials);
```

## Properties

<ResponseField name="youtubeAnalytics" type="YouTubeAnalyticsAPI">
  YouTube Analytics API v2 client
</ResponseField>

<ResponseField name="youtube" type="YouTubeAPI">
  YouTube Data API v3 client
</ResponseField>

<ResponseField name="performanceData" type="Map">
  Historical performance data cache
</ResponseField>

<ResponseField name="logger" type="Logger">
  Logger instance for tracking analytics
</ResponseField>

## Methods

### initialize()

Initializes the agent and loads historical analytics data.

<ParamField path="return" type="Promise<boolean>">
  Returns true when initialization is complete
</ParamField>

```javascript theme={null}
await agent.initialize();
// Sets up YouTube Analytics API v2 and YouTube Data API v3
// Loads historical performance data from database
```

### analyzeVideoPerformance(videoId)

Performs comprehensive analysis of video performance.

<ParamField path="videoId" type="string" required>
  YouTube video ID
</ParamField>

<ParamField path="return" type="Promise<Object>">
  Complete performance report
</ParamField>

<ResponseField name="report.videoId" type="string">
  YouTube video ID
</ResponseField>

<ResponseField name="report.videoDetails" type="Object">
  Video metadata (title, description, tags, statistics)
</ResponseField>

<ResponseField name="report.analytics" type="Object">
  Analytics data (views, watch time, demographics, traffic, devices, engagement)
</ResponseField>

<ResponseField name="report.thumbnailMetrics" type="Object">
  Thumbnail performance (impressions, CTR, quality, recommendations)
</ResponseField>

<ResponseField name="report.seoMetrics" type="Object">
  SEO performance (title score, description score, tag score, search performance)
</ResponseField>

<ResponseField name="report.insights" type="Array<Object>">
  Actionable insights with recommendations
</ResponseField>

<ResponseField name="report.performance" type="Object">
  Overall performance score with breakdown and grade
</ResponseField>

```javascript theme={null}
const report = await agent.analyzeVideoPerformance('dQw4w9WgXcQ');

console.log(report);
// {
//   videoId: 'dQw4w9WgXcQ',
//   videoDetails: {
//     title: 'JavaScript Tutorial',
//     publishedAt: '2026-03-10T14:00:00.000Z',
//     statistics: { viewCount: 15000, likeCount: 450, commentCount: 89 }
//   },
//   analytics: {
//     views: { totalViews: 15000, totalImpressions: 50000, averageCTR: 7.5 },
//     watchTime: { totalWatchTime: 75000, averageViewDuration: 300, averageViewPercentage: 58.5 },
//     engagement: { engagementRate: 3.6, likeRatio: 97.8, engagementQuality: 'average' },
//     demographics: { primaryAudience: 'males 25-34' },
//     trafficSources: { topSource: 'YOUTUBE_SEARCH', organicPercentage: 65 },
//     devices: { mobilePercentage: '68.5' }
//   },
//   thumbnailMetrics: {
//     impressions: 50000,
//     clickThroughRate: 7.5,
//     ctrQuality: 'good',
//     recommendations: ['Good thumbnail performance', 'Minor optimizations may help']
//   },
//   seoMetrics: {
//     titleScore: 75,
//     descriptionScore: 85,
//     tagScore: 70,
//     overallSEOScore: 77,
//     searchPerformance: { searchPercentage: 35, searchQuality: 'good' }
//   },
//   insights: [
//     {
//       type: 'success',
//       category: 'retention',
//       message: 'Excellent audience retention rate',
//       impact: 'medium'
//     },
//     {
//       type: 'warning',
//       category: 'thumbnail',
//       message: 'Thumbnail could be more compelling',
//       impact: 'high',
//       recommendation: 'Consider A/B testing different designs'
//     }
//   ],
//   performance: {
//     score: 73,
//     breakdown: { views: 22, retention: 15, engagement: 18, ctr: 15 },
//     grade: 'B'
//   },
//   analyzedAt: '2026-03-15T10:00:00.000Z'
// }
```

### getVideoDetails(videoId)

Fetches video metadata from YouTube.

<ParamField path="videoId" type="string" required>
  YouTube video ID
</ParamField>

<ParamField path="return" type="Promise<Object>">
  Video details object
</ParamField>

```javascript theme={null}
const details = await agent.getVideoDetails('dQw4w9WgXcQ');
// {
//   id: 'dQw4w9WgXcQ',
//   title: 'JavaScript Tutorial',
//   description: '...',
//   tags: ['javascript', 'tutorial', ...],
//   publishedAt: '2026-03-10T14:00:00.000Z',
//   duration: 'PT8M30S',
//   statistics: { viewCount: 15000, likeCount: 450, commentCount: 89 }
// }
```

### getVideoAnalytics(videoId)

Fetches comprehensive analytics for a video (last 30 days).

<ParamField path="videoId" type="string" required>
  YouTube video ID
</ParamField>

<ParamField path="return" type="Promise<Object>">
  Analytics data object
</ParamField>

```javascript theme={null}
const analytics = await agent.getVideoAnalytics('dQw4w9WgXcQ');
// {
//   period: { startDate: '2026-02-13', endDate: '2026-03-15' },
//   views: { totalViews: 15000, totalImpressions: 50000, averageCTR: 7.5, dailyData: [...] },
//   watchTime: { totalWatchTime: 75000, averageViewDuration: 300, averageViewPercentage: 58.5, retentionQuality: 'good' },
//   demographics: { ageGroups: [...], gender: [...], primaryAudience: 'males 25-34' },
//   trafficSources: { sources: [...], topSource: 'YOUTUBE_SEARCH', organicPercentage: 65 },
//   devices: { devices: [...], mobilePercentage: '68.5' },
//   engagement: { engagementRate: 3.6, likeRatio: 97.8, commentsPerView: 0.0059, engagementQuality: 'average' }
// }
```

### calculatePerformanceScore(analytics)

Calculates overall performance score (0-100).

<ParamField path="analytics" type="Object" required>
  Analytics data from getVideoAnalytics
</ParamField>

<ParamField path="return" type="Object">
  Performance score with breakdown and grade
</ParamField>

```javascript theme={null}
const performance = agent.calculatePerformanceScore(analytics);
// {
//   score: 73,
//   breakdown: {
//     views: 22,      // 30 points max
//     retention: 15,  // 25 points max
//     engagement: 18, // 25 points max
//     ctr: 15        // 20 points max
//   },
//   grade: 'B'  // A+, A, B, C, D, or F
// }

// Grade thresholds:
// A+: 90+
// A:  80-89
// B:  70-79
// C:  60-69
// D:  50-59
// F:  <50
```

### analyzeThumbnailPerformance(videoId)

Analyzes thumbnail click-through rate.

<ParamField path="videoId" type="string" required>
  YouTube video ID
</ParamField>

<ParamField path="return" type="Promise<Object>">
  Thumbnail metrics with recommendations
</ParamField>

```javascript theme={null}
const thumbnailMetrics = await agent.analyzeThumbnailPerformance('dQw4w9WgXcQ');
// {
//   impressions: 50000,
//   clickThroughRate: 7.5,
//   ctrQuality: 'good',  // excellent (>10), good (6-10), average (3-6), poor (<3)
//   recommendations: [
//     'Good thumbnail performance',
//     'Minor optimizations may help'
//   ]
// }
```

### analyzeSEOPerformance(videoDetails, analytics)

Analyzes SEO optimization quality.

<ParamField path="videoDetails" type="Object" required>
  Video details from getVideoDetails
</ParamField>

<ParamField path="analytics" type="Object" required>
  Analytics data from getVideoAnalytics
</ParamField>

<ParamField path="return" type="Promise<Object>">
  SEO metrics with scores and recommendations
</ParamField>

```javascript theme={null}
const seoMetrics = await agent.analyzeSEOPerformance(videoDetails, analytics);
// {
//   titleScore: 75,        // 0-100
//   descriptionScore: 85,  // 0-100
//   tagScore: 70,          // 0-100
//   overallSEOScore: 77,   // Average of above
//   searchPerformance: {
//     searchPercentage: 35,
//     searchQuality: 'good',  // good (>20), average (10-20), poor (<10)
//     organicDiscovery: true   // true if >30% from search
//   },
//   recommendations: [
//     'Improve description with timestamps and detailed content'
//   ]
// }
```

### generateInsights(videoDetails, analytics, thumbnailMetrics, seoMetrics)

Generates actionable insights from all metrics.

<ParamField path="videoDetails" type="Object" required>
  Video details
</ParamField>

<ParamField path="analytics" type="Object" required>
  Analytics data
</ParamField>

<ParamField path="thumbnailMetrics" type="Object" required>
  Thumbnail metrics
</ParamField>

<ParamField path="seoMetrics" type="Object" required>
  SEO metrics
</ParamField>

<ParamField path="return" type="Promise<Array<Object>>">
  Array of insight objects
</ParamField>

```javascript theme={null}
const insights = await agent.generateInsights(videoDetails, analytics, thumbnailMetrics, seoMetrics);
// [
//   {
//     type: 'success',      // success, warning, or critical
//     category: 'views',     // views, retention, thumbnail, seo, engagement
//     message: 'Video is performing above average in terms of views',
//     impact: 'high'         // high, medium, or low
//   },
//   {
//     type: 'critical',
//     category: 'retention',
//     message: 'Poor audience retention - viewers dropping off early',
//     impact: 'high',
//     recommendation: 'Review content structure and pacing'
//   }
// ]
```

### getRecentAnalytics(days)

Gets analytics summary for recent videos.

<ParamField path="days" type="number" default="7">
  Number of days to look back
</ParamField>

<ParamField path="return" type="Promise<Object>">
  Summary analytics for recent videos
</ParamField>

```javascript theme={null}
const recent = await agent.getRecentAnalytics(7);
// {
//   totalVideos: 3,
//   averagePerformanceScore: 75,
//   topPerformers: [report1, report2, report3],
//   insights: [
//     'Channel is performing well across most metrics',
//     'Some videos showing poor retention - review content quality'
//   ]
// }
```

## Performance Scoring

The agent uses a weighted scoring system:

<CodeGroup>
  ```javascript Views Score (30 points) theme={null}
  // 30 points max
  // Based on view count relative to 10,000 baseline
  viewsScore = Math.min(30, (totalViews / 10000) * 30)
  ```

  ```javascript Retention Score (25 points) theme={null}
  // 25 points max
  // Based on average view percentage
  retentionScore = (averageViewPercentage / 100) * 25
  ```

  ```javascript Engagement Score (25 points) theme={null}
  // 25 points max
  // Based on engagement rate (likes + comments / views)
  engagementScore = Math.min(25, engagementRate * 5)
  ```

  ```javascript CTR Score (20 points) theme={null}
  // 20 points max
  // Based on click-through rate
  ctrScore = Math.min(20, averageCTR * 2)
  ```
</CodeGroup>

## Insight Types and Triggers

<Accordion title="Views Insights">
  * Success: more than 10,000 views
  * Warning: less than 1,000 views (recommend promotion/SEO optimization)
</Accordion>

<Accordion title="Retention Insights">
  * Success: more than 50% average view percentage
  * Critical: less than 30% average view percentage (review structure/pacing)
</Accordion>

<Accordion title="Thumbnail Insights">
  * Success: more than 8% CTR
  * Warning: less than 3% CTR (recommend A/B testing)
</Accordion>

<Accordion title="SEO Insights">
  * Success: more than 80 SEO score
  * Warning: less than 50 SEO score (optimize title/description/tags)
</Accordion>

<Accordion title="Engagement Insights">
  * Success: more than 5% engagement rate
  * Warning: less than 1% engagement rate (encourage interaction)
</Accordion>

## Usage Example

```javascript theme={null}
const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');

const agent = new AnalyticsOptimizationAgent(db, credentials);
await agent.initialize();

// Analyze a specific video
const report = await agent.analyzeVideoPerformance('dQw4w9WgXcQ');

console.log('Performance Grade:', report.performance.grade);
console.log('Performance Score:', report.performance.score, '/100');

// Check insights
report.insights.forEach(insight => {
  console.log(`[${insight.type.toUpperCase()}] ${insight.category}:`);
  console.log(`  ${insight.message}`);
  if (insight.recommendation) {
    console.log(`  → ${insight.recommendation}`);
  }
});

// Get analytics summary
const recent = await agent.getRecentAnalytics(7);
console.log('Last 7 days:');
console.log('  Videos:', recent.totalVideos);
console.log('  Avg Score:', recent.averagePerformanceScore);

// Track specific metrics
console.log('\nKey Metrics:');
console.log('  Views:', report.analytics.views.totalViews);
console.log('  CTR:', report.analytics.views.averageCTR + '%');
console.log('  Avg View %:', report.analytics.watchTime.averageViewPercentage + '%');
console.log('  Engagement:', report.analytics.engagement.engagementRate + '%');
console.log('  Search Traffic:', report.seoMetrics.searchPerformance.searchPercentage + '%');
```

## Analytics Metrics

<Accordion title="Views Metrics">
  * Total views
  * Total impressions
  * Average CTR (Click-Through Rate)
  * Daily view data
</Accordion>

<Accordion title="Watch Time Metrics">
  * Total minutes watched
  * Average view duration
  * Average view percentage (retention)
  * Retention quality assessment
</Accordion>

<Accordion title="Engagement Metrics">
  * Engagement rate: (likes + comments) / views
  * Like ratio: likes / (likes + dislikes)
  * Comments per view
  * Engagement quality assessment
</Accordion>

<Accordion title="Demographics">
  * Age group distribution
  * Gender distribution
  * Primary audience identification
</Accordion>

<Accordion title="Traffic Sources">
  * Source breakdown (search, suggested, external, etc.)
  * Top traffic source
  * Organic percentage (search + suggested)
</Accordion>

<Accordion title="Devices">
  * Device type distribution (mobile, desktop, tablet, TV)
  * Mobile percentage
</Accordion>

## Best Practices

<Accordion title="Analyze Regularly">
  Run analysis 3-7 days after publishing to get meaningful data. Re-analyze at 30 days for long-term performance.
</Accordion>

<Accordion title="Act on Critical Insights">
  Prioritize 'critical' insights with 'high' impact. These indicate significant issues affecting video performance.
</Accordion>

<Accordion title="Track Performance Over Time">
  Use getRecentAnalytics() weekly to identify trends and patterns in your content performance.
</Accordion>

<Accordion title="Focus on Retention">
  Retention (average view percentage) is one of the most important metrics. Target >50% for good performance.
</Accordion>

<Accordion title="Optimize Based on Data">
  Use SEO scores and thumbnail CTR to guide optimization efforts. Apply learnings to future videos.
</Accordion>

## YouTube Analytics API Requirements

<Accordion title="OAuth 2.0 Credentials">
  Requires OAuth 2.0 with scope: [https://www.googleapis.com/auth/youtube.readonly](https://www.googleapis.com/auth/youtube.readonly) and [https://www.googleapis.com/auth/yt-analytics.readonly](https://www.googleapis.com/auth/yt-analytics.readonly)
</Accordion>

<Accordion title="Data Delay">
  YouTube Analytics data has a 24-48 hour delay. Recent videos may show incomplete data.
</Accordion>

<Accordion title="Historical Data">
  The agent queries last 30 days by default. Adjust date ranges in method calls for different periods.
</Accordion>
