Skip to main content

Overview

The ContentStrategyAgent analyzes YouTube trends, competitor channels, and historical performance to generate optimized content strategies. It identifies trending topics, selects optimal publishing times, and creates data-driven content recommendations.

Constructor

db
Database
required
Database instance for storing and retrieving content data
credentials
Credentials
required
Credentials manager with YouTube API access
const { ContentStrategyAgent } = require('./agents/content-strategy-agent');

const agent = new ContentStrategyAgent(db, credentials);

Properties

db
Database
Database connection instance
credentials
Credentials
YouTube API credentials manager
logger
Logger
Logger instance for tracking agent operations
Array of currently trending topics with scores and sources
competitorData
Array
Analysis data from competitor channels
contentCalendar
Array
Scheduled content calendar entries

Methods

initialize()

Initializes the agent, loads historical data, and analyzes current trends.
return
Promise<boolean>
Returns true when initialization is complete
await agent.initialize();
// Agent is ready to generate content strategies

generateContentStrategy(requestedTopic)

Generates a comprehensive content strategy for a topic.
requestedTopic
string
Specific topic to create strategy for. If not provided, selects optimal trending topic.
return
Promise<Object>
Complete content strategy object
strategy.topic
string
Selected content topic
strategy.angle
string
Unique content angle generated for the topic
strategy.targetAudience
string
Identified target audience demographic
strategy.contentType
string
Content type (Tutorial, Explainer, List, Review, Story)
strategy.keywords
Array<string>
Extracted keywords for SEO optimization
strategy.estimatedViews
number
Predicted view count based on topic score
strategy.bestPublishTime
string
ISO timestamp for optimal publishing time
strategy.competitorAnalysis
Array
Insights from competitor analysis
const strategy = await agent.generateContentStrategy('AI Technology');

console.log(strategy);
// {
//   topic: 'AI Technology',
//   angle: 'The Ultimate Guide to AI Technology',
//   targetAudience: 'Tech enthusiasts, developers, early adopters',
//   contentType: 'Explainer',
//   keywords: ['technology', 'artificial', 'intelligence', ...],
//   estimatedViews: 15000,
//   bestPublishTime: '2026-03-10T14:00:00.000Z',
//   competitorAnalysis: [...],
//   createdAt: '2026-03-05T10:00:00.000Z'
// }

fetchYouTubeTrends()

Fetches trending videos from YouTube API.
return
Promise<Array>
Array of trending video data
const trends = await agent.fetchYouTubeTrends();
// Uses YouTube API videos.list with chart: 'mostPopular'

analyzeCompetitors()

Analyzes competitor channels specified in environment variables.
return
Promise<Array>
Competitor analysis data including top topics and performance metrics
const competitors = await agent.analyzeCompetitors();
// Reads from process.env.COMPETITOR_CHANNELS

getChannelVideos(channelId)

Retrieves recent videos from a specific channel.
channelId
string
required
YouTube channel ID to analyze
return
Promise<Array>
Array of video details with statistics
const videos = await agent.getChannelVideos('UCxxxxxxxx');
// Returns up to 20 most recent videos with full statistics

analyzeVideoPerformance(videos)

Analyzes performance metrics for a collection of videos.
videos
Array
required
Array of video objects with statistics
return
Object
Performance analysis including top topics, average views, and upload frequency
topTopics
Array
Top 10 performing topics with average views
avgViews
number
Average view count across all videos
frequency
number
Number of videos analyzed
const analysis = agent.analyzeVideoPerformance(videos);
// {
//   topTopics: [{ topic: 'tutorial', avgViews: 50000 }, ...],
//   avgViews: 25000,
//   frequency: 20
// }

extractKeywords(text)

Extracts meaningful keywords from text by filtering stop words.
text
string
required
Text to extract keywords from
return
Array<string>
Array of extracted keywords (words > 3 characters, excluding stop words)
const keywords = agent.extractKeywords('The Ultimate Guide to AI Technology');
// ['ultimate', 'guide', 'technology']

selectOptimalTopic()

Selects the best topic from trending topics using scoring algorithm.
return
Object
Selected topic with score
const optimal = agent.selectOptimalTopic();
// Filters out recently used topics and applies seasonal/audience multipliers

identifyTargetAudience(topic)

Identifies the target audience for a given topic.
topic
string
required
Content topic
return
Promise<string>
Target audience description
const audience = await agent.identifyTargetAudience('Python Programming');
// 'Tech enthusiasts, developers, early adopters'

selectContentType(topic)

Determines the optimal content type based on topic keywords.
topic
string
required
Content topic
return
string
Content type: Tutorial, List, Review, Explainer, News, or Story
const type = agent.selectContentType('How to Master JavaScript');
// 'Tutorial'

calculateBestPublishTime()

Calculates the optimal publishing time based on historical performance.
return
string
ISO timestamp for next optimal publish time
const publishTime = agent.calculateBestPublishTime();
// Selects optimal day/hour combination (e.g., Tuesday at 2 PM)

Environment Variables

YOUTUBE_REGION
string
default:"US"
YouTube region code for trending videos
COMPETITOR_CHANNELS
string
Comma-separated list of competitor channel IDs to analyze

Usage Example

const { ContentStrategyAgent } = require('./agents/content-strategy-agent');
const { Database } = require('./utils/database');
const { Credentials } = require('./utils/credentials');

const db = new Database();
const credentials = new Credentials();
const agent = new ContentStrategyAgent(db, credentials);

// Initialize the agent
await agent.initialize();

// Generate strategy for a specific topic
const strategy = await agent.generateContentStrategy('Cloud Computing');

// Or let the agent select optimal topic
const autoStrategy = await agent.generateContentStrategy();

console.log(`Topic: ${strategy.topic}`);
console.log(`Angle: ${strategy.angle}`);
console.log(`Content Type: ${strategy.contentType}`);
console.log(`Estimated Views: ${strategy.estimatedViews}`);
console.log(`Best Publish Time: ${strategy.bestPublishTime}`);

Error Handling

The agent implements comprehensive error handling:
try {
  const strategy = await agent.generateContentStrategy();
} catch (error) {
  // Handles:
  // - YouTube API errors
  // - Database connection errors
  // - Invalid competitor channel IDs
  // - Network timeouts
  console.error('Strategy generation failed:', error.message);
}

Best Practices

Call initialize() periodically (e.g., daily) to refresh trending topics and competitor analysis. The agent caches data to minimize API calls.
Set COMPETITOR_CHANNELS environment variable with relevant channel IDs in your niche for better strategy recommendations.
The agent learns from historical content performance. Ensure you’re saving analytics data back to the database for improved predictions.
The agent automatically avoids repeating topics within 7 days. This prevents content fatigue and maintains audience interest.