> ## 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.

# ContentStrategyAgent

> AI-powered content strategy and trend analysis agent

## 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

<ParamField path="db" type="Database" required>
  Database instance for storing and retrieving content data
</ParamField>

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

```javascript theme={null}
const { ContentStrategyAgent } = require('./agents/content-strategy-agent');

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

## Properties

<ResponseField name="db" type="Database">
  Database connection instance
</ResponseField>

<ResponseField name="credentials" type="Credentials">
  YouTube API credentials manager
</ResponseField>

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

<ResponseField name="trendingTopics" type="Array">
  Array of currently trending topics with scores and sources
</ResponseField>

<ResponseField name="competitorData" type="Array">
  Analysis data from competitor channels
</ResponseField>

<ResponseField name="contentCalendar" type="Array">
  Scheduled content calendar entries
</ResponseField>

## Methods

### initialize()

Initializes the agent, loads historical data, and analyzes current trends.

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

```javascript theme={null}
await agent.initialize();
// Agent is ready to generate content strategies
```

### generateContentStrategy(requestedTopic)

Generates a comprehensive content strategy for a topic.

<ParamField path="requestedTopic" type="string" optional>
  Specific topic to create strategy for. If not provided, selects optimal trending topic.
</ParamField>

<ParamField path="return" type="Promise<Object>">
  Complete content strategy object
</ParamField>

<ResponseField name="strategy.topic" type="string">
  Selected content topic
</ResponseField>

<ResponseField name="strategy.angle" type="string">
  Unique content angle generated for the topic
</ResponseField>

<ResponseField name="strategy.targetAudience" type="string">
  Identified target audience demographic
</ResponseField>

<ResponseField name="strategy.contentType" type="string">
  Content type (Tutorial, Explainer, List, Review, Story)
</ResponseField>

<ResponseField name="strategy.keywords" type="Array<string>">
  Extracted keywords for SEO optimization
</ResponseField>

<ResponseField name="strategy.estimatedViews" type="number">
  Predicted view count based on topic score
</ResponseField>

<ResponseField name="strategy.bestPublishTime" type="string">
  ISO timestamp for optimal publishing time
</ResponseField>

<ResponseField name="strategy.competitorAnalysis" type="Array">
  Insights from competitor analysis
</ResponseField>

```javascript theme={null}
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.

<ParamField path="return" type="Promise<Array>">
  Array of trending video data
</ParamField>

```javascript theme={null}
const trends = await agent.fetchYouTubeTrends();
// Uses YouTube API videos.list with chart: 'mostPopular'
```

### analyzeCompetitors()

Analyzes competitor channels specified in environment variables.

<ParamField path="return" type="Promise<Array>">
  Competitor analysis data including top topics and performance metrics
</ParamField>

```javascript theme={null}
const competitors = await agent.analyzeCompetitors();
// Reads from process.env.COMPETITOR_CHANNELS
```

### getChannelVideos(channelId)

Retrieves recent videos from a specific channel.

<ParamField path="channelId" type="string" required>
  YouTube channel ID to analyze
</ParamField>

<ParamField path="return" type="Promise<Array>">
  Array of video details with statistics
</ParamField>

```javascript theme={null}
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.

<ParamField path="videos" type="Array" required>
  Array of video objects with statistics
</ParamField>

<ParamField path="return" type="Object">
  Performance analysis including top topics, average views, and upload frequency
</ParamField>

<ResponseField name="topTopics" type="Array">
  Top 10 performing topics with average views
</ResponseField>

<ResponseField name="avgViews" type="number">
  Average view count across all videos
</ResponseField>

<ResponseField name="frequency" type="number">
  Number of videos analyzed
</ResponseField>

```javascript theme={null}
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.

<ParamField path="text" type="string" required>
  Text to extract keywords from
</ParamField>

<ParamField path="return" type="Array<string>">
  Array of extracted keywords (words > 3 characters, excluding stop words)
</ParamField>

```javascript theme={null}
const keywords = agent.extractKeywords('The Ultimate Guide to AI Technology');
// ['ultimate', 'guide', 'technology']
```

### selectOptimalTopic()

Selects the best topic from trending topics using scoring algorithm.

<ParamField path="return" type="Object">
  Selected topic with score
</ParamField>

```javascript theme={null}
const optimal = agent.selectOptimalTopic();
// Filters out recently used topics and applies seasonal/audience multipliers
```

### identifyTargetAudience(topic)

Identifies the target audience for a given topic.

<ParamField path="topic" type="string" required>
  Content topic
</ParamField>

<ParamField path="return" type="Promise<string>">
  Target audience description
</ParamField>

```javascript theme={null}
const audience = await agent.identifyTargetAudience('Python Programming');
// 'Tech enthusiasts, developers, early adopters'
```

### selectContentType(topic)

Determines the optimal content type based on topic keywords.

<ParamField path="topic" type="string" required>
  Content topic
</ParamField>

<ParamField path="return" type="string">
  Content type: Tutorial, List, Review, Explainer, News, or Story
</ParamField>

```javascript theme={null}
const type = agent.selectContentType('How to Master JavaScript');
// 'Tutorial'
```

### calculateBestPublishTime()

Calculates the optimal publishing time based on historical performance.

<ParamField path="return" type="string">
  ISO timestamp for next optimal publish time
</ParamField>

```javascript theme={null}
const publishTime = agent.calculateBestPublishTime();
// Selects optimal day/hour combination (e.g., Tuesday at 2 PM)
```

## Environment Variables

<ParamField path="YOUTUBE_REGION" type="string" default="US">
  YouTube region code for trending videos
</ParamField>

<ParamField path="COMPETITOR_CHANNELS" type="string">
  Comma-separated list of competitor channel IDs to analyze
</ParamField>

## Usage Example

```javascript theme={null}
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:

```javascript theme={null}
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

<Accordion title="Optimize Trend Analysis">
  Call `initialize()` periodically (e.g., daily) to refresh trending topics and competitor analysis. The agent caches data to minimize API calls.
</Accordion>

<Accordion title="Configure Competitors">
  Set `COMPETITOR_CHANNELS` environment variable with relevant channel IDs in your niche for better strategy recommendations.
</Accordion>

<Accordion title="Monitor Historical Performance">
  The agent learns from historical content performance. Ensure you're saving analytics data back to the database for improved predictions.
</Accordion>

<Accordion title="Topic Rotation">
  The agent automatically avoids repeating topics within 7 days. This prevents content fatigue and maintains audience interest.
</Accordion>
