Skip to main content

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

db
Database
required
Database instance for analytics history
credentials
Credentials
required
Credentials manager with YouTube Analytics API access
const { AnalyticsOptimizationAgent } = require('./agents/analytics-optimization-agent');

const agent = new AnalyticsOptimizationAgent(db, credentials);

Properties

youtubeAnalytics
YouTubeAnalyticsAPI
YouTube Analytics API v2 client
youtube
YouTubeAPI
YouTube Data API v3 client
performanceData
Map
Historical performance data cache
logger
Logger
Logger instance for tracking analytics

Methods

initialize()

Initializes the agent and loads historical analytics data.
return
Promise<boolean>
Returns true when initialization is complete
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.
videoId
string
required
YouTube video ID
return
Promise<Object>
Complete performance report
report.videoId
string
YouTube video ID
report.videoDetails
Object
Video metadata (title, description, tags, statistics)
report.analytics
Object
Analytics data (views, watch time, demographics, traffic, devices, engagement)
report.thumbnailMetrics
Object
Thumbnail performance (impressions, CTR, quality, recommendations)
report.seoMetrics
Object
SEO performance (title score, description score, tag score, search performance)
report.insights
Array<Object>
Actionable insights with recommendations
report.performance
Object
Overall performance score with breakdown and grade
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.
videoId
string
required
YouTube video ID
return
Promise<Object>
Video details object
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).
videoId
string
required
YouTube video ID
return
Promise<Object>
Analytics data object
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).
analytics
Object
required
Analytics data from getVideoAnalytics
return
Object
Performance score with breakdown and grade
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.
videoId
string
required
YouTube video ID
return
Promise<Object>
Thumbnail metrics with recommendations
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.
videoDetails
Object
required
Video details from getVideoDetails
analytics
Object
required
Analytics data from getVideoAnalytics
return
Promise<Object>
SEO metrics with scores and recommendations
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.
videoDetails
Object
required
Video details
analytics
Object
required
Analytics data
thumbnailMetrics
Object
required
Thumbnail metrics
seoMetrics
Object
required
SEO metrics
return
Promise<Array<Object>>
Array of insight objects
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.
days
number
default:"7"
Number of days to look back
return
Promise<Object>
Summary analytics for recent videos
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:
// 30 points max
// Based on view count relative to 10,000 baseline
viewsScore = Math.min(30, (totalViews / 10000) * 30)

Insight Types and Triggers

  • Success: more than 10,000 views
  • Warning: less than 1,000 views (recommend promotion/SEO optimization)
  • Success: more than 50% average view percentage
  • Critical: less than 30% average view percentage (review structure/pacing)
  • Success: more than 8% CTR
  • Warning: less than 3% CTR (recommend A/B testing)
  • Success: more than 80 SEO score
  • Warning: less than 50 SEO score (optimize title/description/tags)
  • Success: more than 5% engagement rate
  • Warning: less than 1% engagement rate (encourage interaction)

Usage Example

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

  • Total views
  • Total impressions
  • Average CTR (Click-Through Rate)
  • Daily view data
  • Total minutes watched
  • Average view duration
  • Average view percentage (retention)
  • Retention quality assessment
  • Engagement rate: (likes + comments) / views
  • Like ratio: likes / (likes + dislikes)
  • Comments per view
  • Engagement quality assessment
  • Age group distribution
  • Gender distribution
  • Primary audience identification
  • Source breakdown (search, suggested, external, etc.)
  • Top traffic source
  • Organic percentage (search + suggested)
  • Device type distribution (mobile, desktop, tablet, TV)
  • Mobile percentage

Best Practices

Run analysis 3-7 days after publishing to get meaningful data. Re-analyze at 30 days for long-term performance.
Prioritize ‘critical’ insights with ‘high’ impact. These indicate significant issues affecting video performance.
Use getRecentAnalytics() weekly to identify trends and patterns in your content performance.
Retention (average view percentage) is one of the most important metrics. Target >50% for good performance.
Use SEO scores and thumbnail CTR to guide optimization efforts. Apply learnings to future videos.

YouTube Analytics API Requirements

YouTube Analytics data has a 24-48 hour delay. Recent videos may show incomplete data.
The agent queries last 30 days by default. Adjust date ranges in method calls for different periods.