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.
Overview
The Analytics & Optimization Agent is your AI-powered performance analyst that continuously monitors your video metrics, identifies optimization opportunities, and provides actionable insights to improve your channel’s performance. It transforms raw analytics data into strategic recommendations.
What It Does The Analytics Agent tracks comprehensive video metrics including views, retention, engagement, CTR, and traffic sources. It generates performance reports with insights and specific recommendations for improvement.
Key Features
Performance Analysis Comprehensive video performance scoring (0-100)
Retention Tracking Monitors audience retention and drop-off points
SEO Performance Analyzes title, description, and tag effectiveness
Smart Insights AI-generated recommendations for improvement
Core Methods
Comprehensive video performance analysis:
analytics-optimization-agent.js
async analyzeVideoPerformance ( videoId ) {
this . logger . info ( `Analyzing performance for video: ${ videoId } ` );
// Get video details
const videoDetails = await this . getVideoDetails ( videoId );
// Get analytics data
const analytics = await this . getVideoAnalytics ( videoId );
// Analyze thumbnail performance
const thumbnailMetrics = await this . analyzeThumbnailPerformance ( videoId );
// Analyze title and SEO performance
const seoMetrics = await this . analyzeSEOPerformance ( videoDetails , analytics );
// Generate insights and recommendations
const insights = await this . generateInsights (
videoDetails , analytics , thumbnailMetrics , seoMetrics
);
const performanceReport = {
videoId ,
videoDetails ,
analytics ,
thumbnailMetrics ,
seoMetrics ,
insights ,
performance: this . calculatePerformanceScore ( analytics ),
analyzedAt: new Date (). toISOString ()
};
// Store in performance data
this . performanceData . set ( videoId , performanceReport );
// Save to database
await this . db . saveAnalyticsReport ( performanceReport );
this . logger . info ( `Analysis complete. Performance score: ${ performanceReport . performance . score } /100` );
return performanceReport ;
}
Analytics Data Collection
The agent collects comprehensive metrics from YouTube Analytics API:
getVideoAnalytics()
analytics-optimization-agent.js
async getVideoAnalytics ( videoId ) {
const endDate = new Date (). toISOString (). split ( 'T' )[ 0 ];
const startDate = new Date ( Date . now () - 30 * 24 * 60 * 60 * 1000 )
. toISOString (). split ( 'T' )[ 0 ];
try {
// Get various analytics metrics
const [
viewsData ,
watchTimeData ,
demographicsData ,
trafficSourcesData ,
deviceData
] = await Promise . all ([
this . getViewsAnalytics ( videoId , startDate , endDate ),
this . getWatchTimeAnalytics ( videoId , startDate , endDate ),
this . getDemographicsAnalytics ( videoId , startDate , endDate ),
this . getTrafficSourcesAnalytics ( videoId , startDate , endDate ),
this . getDeviceAnalytics ( videoId , startDate , endDate )
]);
return {
period: { startDate , endDate },
views: viewsData ,
watchTime: watchTimeData ,
demographics: demographicsData ,
trafficSources: trafficSourcesData ,
devices: deviceData ,
engagement: await this . calculateEngagementMetrics ( videoId )
};
} catch ( error ) {
this . logger . error ( `Failed to get analytics for ${ videoId } :` , error );
return this . getSimulatedAnalytics ( videoId );
}
}
Key Metrics
Views & Impressions
Watch Time & Retention
Engagement
Traffic Sources
Tracks views, impressions, and click-through rate: analytics-optimization-agent.js
async getViewsAnalytics ( videoId , startDate , endDate ) {
const response = await this . youtubeAnalytics . reports . query ({
ids: 'channel==MINE' ,
startDate ,
endDate ,
metrics: 'views,impressions,impressionClickThroughRate' ,
dimensions: 'day' ,
filters: `video== ${ videoId } `
});
return {
totalViews: response . data . rows ?. reduce (( sum , row ) => sum + row [ 1 ], 0 ) || 0 ,
totalImpressions: response . data . rows ?. reduce (( sum , row ) => sum + row [ 2 ], 0 ) || 0 ,
averageCTR: this . calculateAverage ( response . data . rows ?. map ( row => row [ 3 ]) || []),
dailyData: response . data . rows || []
};
}
Key Insights :
CTR > 8%: Excellent thumbnail/title
CTR 5-8%: Good performance
CTR < 3%: Needs optimization
Monitors audience retention metrics: analytics-optimization-agent.js
async getWatchTimeAnalytics ( videoId , startDate , endDate ) {
const response = await this . youtubeAnalytics . reports . query ({
ids: 'channel==MINE' ,
startDate ,
endDate ,
metrics: 'estimatedMinutesWatched,averageViewDuration,averageViewPercentage' ,
filters: `video== ${ videoId } `
});
const data = response . data . rows ?.[ 0 ] || [ 0 , 0 , 0 ];
return {
totalWatchTime: data [ 0 ] || 0 ,
averageViewDuration: data [ 1 ] || 0 ,
averageViewPercentage: data [ 2 ] || 0 ,
retentionQuality: this . assessRetentionQuality ( data [ 2 ])
};
}
Quality Assessment :
60%: Excellent retention
40-60%: Good retention
25-40%: Average retention
< 25%: Poor retention
Calculates engagement rate from likes and comments: analytics-optimization-agent.js
async calculateEngagementMetrics ( videoId ) {
const videoDetails = await this . getVideoDetails ( videoId );
const stats = videoDetails . statistics ;
const engagementRate = (
( stats . likeCount + stats . commentCount ) / stats . viewCount * 100
). toFixed ( 2 );
const likeRatio = (
stats . likeCount / ( stats . likeCount + ( stats . dislikeCount || 0 )) * 100
). toFixed ( 2 );
return {
engagementRate: parseFloat ( engagementRate ),
likeRatio: parseFloat ( likeRatio ),
commentsPerView: ( stats . commentCount / stats . viewCount * 100 ). toFixed ( 4 ),
engagementQuality: this . assessEngagementQuality ( parseFloat ( engagementRate ))
};
}
Quality Levels :
8%: Excellent engagement
5-8%: Good engagement
2-5%: Average engagement
< 2%: Poor engagement
Analyzes where views are coming from: analytics-optimization-agent.js
async getTrafficSourcesAnalytics ( videoId , startDate , endDate ) {
const response = await this . youtubeAnalytics . reports . query ({
ids: 'channel==MINE' ,
startDate ,
endDate ,
metrics: 'views' ,
dimensions: 'insightTrafficSourceType' ,
filters: `video== ${ videoId } `
});
const sources = response . data . rows || [];
const totalViews = sources . reduce (( sum , row ) => sum + row [ 1 ], 0 );
return {
sources: sources . map ( row => ({
source: row [ 0 ],
views: row [ 1 ],
percentage: (( row [ 1 ] / totalViews ) * 100 ). toFixed ( 1 )
})),
topSource: sources . length > 0 ? sources [ 0 ][ 0 ] : 'unknown' ,
organicPercentage: this . calculateOrganicPercentage ( sources )
};
}
Traffic Types :
SEARCH: YouTube/Google search
SUGGESTED_VIDEO: Recommended videos
EXTERNAL: External websites
BROWSE: Homepage/subscriptions
The agent calculates a comprehensive performance score:
analytics-optimization-agent.js
calculatePerformanceScore ( analytics ) {
let score = 0 ;
let maxScore = 0 ;
// Views score (30 points max)
const viewsScore = Math . min ( 30 , ( analytics . views . totalViews / 10000 ) * 30 );
score += viewsScore ;
maxScore += 30 ;
// Retention score (25 points max)
const retentionScore = ( analytics . watchTime . averageViewPercentage / 100 ) * 25 ;
score += retentionScore ;
maxScore += 25 ;
// Engagement score (25 points max)
const engagementScore = Math . min ( 25 , analytics . engagement . engagementRate * 5 );
score += engagementScore ;
maxScore += 25 ;
// CTR score (20 points max)
const ctrScore = Math . min ( 20 , analytics . views . averageCTR * 2 );
score += ctrScore ;
maxScore += 20 ;
const finalScore = Math . round (( score / maxScore ) * 100 );
return {
score: finalScore ,
breakdown: {
views: Math . round ( viewsScore ),
retention: Math . round ( retentionScore ),
engagement: Math . round ( engagementScore ),
ctr: Math . round ( ctrScore )
},
grade: this . getPerformanceGrade ( finalScore )
};
}
A+ (90-100) Exceptional performance across all metrics
A (80-89) Strong performance with minor optimization opportunities
B (70-79) Good performance with some areas for improvement
C (60-69) Average performance, needs optimization
D (50-59) Below average, requires attention
F (0-49) Poor performance, immediate action needed
Insight Generation
The agent generates AI-powered insights and recommendations:
generateInsights()
analytics-optimization-agent.js
async generateInsights ( videoDetails , analytics , thumbnailMetrics , seoMetrics ) {
const insights = [];
// Performance insights
if ( analytics . views . totalViews > 10000 ) {
insights . push ({
type: 'success' ,
category: 'views' ,
message: 'Video is performing above average in terms of views' ,
impact: 'high'
});
} else if ( analytics . views . totalViews < 1000 ) {
insights . push ({
type: 'warning' ,
category: 'views' ,
message: 'Video views are below expected threshold' ,
impact: 'high' ,
recommendation: 'Consider promoting the video or optimizing SEO'
});
}
// Retention insights
if ( analytics . watchTime . averageViewPercentage > 50 ) {
insights . push ({
type: 'success' ,
category: 'retention' ,
message: 'Excellent audience retention rate' ,
impact: 'medium'
});
} else if ( analytics . watchTime . averageViewPercentage < 30 ) {
insights . push ({
type: 'critical' ,
category: 'retention' ,
message: 'Poor audience retention - viewers are dropping off early' ,
impact: 'high' ,
recommendation: 'Review content structure and pacing'
});
}
// Thumbnail insights
if ( thumbnailMetrics . clickThroughRate > 8 ) {
insights . push ({
type: 'success' ,
category: 'thumbnail' ,
message: 'Thumbnail is highly effective at driving clicks' ,
impact: 'high'
});
} else if ( thumbnailMetrics . clickThroughRate < 3 ) {
insights . push ({
type: 'warning' ,
category: 'thumbnail' ,
message: 'Thumbnail may not be compelling enough' ,
impact: 'high' ,
recommendation: 'Consider A/B testing different thumbnail designs'
});
}
// SEO insights
if ( seoMetrics . overallSEOScore > 80 ) {
insights . push ({
type: 'success' ,
category: 'seo' ,
message: 'Video is well-optimized for search' ,
impact: 'medium'
});
} else if ( seoMetrics . overallSEOScore < 50 ) {
insights . push ({
type: 'warning' ,
category: 'seo' ,
message: 'SEO optimization needs improvement' ,
impact: 'medium' ,
recommendation: 'Optimize title, description, and tags'
});
}
return insights ;
}
Analyzes title, description, and tag effectiveness:
analytics-optimization-agent.js
async analyzeSEOPerformance ( videoDetails , analytics ) {
const title = videoDetails . title ;
const description = videoDetails . description ;
const tags = videoDetails . tags ;
// Analyze title effectiveness
const titleScore = this . scoreTitleEffectiveness ( title , analytics . views . totalViews );
// Analyze description optimization
const descriptionScore = this . scoreDescriptionOptimization ( description );
// Analyze tag relevance
const tagScore = this . scoreTagRelevance ( tags , title );
// Search performance
const searchPerformance = this . analyzeSearchPerformance ( analytics . trafficSources );
return {
titleScore ,
descriptionScore ,
tagScore ,
searchPerformance ,
overallSEOScore: Math . round (( titleScore + descriptionScore + tagScore ) / 3 ),
recommendations: this . generateSEORecommendations (
titleScore , descriptionScore , tagScore , searchPerformance
)
};
}
analytics-optimization-agent.js
async analyzeThumbnailPerformance ( videoId ) {
try {
const response = await this . youtubeAnalytics . reports . query ({
ids: 'channel==MINE' ,
startDate: new Date ( Date . now () - 7 * 24 * 60 * 60 * 1000 ). toISOString (). split ( 'T' )[ 0 ],
endDate: new Date (). toISOString (). split ( 'T' )[ 0 ],
metrics: 'impressions,impressionClickThroughRate' ,
filters: `video== ${ videoId } `
});
const data = response . data . rows ?.[ 0 ] || [ 0 , 0 ];
const ctr = data [ 1 ] || 0 ;
return {
impressions: data [ 0 ] || 0 ,
clickThroughRate: ctr ,
ctrQuality: this . assessCTRQuality ( ctr ),
recommendations: this . generateThumbnailRecommendations ( ctr )
};
} catch ( error ) {
return {
impressions: 0 ,
clickThroughRate: 0 ,
ctrQuality: 'unknown' ,
recommendations: [ 'Unable to analyze thumbnail performance' ]
};
}
}
Channel-Wide Analytics
Monitor overall channel performance:
getRecentAnalytics()
analytics-optimization-agent.js
async getRecentAnalytics ( days = 7 ) {
const recentReports = Array . from ( this . performanceData . values ())
. filter ( report => {
const reportDate = new Date ( report . analyzedAt );
const cutoffDate = new Date ( Date . now () - days * 24 * 60 * 60 * 1000 );
return reportDate > cutoffDate ;
})
. sort (( a , b ) => new Date ( b . analyzedAt ) - new Date ( a . analyzedAt ));
return {
totalVideos: recentReports . length ,
averagePerformanceScore: this . calculateAverageScore ( recentReports ),
topPerformers: recentReports . slice ( 0 , 5 ),
insights: this . generateChannelInsights ( recentReports )
};
}
Example Analytics Report
{
"videoId" : "dQw4w9WgXcQ" ,
"videoDetails" : {
"title" : "Ultimate Guide to AI Technology Trends (2026)" ,
"publishedAt" : "2026-03-07T14:00:00Z" ,
"statistics" : {
"viewCount" : 45230 ,
"likeCount" : 2891 ,
"commentCount" : 342
}
},
"analytics" : {
"views" : {
"totalViews" : 45230 ,
"totalImpressions" : 125000 ,
"averageCTR" : 7.2
},
"watchTime" : {
"totalWatchTime" : 18500 ,
"averageViewDuration" : 415 ,
"averageViewPercentage" : 62.3 ,
"retentionQuality" : "excellent"
},
"engagement" : {
"engagementRate" : 7.15 ,
"likeRatio" : 98.5 ,
"engagementQuality" : "good"
}
},
"thumbnailMetrics" : {
"clickThroughRate" : 7.2 ,
"ctrQuality" : "good" ,
"recommendations" : [
"Good thumbnail performance" ,
"Minor optimizations may help"
]
},
"seoMetrics" : {
"titleScore" : 85 ,
"descriptionScore" : 78 ,
"tagScore" : 72 ,
"overallSEOScore" : 78
},
"performance" : {
"score" : 84 ,
"grade" : "A" ,
"breakdown" : {
"views" : 25 ,
"retention" : 23 ,
"engagement" : 22 ,
"ctr" : 14
}
},
"insights" : [
{
"type" : "success" ,
"category" : "views" ,
"message" : "Video is performing above average" ,
"impact" : "high"
},
{
"type" : "success" ,
"category" : "retention" ,
"message" : "Excellent audience retention rate" ,
"impact" : "medium"
}
]
}
Best Practices
Check analytics within 24 hours of publishing and again after 7 days for trend analysis
Implement recommendations promptly, especially for critical issues
Look for patterns across multiple videos to identify systematic issues or strengths
Use insights to inform A/B tests on thumbnails, titles, and content structure
Analysis Time 10-30 seconds
Insight Count 5-15 per video
Next Steps
Content Strategy Use insights to inform future content strategy
SEO Optimizer Apply SEO recommendations to improve rankings
Dashboard View real-time analytics in the dashboard
API Reference View complete API documentation