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

# Manual Operations

> Complete reference for manual control, overrides, and direct API operations

## Overview

While the YouTube Automation Agent is designed for hands-off operation, you have complete manual control over every aspect of content generation, publishing, and optimization. This guide covers all manual operations and API endpoints.

<Note>
  All API endpoints run on port `3456` by default. Override with `PORT` environment variable.
</Note>

## API Base URL

```bash theme={null}
http://localhost:3456
```

## Core API Endpoints

### Health Check

Verify system status and agent availability.

<CodeGroup>
  ```bash cURL theme={null}
  curl http://localhost:3456/health
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:3456/health');
  const health = await response.json();
  console.log(health);
  ```

  ```python Python theme={null}
  import requests

  response = requests.get('http://localhost:3456/health')
  health = response.json()
  print(health)
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "status": "healthy",
  "initialized": true,
  "agents": [
    "strategy",
    "scriptWriter",
    "thumbnailDesigner",
    "seoOptimizer",
    "production",
    "publishing",
    "analytics"
  ],
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

**Response Fields:**

| Field         | Type    | Description                         |
| ------------- | ------- | ----------------------------------- |
| `status`      | string  | `healthy` or `unhealthy`            |
| `initialized` | boolean | All agents initialized successfully |
| `agents`      | array   | List of active agent names          |
| `timestamp`   | string  | ISO 8601 timestamp of health check  |

### Manual Content Generation

Generate content immediately without waiting for scheduled automation.

<CodeGroup>
  ```bash Auto Topic theme={null}
  curl -X POST http://localhost:3456/generate \
    -H "Content-Type: application/json" \
    -d '{
      "topic": null,
      "style": "story",
      "length": "medium"
    }'
  ```

  ```bash Specific Topic theme={null}
  curl -X POST http://localhost:3456/generate \
    -H "Content-Type: application/json" \
    -d '{
      "topic": "The Evolution of Digital Art",
      "style": "story",
      "length": "long"
    }'
  ```

  ```bash Tutorial Style theme={null}
  curl -X POST http://localhost:3456/generate \
    -H "Content-Type: application/json" \
    -d '{
      "topic": "How to Create Compelling Narratives",
      "style": "tutorial",
      "length": "medium"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:3456/generate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      topic: null,
      style: 'story',
      length: 'medium'
    })
  });

  const result = await response.json();
  console.log(result);
  ```
</CodeGroup>

**Request Parameters:**

| Parameter | Type        | Required | Options                          | Description                   |
| --------- | ----------- | -------- | -------------------------------- | ----------------------------- |
| `topic`   | string/null | No       | Any string or `null`             | Specific topic or auto-select |
| `style`   | string      | No       | `story`, `tutorial`, `explainer` | Content presentation style    |
| `length`  | string      | No       | `short`, `medium`, `long`        | Target video length           |

**Response:**

```json theme={null}
{
  "success": true,
  "result": {
    "contentId": "abc123xyz",
    "title": "How Stories Shape Our Digital World",
    "scheduledFor": "2024-01-16T14:00:00.000Z"
  }
}
```

<Tip>
  Set `topic: null` to let the Content Strategy Agent automatically select the best topic based on trending content and channel performance.
</Tip>

### View Analytics

Retrieve performance analytics for recently published videos.

<CodeGroup>
  ```bash cURL theme={null}
  curl http://localhost:3456/analytics
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:3456/analytics');
  const analytics = await response.json();
  console.log(analytics);
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "totalVideos": 15,
  "averagePerformanceScore": 78.5,
  "topPerformers": [
    {
      "videoId": "dQw4w9WgXcQ",
      "title": "The Art of Digital Storytelling",
      "performanceScore": 92,
      "videoDetails": {
        "statistics": {
          "viewCount": "12500",
          "likeCount": "850",
          "commentCount": "143"
        },
        "tags": ["storytelling", "digital art", "creativity"]
      }
    }
  ],
  "recentAnalytics": [...]
}
```

**Analytics Metrics:**

* **Performance Score**: 0-100 composite score based on engagement, retention, and CTR
* **View Count**: Total views across all tracked videos
* **Engagement Rate**: (Likes + Comments) / Views
* **Top Performers**: Top 3 highest-scoring videos

### View Upcoming Schedule

Get list of scheduled content ready for publishing.

<CodeGroup>
  ```bash cURL theme={null}
  curl http://localhost:3456/schedule
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:3456/schedule');
  const schedule = await response.json();
  console.log(schedule);
  ```
</CodeGroup>

**Response:**

```json theme={null}
[
  {
    "id": "content_001",
    "title": "The Art of Digital Storytelling",
    "publishTime": "2024-01-16T14:00:00.000Z",
    "status": "scheduled",
    "contentType": "story",
    "estimatedDuration": "8:45"
  },
  {
    "id": "content_002",
    "title": "Understanding Visual Narratives",
    "publishTime": "2024-01-17T14:00:00.000Z",
    "status": "scheduled",
    "contentType": "story",
    "estimatedDuration": "10:30"
  }
]
```

### Manual Publishing

Publish content immediately, bypassing the scheduled time.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://localhost:3456/publish/abc123xyz
  ```

  ```javascript JavaScript theme={null}
  const contentId = 'abc123xyz';
  const response = await fetch(`http://localhost:3456/publish/${contentId}`, {
    method: 'POST'
  });

  const result = await response.json();
  console.log(result);
  ```
</CodeGroup>

**URL Parameters:**

| Parameter   | Type   | Description                             |
| ----------- | ------ | --------------------------------------- |
| `contentId` | string | The content ID from generation response |

**Response:**

```json theme={null}
{
  "success": true,
  "result": {
    "videoId": "dQw4w9WgXcQ",
    "status": "published",
    "url": "https://youtube.com/watch?v=dQw4w9WgXcQ",
    "publishedAt": "2024-01-15T10:45:00.000Z"
  }
}
```

<Note>
  Manual publishing requires valid YouTube OAuth tokens. If publishing fails, reauthorize with `npm run credentials:setup`.
</Note>

## Dashboard Access

Access the web-based dashboard for visual monitoring and control.

### Dashboard URL

```bash theme={null}
http://localhost:3456
```

### Dashboard Features

The dashboard provides:

<Steps>
  <Step title="System Overview">
    Real-time status of all 7 agents:

    * Content Strategy Agent
    * Script Writer Agent
    * Thumbnail Designer Agent
    * SEO Optimizer Agent
    * Production Management Agent
    * Publishing Scheduling Agent
    * Analytics Optimization Agent
  </Step>

  <Step title="Quick Actions">
    One-click buttons for:

    * **Generate Content Now**: Trigger immediate generation
    * **View Analytics**: Open analytics data in new tab
    * **View Schedule**: Open schedule data in new tab
  </Step>

  <Step title="Status Cards">
    Four at-a-glance metrics:

    * System Status (🟢/🔴)
    * Content Generated count
    * Videos Published count
    * Next Generation time
  </Step>

  <Step title="Live Monitoring">
    Six dashboard cards showing:

    * System Overview (uptime, agents active)
    * Upcoming Schedule (next 3 items)
    * Content Strategy (current focus)
    * Recent Activity (automation log)
    * Agent Status (all 7 agents)
    * Performance Metrics (scores and stats)
  </Step>
</Steps>

### Dashboard API Calls

The dashboard automatically refreshes every 30 seconds using these endpoints:

```javascript theme={null}
// Dashboard refresh cycle
setInterval(async () => {
  // 1. Load system health
  const health = await fetch('/health');
  
  // 2. Load schedule
  const schedule = await fetch('/schedule');
  
  // 3. Load analytics
  const analytics = await fetch('/analytics');
  
  // 4. Update UI
  updateDashboard(health, schedule, analytics);
}, 30000);
```

## Advanced Operations

### Querying the Database

Access the SQLite database directly for advanced queries.

```bash theme={null}
# Open database
sqlite3 ./data/youtube-automation.db
```

**Useful Queries:**

<CodeGroup>
  ```sql Recent Content theme={null}
  SELECT id, title, status, publish_time 
  FROM publish_schedule 
  ORDER BY created_at DESC 
  LIMIT 10;
  ```

  ```sql Performance Analysis theme={null}
  SELECT 
    ps.title,
    ar.performance_score,
    json_extract(ar.video_details, '$.statistics.viewCount') as views
  FROM analytics_reports ar
  JOIN publish_schedule ps ON ar.video_id = ps.id
  WHERE ar.performance_score > 70
  ORDER BY ar.performance_score DESC;
  ```

  ```sql Automation Events theme={null}
  SELECT 
    event_type,
    status,
    created_at,
    json_extract(data, '$.contentId') as content_id
  FROM automation_events
  WHERE status = 'success'
  ORDER BY created_at DESC
  LIMIT 20;
  ```

  ```sql Keyword Performance theme={null}
  SELECT 
    keyword,
    total_views,
    video_count,
    ROUND(CAST(total_views AS FLOAT) / video_count) as avg_views
  FROM keyword_performance
  ORDER BY total_views DESC
  LIMIT 15;
  ```
</CodeGroup>

### Manual Agent Invocation

Call individual agents programmatically for fine-grained control.

```javascript theme={null}
const { YouTubeAutomationAgent } = require('./index');

const agent = new YouTubeAutomationAgent();
await agent.initialize();

// 1. Generate content strategy only
const strategy = await agent.agents.strategy.generateContentStrategy(
  "The Future of AI in Creative Industries"
);

// 2. Write script from strategy
const script = await agent.agents.scriptWriter.generateScript(strategy);

// 3. Generate thumbnail
const thumbnail = await agent.agents.thumbnailDesigner.generateThumbnail(script);

// 4. Optimize SEO
const seoData = await agent.agents.seoOptimizer.optimize(script, strategy);

// 5. Process through production
const productionData = await agent.agents.production.processContent({
  strategy,
  script,
  thumbnail,
  seo: seoData
});

// 6. Schedule for publishing
await agent.agents.publishing.scheduleContent(productionData);
```

### Automation Control

Programmatically control the automation scheduler.

```javascript theme={null}
const { DailyAutomation } = require('./schedules/daily-automation');

// Access automation instance
const automation = agent.scheduler;

// Pause automation (keeps system running but stops scheduled tasks)
await automation.pauseAutomation();

// Resume automation
await automation.resumeAutomation();

// Stop all scheduled tasks
await automation.stopAutomation();

// Get automation status
const status = await automation.getAutomationStatus();
console.log(status);
// {
//   enabled: true,
//   scheduledTasks: [
//     { name: 'daily-content-generation', running: true },
//     { name: 'publish-queue-processing', running: true },
//     ...
//   ],
//   uptime: 86400
// }
```

## Batch Operations

### Generate Multiple Videos

Create content pipeline for multiple videos at once.

```bash theme={null}
# Generate 3 videos with different topics
for topic in "Digital Storytelling" "Visual Narratives" "Creative Expression"; do
  curl -X POST http://localhost:3456/generate \
    -H "Content-Type: application/json" \
    -d "{
      \"topic\": \"$topic\",
      \"style\": \"story\",
      \"length\": \"medium\"
    }"
  sleep 5
done
```

### Bulk Analytics Check

Retrieve analytics for specific video IDs.

```javascript theme={null}
const videoIds = ['abc123', 'def456', 'ghi789'];

for (const videoId of videoIds) {
  const analytics = await agent.agents.analytics.analyzeVideoPerformance(videoId);
  console.log(`${videoId}: Score ${analytics.performanceScore}`);
  
  // Delay to avoid rate limits
  await new Promise(resolve => setTimeout(resolve, 2000));
}
```

## Error Handling

### API Error Responses

All endpoints return consistent error format:

```json theme={null}
{
  "success": false,
  "error": "OpenAI API rate limit exceeded"
}
```

**Common HTTP Status Codes:**

| Code | Meaning             | Action                         |
| ---- | ------------------- | ------------------------------ |
| 200  | Success             | Request completed successfully |
| 400  | Bad Request         | Check request parameters       |
| 500  | Server Error        | Check logs, verify credentials |
| 503  | Service Unavailable | System not initialized         |

### Retry Logic

Implement exponential backoff for failed requests:

```javascript theme={null}
async function generateWithRetry(topic, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('http://localhost:3456/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ topic, style: 'story', length: 'medium' })
      });
      
      if (response.ok) {
        return await response.json();
      }
    } catch (error) {
      console.error(`Attempt ${i + 1} failed:`, error.message);
      
      if (i < maxRetries - 1) {
        // Exponential backoff: 2s, 4s, 8s
        await new Promise(resolve => setTimeout(resolve, 2000 * Math.pow(2, i)));
      }
    }
  }
  
  throw new Error('Generation failed after all retries');
}
```

## Monitoring and Logging

### Console Logs

The system provides detailed logging:

```bash theme={null}
[MainAgent] ✓ YouTube Automation Agent initialized successfully!
[ContentStrategy] Starting content generation pipeline...
[ContentStrategy] Strategy generated: The Art of Digital Storytelling
[ScriptWriter] Script generated: How Stories Shape Our Digital World
[ThumbnailDesigner] Thumbnail generated
[SEOOptimizer] SEO optimization complete
[ProductionManagement] Production processing complete
[Database] Content saved with ID: abc123xyz
```

### Log Levels

* **INFO**: Normal operations
* **SUCCESS**: Completed tasks
* **WARN**: Non-critical issues
* **ERROR**: Failures requiring attention

### Automation Events Log

Query the automation\_events table for historical data:

```sql theme={null}
SELECT 
  event_type,
  status,
  datetime(created_at) as timestamp,
  json_extract(data, '$.topic') as topic
FROM automation_events
WHERE date(created_at) = date('now')
ORDER BY created_at DESC;
```

## Integration Examples

### Webhook Integration

Receive notifications when content is published:

```javascript theme={null}
// Add to index.js after successful publish
const axios = require('axios');

app.post('/publish/:contentId', async (req, res) => {
  try {
    const result = await agents.publishing.publishContent(contentId);
    
    // Send webhook notification
    await axios.post('https://your-webhook-url.com/notify', {
      event: 'video_published',
      videoId: result.videoId,
      title: result.title,
      url: result.url
    });
    
    res.json({ success: true, result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});
```

### Slack Notifications

Post updates to Slack channel:

```javascript theme={null}
const { WebClient } = require('@slack/web-api');
const slack = new WebClient(process.env.SLACK_TOKEN);

async function notifySlack(message) {
  await slack.chat.postMessage({
    channel: '#youtube-automation',
    text: message
  });
}

// After content generation
notifySlack(`✅ New video generated: "${result.title}" - Scheduled for ${result.scheduledFor}`);
```

### Discord Integration

```javascript theme={null}
const { Webhook } = require('discord-webhook-node');
const hook = new Webhook(process.env.DISCORD_WEBHOOK_URL);

await hook.send({
  username: 'YouTube Automation',
  embeds: [{
    title: '🎬 New Video Published',
    description: result.title,
    url: result.url,
    color: 0x00ff00
  }]
});
```

## Best Practices

<Tip>
  Use manual operations sparingly. The automation system learns and improves when left to run continuously.
</Tip>

### When to Use Manual Operations

✅ **Good Use Cases:**

* Testing new content topics
* Creating time-sensitive content
* Recovering from automation failures
* Initial channel setup and configuration
* Bulk content generation for launch

❌ **Avoid Manual Operations For:**

* Regular daily content (use automation)
* Frequent publishing overrides
* Constant schedule changes
* Micromanaging content topics

### Rate Limiting

Be mindful of API quotas:

* **OpenAI API**: 3,500 requests/minute
* **YouTube Data API**: 10,000 units/day
* **YouTube Analytics API**: 50,000 requests/day

<Note>
  The automation system includes built-in rate limiting with 2-second delays between analytics requests.
</Note>

## Next Steps

<CardGroup cols={2}>
  <Card title="Dashboard Guide" icon="chart-line" href="/guides/dashboard">
    Master the web dashboard interface
  </Card>

  <Card title="API Reference" icon="code" href="/api/overview">
    Complete API endpoint documentation
  </Card>

  <Card title="Agent Configuration" icon="robot" href="/configuration/ai-providers">
    Customize individual agent behaviors
  </Card>

  <Card title="Troubleshooting" icon="wrench" href="/advanced/troubleshooting">
    Solve common issues and errors
  </Card>
</CardGroup>
