# YouTube To AI RAG (`egsand/youtube-to-ai-rag`) Actor

- **URL**: https://apify.com/egsand/youtube-to-ai-rag.md
- **Developed by:** [Enrique G.](https://apify.com/egsand) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.00 / 1,000 video minute processeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## 🎬 YouTube to AI & RAG: Multimodal Markdown & Visual Extractor

> **Transform any YouTube video into an AI-ready Multimodal Markdown document and structured dataset.**\
> Extract timestamped spoken transcripts synchronized with exact slide, code, and diagram screen captures—ready for **ChatGPT, Claude 3.5, Gemini, Cursor, Notion AI, LangChain, and RAG pipelines.**

***

### ⚡ The Problem: Why Traditional YouTube Scrapers Fail for AI

Most YouTube scrapers on the market only extract plain text transcripts. But in technical tutorials, lectures, webinars, and product demos, **over 70% of critical knowledge is visual**:

- 📊 Complex architectural diagrams and workflows
- 💻 Code snippets, terminal commands, and IDE windows
- 📈 Financial charts, comparison tables, and slide decks
- 🖥️ UI walkthroughs and visual settings

When you feed plain text into an LLM, the model misses the entire visual context.

**YouTube to AI & RAG Extractor solves this completely**: it pairs every spoken paragraph with the **exact visual frame displayed on screen at that precise second**, hosted via permanent high-speed URLs and formatted into token-dense Markdown.

***

### 📊 Feature Comparison

| Feature | Standard YouTube Scrapers | **YouTube to AI & RAG Extractor** |
| :--- | :--- | :--- |
| **Output Format** | Plain raw text or bulky JSON | ✅ **Token-dense Multimodal Markdown + YAML Frontmatter** |
| **Visual Context** | ❌ None (Audio text only) | ✅ **Synchronized screen captures of slides, code & diagrams** |
| **Duplicate Slide Filtering** | ❌ None | ✅ **Smart Visual Deduplication (no redundant images)** |
| **Hosted Image URLs** | ❌ Broken or local paths | ✅ **Permanent cloud-hosted public URLs ready for LLMs** |
| **Clickable Timestamp Links**| ❌ Raw second numbers | ✅ **Direct clickable YouTube jump links (`https://youtu.be/...`)** |
| **Time Range Trimming** | ⚠️ Must download whole video | ✅ **Process specific clips (`startTime` / `endTime`)** |
| **LLM & RAG Ready** | ❌ Requires custom pipelines | ✅ **Drop directly into ChatGPT, Claude, Gemini, or Vector DBs** |

***

### 📄 Sample Multimodal Markdown Output

When processed, each video generates a clean, token-optimized Markdown document structured like this:

```markdown
---
video_id: "7xTGNNLPyMI"
title: "Building Autonomous Agents with Memory & Tool Calling"
channel: "AI Engineering Hub"
duration: "24:18"
time_range: "02:00 - 10:30"
total_captures: 8
source_url: "https://www.youtube.com/watch?v=7xTGNNLPyMI"
---

## Building Autonomous Agents with Memory & Tool Calling
**Channel:** AI Engineering Hub | **Duration:** 24:18 | **Source:** [https://www.youtube.com/watch?v=7xTGNNLPyMI](https://www.youtube.com/watch?v=7xTGNNLPyMI)  
**Extracted Range:** 02:00 - 10:30 | **Visual Captures:** 8 screenshots  

---

#### ⏱️ [02:15](https://youtu.be/7xTGNNLPyMI?t=135)
In this section, we examine the core multi-agent architecture. The supervisor agent coordinates tool execution across worker agents.

![Screen Capture 02:15](https://api.apify.com/v2/key-value-stores/.../records/frame_7xTGNNLPyMI_00135.jpg)

---

#### ⏱️ [04:40](https://youtu.be/7xTGNNLPyMI?t=280)
Here is the concrete implementation. Notice how the state schema persists conversational history across sub-agent handoffs.

![Screen Capture 04:40](https://api.apify.com/v2/key-value-stores/.../records/frame_7xTGNNLPyMI_00280.jpg)

---

#### ⏱️ [07:12](https://youtu.be/7xTGNNLPyMI?t=432)
Finally, let's benchmark latency when streaming tokens with local models versus cloud inference endpoints.

![Screen Capture 07:12](https://api.apify.com/v2/key-value-stores/.../records/frame_7xTGNNLPyMI_00432.jpg)
```

***

### 🛠️ Input Configuration

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `videoUrls` | Array | *(Required)* | List of YouTube video URLs or 11-character video IDs (supports standard watch URLs, youtu.be, shorts, and live streams). |
| `captureMode` | Select | `interval` | Choose capture frequency: `interval` (every N seconds), `timestamp` (on each transcript phrase), `smart_scene` (slide changes), or `none` (text only). |
| `intervalSeconds`| Integer | `15` | Interval in seconds between screenshots when using interval mode (2 to 600 seconds). |
| `deduplicateFrames`| Boolean | `true` | When enabled, skips redundant screenshots if the slide, code window, or graphic hasn't changed. |
| `maxScreenshots` | Integer | `100` | Safety limit on maximum screenshots per video to control token usage and run speed. |
| `preferredLanguages` | Array | `["en", "es", "auto"]` | Prioritized subtitle languages with automatic fallback to original video audio tracks. |
| `startTime` | String | `""` | Optional start timestamp (e.g. `02:30`, `5`, or `01:10:00`). |
| `endTime` | String | `""` | Optional end timestamp (e.g. `12:45` or `01:30:00`). |
| `imageResolution`| Select | `480p` | Resolution of captured slides (`360p` ultra-fast, `480p` recommended sharp text balance, `720p` high-def). |
| `outputFormat` | Select | `both` | Formats to deliver: `both`, `markdown_only`, or `dataset_only`. |
| `proxyConfiguration` | Object | `Default` | Optional proxy settings to access region-restricted videos. |

***

### 🤖 Integrations & AI Workflows

#### 1. Direct LLM Context Injection (Claude 3.5 Sonnet, ChatGPT Plus, Gemini)

Download the generated `.md` file or copy the `aiMarkdown` field directly into your prompt. Vision-capable models will simultaneously analyze the spoken explanations and the code or architecture shown in the screenshots.

#### 2. LangChain & LlamaIndex RAG Pipelines

Load dataset items directly and convert into documents with visual metadata:

**Python (Apify Client & LangChain):**

```python
from apify_client import ApifyClient
from langchain_core.documents import Document

client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("egsand/youtube-to-ai-rag").call(run_input={
    "videoUrls": ["https://www.youtube.com/watch?v=7xTGNNLPyMI"],
    "captureMode": "interval",
    "intervalSeconds": 20
})

dataset_items = client.dataset(run["defaultDatasetId"]).list_items().items
documents = [
    Document(
        page_content=item["aiMarkdown"],
        metadata={
            "title": item["title"],
            "url": item["videoUrl"],
            "duration": item["durationFormatted"]
        }
    )
    for item in dataset_items
]
```

**JavaScript / TypeScript:**

```javascript
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });
const run = await client.actor('egsand/youtube-to-ai-rag').call({
    videoUrls: ['https://www.youtube.com/watch?v=7xTGNNLPyMI'],
    captureMode: 'interval',
    intervalSeconds: 20,
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(`Extracted Markdown for: ${items[0].title}`);
```

#### 3. Automated Workflows with n8n, Make & Zapier

1. **Trigger**: Watch an RSS feed or YouTube channel for new tutorial uploads.
2. **Action**: Run this Actor with the new video URL.
3. **Delivery**: Send the generated Markdown document to Notion, Obsidian, Slack, or a vector store.

***

### 💡 Practical Use Cases

- **AI Researchers & Engineers**: Ingest entire university lecture series, technical conference talks, and paper presentations into your personal RAG knowledge base.
- **Developers & Learners**: Summarize 2-hour coding tutorials into clean, readable Markdown guides with all code snippets captured.
- **Product Teams & Marketers**: Extract competitor demo videos and feature walkthroughs into structured visual reports.
- **Content Creators**: Repurpose video content into illustrated blog articles, LinkedIn carousels, and newsletter guides.

***

### 💰 Transparent Per-Minute Billing

This Actor uses fair **Pay-Per-Event (`video-minute`)** pricing based strictly on the processed video duration:

- **Minimum 1 Minute (Videos < 60s)**: Videos or clips shorter than 60 seconds (such as YouTube Shorts) are billed as **1 minute** (`1 video-minute` event).
- **Per Started Minute Rounding**: Partial minutes are rounded up to the next full minute (e.g., a `03:33` video is billed as `4 minutes`).
- **Clip-Range Savings (`startTime` / `endTime`)**: If you extract a 5-minute segment from a 2-hour video using `startTime` and `endTime`, you are only billed for the **5 minutes processed**, not the full 2-hour video.

***

### ❓ Frequently Asked Questions (FAQ)

**Q: Do the image links expire?**\
A: No. Screenshots are stored in your Apify Key-Value Store with permanent direct URLs that can be embedded anywhere.

**Q: Does it work with videos without official captions?**\
A: Yes! The actor automatically extracts auto-generated speech recognition tracks whenever manual subtitles are not available. If a video has no spoken audio at all, it automatically generates a visual keyframe timeline.

**Q: Can I process only a specific portion of a long video?**\
A: Yes. Use the `startTime` and `endTime` fields (e.g. `startTime: "10:00"`, `endTime: "25:30"`) to extract and pay only for the relevant chapter.

**Q: How are short videos under 1 minute billed?**\
A: Any video or trimmed clip under 60 seconds is billed at the minimum unit of 1 minute (`1 video-minute` event).

# Actor input Schema

## `videoUrls` (type: `array`):

Direct URLs or IDs of YouTube videos to process (supports standard watch URLs, youtu.be, shorts, and live archives).

## `captureMode` (type: `string`):

How screenshots are extracted: 'interval' (every N seconds), 'timestamp' (on each transcript change), 'smart_scene' (on visual slide/scene changes), or 'none' (transcripts only).

## `intervalSeconds` (type: `integer`):

Time spacing in seconds between captures when using interval mode.

## `deduplicateFrames` (type: `boolean`):

Skip consecutive duplicate frames if the presentation slide or code snippet on screen remains unchanged.

## `maxScreenshots` (type: `integer`):

Maximum number of screenshots to store and embed per video to optimize storage and token usage.

## `preferredLanguages` (type: `array`):

List of language codes to prioritize (e.g. \['en', 'es', 'pt', 'fr']). Automatically falls back to original video subtitles or auto-generated tracks.

## `startTime` (type: `string`):

Clip start timestamp (e.g. '01:30', '5', or '01:15:00'). Leaves earlier video unprocessed.

## `endTime` (type: `string`):

Clip end timestamp (e.g. '08:45' or '02:00:00'). Processes only up to this point.

## `imageResolution` (type: `string`):

Quality and resolution of extracted screenshots. '480p' provides the optimal balance of sharp text recognition and fast loading.

## `outputFormat` (type: `string`):

Choose output formats: Multimodal Markdown (AI prompt ready), Structured JSON Dataset, or Both.

## `proxyConfiguration` (type: `object`):

Optional Apify Proxy configuration to bypass regional YouTube restrictions in cloud environments.

## Actor input object example

```json
{
  "videoUrls": [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  ],
  "captureMode": "interval",
  "intervalSeconds": 15,
  "deduplicateFrames": true,
  "maxScreenshots": 100,
  "preferredLanguages": [
    "en",
    "es",
    "auto"
  ],
  "imageResolution": "480p",
  "outputFormat": "both",
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `overview` (type: `string`):

Summary dataset of all processed YouTube videos, duration, language, and total captures.

## `aiMarkdownView` (type: `string`):

Dataset view containing the complete Multimodal Markdown for LLMs with embedded image links and frontmatter.

## `latestAiMarkdown` (type: `string`):

Direct link to download or inspect the formatted Multimodal Markdown file in Key-Value Store.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "videoUrls": [
        "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    ],
    "preferredLanguages": [
        "en",
        "es",
        "auto"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("egsand/youtube-to-ai-rag").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "videoUrls": ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
    "preferredLanguages": [
        "en",
        "es",
        "auto",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("egsand/youtube-to-ai-rag").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "videoUrls": [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  ],
  "preferredLanguages": [
    "en",
    "es",
    "auto"
  ]
}' |
apify call egsand/youtube-to-ai-rag --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,egsand/youtube-to-ai-rag"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/aQ5zhfRRdsXIfLfat/builds/E9OZLKQyPwMRM5pRG/openapi.json
