# YouTube Transcript Scraper & API - Chunked for RAG (`darius.c.andrei/youtube-transcripts-rag`) Actor

YouTube transcripts that arrive already chunked for RAG, each chunk carrying a youtu.be?t= link back to the second it was said. Also an MCP server: get_transcript and get_chunks from Claude or Cursor. Videos, channels, playlists, searches. Never charges for a video it could not transcribe.

- **URL**: https://apify.com/darius.c.andrei/youtube-transcripts-rag.md
- **Developed by:** [Darius Andrei](https://apify.com/darius.c.andrei) (community)
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 transcripts

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

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 Transcripts for RAG

**Transcripts that arrive already chunked, with a timestamp link on every chunk — and
you are never charged for a video that did not come back.**

A failed video still gets you a row, with a code saying whether the video has no captions
or whether we broke. Both are free. Only a delivered transcript is billed.

Most YouTube transcript scrapers hand you one long string. You then write the splitter,
the overlap logic and the "where in the video did this come from" bookkeeping yourself —
and that bookkeeping is the part that decides whether your RAG answers can cite anything.

This actor does that half. Each chunk comes back with its own `https://youtu.be/<id>?t=<s>`
link, so a retrieved chunk is a clickable jump to the second it was said. Chapters from
the video description are used as chunk boundaries when the video has them.

### What comes back

Real output, trimmed — one video, `chunkSize: 512`:

```jsonc
{
  "videoId": "aircAruvnKk",
  "title": "But what is a neural network? | Deep learning chapter 1",
  "channel": "3Blue1Brown",
  "status": "success",
  "language": "en",
  "languageSource": "manual",
  "durationSeconds": 1120,
  "chunks": [
    {
      "index": 0,
      "text": "This is a 3. It's sloppily written and rendered at an extremely low resolution of 28x28 pixels, but your brain has no trouble recognizing it as a 3...",
      "startSec": 4.22,
      "endSec": 106.04,
      "startUrl": "https://youtu.be/aircAruvnKk?t=4",
      "tokenCount": 436,
      "chapterTitle": "Introduction example"
    },
    {
      "index": 1,
      "text": "This video is just going to be devoted to the structure component of that, and the following one is going to tackle learning...",
      "startSec": 95.36,
      "endSec": 214.16,
      "startUrl": "https://youtu.be/aircAruvnKk?t=95",
      "tokenCount": 504,
      "chapterTitle": "Series preview"
    }
  ]
}
```

`startUrl` is the field that matters. Store it beside the vector and your answers cite a
second of video instead of a video.

***

### Worked example: a transcript you can cite

Fetch a video, chunk it, embed it, ask a question, print the answer with a link back to
the moment it was said.

```bash
npm i apify-client openai
```

```js
import { ApifyClient } from 'apify-client';
import OpenAI from 'openai';

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const openai = new OpenAI();

const embed = async (texts) => {
    const res = await openai.embeddings.create({ model: 'text-embedding-3-small', input: texts });
    return res.data.map((d) => d.embedding);
};

// 1. Run the actor and take its dataset.
const run = await client.actor('darius.c.andrei/youtube-transcripts-rag').call({
    startUrls: [{ url: 'https://www.youtube.com/watch?v=ZPUtA3W-7_I' }],
    chunkSize: 512,
    chunkOverlap: 64,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();

// 2. Keep the successes. An error row has no `transcript` key at all, so this
//    filter is the whole guard — there is no empty string to sneak through.
const chunks = items
    .filter((item) => item.status === 'success')
    .flatMap((item) => item.chunks);

// 3. Embed. The chunking already happened; there is no splitter to write.
const vectors = await embed(chunks.map((c) => c.text));
const [query] = await embed(['what did he say about democracy?']);

// 4. Nearest chunk.
const cosine = (a, b) => {
    let dot = 0, na = 0, nb = 0;
    for (let i = 0; i < a.length; i += 1) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }
    return dot / (Math.sqrt(na) * Math.sqrt(nb) || 1);
};
const best = chunks[vectors.map((v) => cosine(v, query)).reduce((m, s, i, arr) => (s > arr[m] ? i : m), 0)];

// 5. The point of the whole thing: the answer carries a seekable citation.
console.log(best.text);
console.log(`watch it: ${best.startUrl}`, best.chapterTitle ? `· ${best.chapterTitle}` : '');
```

```
Democracy is in the DNA of India, it is not a gift of any constitution...

watch it: https://youtu.be/ZPUtA3W-7_I?t=1260 · Democracy
```

Swap step 4 for Pinecone, Chroma, pgvector or whatever you already run — the chunk is
already the unit you store, and `startUrl` is the metadata field you keep beside it.

This example lives in [`examples/rag-quickstart.mjs`](examples/rag-quickstart.mjs) and is
covered by `examples/rag-quickstart.test.mjs`, which runs it on every test pass with the
two API calls stubbed, so the field names and the citation line cannot drift from the
code.

#### Chunk fields

| field | type | meaning |
|---|---|---|
| `index` | number | position in the video, from 0 |
| `text` | string | the chunk |
| `startSec` | number | when it starts, in seconds |
| `endSec` | number | when it ends |
| `startUrl` | string | `https://youtu.be/<id>?t=<startSec>` — the citation |
| `tokenCount` | number | approximate tokens (words / 0.75) |
| `chapterTitle` | string | **present only when the video has chapters** |

Chunk sizes are in **approximate tokens**, not characters, and not a tokenizer's tokens:
we ship no tokenizer, because its vocabulary would have to match whichever model you
embed with. Caption segments are atomic — a chunk ends on a segment boundary, so the real
size lands near `chunkSize` rather than on it.

***

### Input

`startUrls` takes `{"url": "..."}` objects or bare strings. Five shapes work:

```jsonc
// one video
{ "startUrls": [{ "url": "https://www.youtube.com/watch?v=ZPUtA3W-7_I" }] }

// several videos
{ "startUrls": [
    { "url": "https://www.youtube.com/watch?v=ZPUtA3W-7_I" },
    { "url": "https://youtu.be/dQw4w9WgXcQ" },
    { "url": "aqz-KE-bpKQ" }                       // a bare video id is fine
] }

// a whole channel, by handle or by id
{ "startUrls": [{ "url": "https://www.youtube.com/@veritasium" }], "maxVideos": 200 }

// a playlist
{ "startUrls": [{ "url": "https://www.youtube.com/playlist?list=PL..." }], "maxVideos": 100 }

// a search
{ "startUrls": [{ "url": "https://www.youtube.com/results?search_query=rag+pipelines" }] }
```

A watch URL that happens to carry a `&list=` is treated as **the single video**, not the
playlist.

| field | default | what it does |
|---|---|---|
| `startUrls` | — | required |
| `maxVideos` | 50 | per input URL. Caps the paging too, so a lower number is a faster run |
| `language` | `[]` | preferred codes, best first (`en`, `pt-BR`). Empty = the video's own |
| `languageFallback` | `translated` | `translated` / `auto-generated` / `manual-only` |
| `outputFormats` | `["text"]` | `text`, `json`, `srt`, `vtt` |
| `includeChunks` | `true` | the chunks above |
| `chunkSize` | 512 | approximate tokens |
| `chunkOverlap` | 64 | approximate tokens, clamped to half the chunk size |
| `chunkBoundary` | `sentence` | `sentence` / `chapter` / `none` |
| `proxyConfiguration` | Apify residential | leave it alone — see below |

#### Why the proxy default is residential

Measured, not assumed. Through datacenter addresses a run returns about twenty transcripts
and then every request after that is `Sign in to confirm you're not a bot` — including a
re-run of the *same twenty video IDs* seven minutes later, so it is the address pool burning
rather than anything about the videos. On residential, 200 videos returned **197 transcripts
and 3 real `NO_CAPTIONS`, with nothing failing on our side.**

The proxy cost is already inside the $0.005. Turning it off is the configuration that does
not work.

#### Limits worth knowing before you set `maxVideos`

These are YouTube's, not ours, and they are measured:

- **A channel or playlist stops paging at 200 pages, about 20,000 videos.** Page 200 comes
  back without a continuation token. Not an error, not a throttle — the end of the road.
- **A search goes dry at roughly 210–260 results**, with page sizes tapering off.
- **A channel expands through its uploads playlist, so shorts and past livestreams are
  included.** The `/videos` tab would filter them out and does not page, so there is no
  "long-form only" option today. If you need one, say so and it gets built.

Set `maxVideos` above these and the run logs what it could not reach rather than
pretending the number was met.

***

### Output: the dataset row

One row per requested video. The shape is **stable and changes additively** — fields get
added, existing fields do not change meaning or type. Build a pipeline on it.

| field | type | present | meaning |
|---|---|---|---|
| `videoId` | string | always | empty on an error against a URL that never resolved to a video |
| `url` | string | always | the watch URL; on an unresolvable input, the string you pasted |
| `status` | `"success"` | `"error"` | always | |
| `title` | string | success | |
| `channel` | string | success | |
| `durationSeconds` | number | **null** | success | **null when YouTube omits `lengthSeconds`** |
| `language` | string | success | the language delivered — the target when translated |
| `languageSource` | string | success | `manual`, `asr` (auto-generated), or `translated` |
| `transcript` | string | **only if `text` is in `outputFormats`** | the plain transcript |
| `segments` | array | **only if `json` is in `outputFormats`** | `{ start, end, text }`, seconds |
| `chunks` | array | **only if `includeChunks`** | the table above |
| `chapters` | array | success | from description timestamps; `[]` when there are none |
| `srt` | string | only if `srt` is in `outputFormats` | |
| `vtt` | string | only if `vtt` is in `outputFormats` | |
| `error` | object | error | `{ code, reason, ourFault }` |
| `meta` | object | success | `{ client, bytes, segmentCount }` — diagnostics |

Three things that will bite a pipeline written from a guess:

1. **`transcript`, `segments` and `chunks` are conditional.** Ask for only SRT and you do
   not pay dataset size for a plain-text duplicate — and you do not get a `transcript`
   key.
2. **An error row has no `transcript` key at all.** Not an empty string. An empty string
   is what an ingestion pipeline swallows silently and embeds as nothing.
3. **`durationSeconds` can be `null`.**

#### Error codes

Every code is one of two kinds, and `error.ourFault` says which:

| code | ourFault | meaning |
|---|---|---|
| `NO_CAPTIONS` | false | the video has no caption track — including one that is nothing but `[Music]` |
| `LIVE_NO_CAPTIONS` | false | a stream that is live right now. It may get captions when it ends |
| `LANGUAGE_UNAVAILABLE` | false | captions exist, but not in a language your settings accept |
| `AGE_RESTRICTED` | false | "Sign in to confirm your age" |
| `VIDEO_PRIVATE` | false | the uploader set it to private |
| `MEMBERS_ONLY` | false | behind a channel membership |
| `REGION_BLOCKED` | false | not playable from the country the request came from |
| `VIDEO_UNAVAILABLE` | false | deleted, never existed, or otherwise gone |
| `INVALID_URL` | false | not a YouTube URL, or a target that does not exist |
| `FETCH_FAILED` | **true** | we broke, after exhausting both client tiers |
| `BOT_CHECK_FAILED` | **true** | YouTube asked us to sign in. Ours to fix, not yours |

`VIDEO_PRIVATE`, `MEMBERS_ONLY` and `REGION_BLOCKED` are classified from YouTube's own
refusal text. We have not yet caught one in the wild to confirm the wording still matches —
a video that lands in none of them comes back as `VIDEO_UNAVAILABLE`, so a walled video is
always reported as unavailable rather than as a transcript you did not get.

**`NO_CAPTIONS` is a fact about the video. `FETCH_FAILED` is our fault. You are never
charged for either.** A competitor returning an empty string for both is why their users
cannot tell a dead video from a dead scraper.

#### Was the run complete?

The `RUN_SUMMARY` record in the run's key-value store, so you do not have to parse logs:

```json
{ "startUrls": 1, "attempted": 200, "succeeded": 193, "failed": 7,
  "skipped": 0, "ourFailures": 0, "charged": 193,
  "warnings": ["https://www.youtube.com/playlist?list=PL...: 26 unavailable videos are hidden"] }
```

`ourFailures` is the health number. Expansion warnings land here and in the log, and
deliberately **not** in the dataset: the dataset is what you embed, and a warning row
would be ingested as if someone had said it in a video.

***

### Pricing

**$5.00 per 1,000 transcripts** — $0.005 each, with the first hour of every video included.

| event | price | fires on |
|---|---|---|
| Transcript delivered | $0.005 | one per video that came back with a transcript |
| Extra video-hour | $0.005 | each started hour past the first — a 3-hour podcast adds 2 |

Most videos never reach the second line. A 58-minute lecture is $0.005 flat. The surcharge
exists because a three-hour podcast moves roughly fifteen times the bytes of an average
video, and one flat price would mean quietly refusing to serve the long ones.

- **No actor-start fee.** A run that returns nothing costs nothing.
- **A failed video is free.** The charge fires on a delivered transcript and nothing else —
  no captions, age wall, our own failure: all free. A failed long video is free too: the
  surcharge rides on the transcript charge and cannot fire without it.
- **A resumed run does not re-bill.** What was charged is written down before it is
  charged, so a platform migration mid-run cannot bill a video twice — or surcharge it twice.
- **Your cost limit is a real stop.** Set a maximum cost per run and the actor stops
  fetching when it is reached, rather than scraping the rest of the channel for free and
  handing you a short dataset with no explanation. The run log says it stopped and why.

***

### MCP: use it from Claude or Cursor

The actor runs in Standby mode and serves MCP over `POST /mcp`.

```jsonc
{
  "mcpServers": {
    "youtube-transcripts": {
      "type": "http",
      "url": "https://darius-c-andrei--youtube-transcripts-rag.apify.actor/mcp",
      "headers": { "Authorization": "Bearer YOUR_APIFY_TOKEN" }
    }
  }
}
```

Two tools, and only two:

| tool | arguments |
|---|---|
| `get_transcript` | `url`, `lang?` |
| `get_chunks` | `url`, `chunkSize?`, `overlap?`, `lang?` |

**Both are single-video on purpose.** A channel or playlist URL is refused with a message
telling you to run the actor instead. An MCP call that quietly starts a 4,000-video job is
a surprise bill, and we would rather say no.

***

### Questions people arrive with

**"My scraper worked and now every request says `Sign in to confirm you're not a bot`."**
Your IP pool is burnt, not your code. Measured here: through datacenter addresses a run
returns about twenty transcripts and then every request fails — *including a re-run of the
same twenty video IDs seven minutes later*. Same videos, same code, different outcome, so
it is the address and not the request. Through residential addresses the same 200 videos
returned 197 transcripts. There is no header, client or delay that fixes a burnt pool.

**"Is this an alternative to the `youtube-transcript-api` Python library?"** For bulk, yes,
and for the same reason: that library runs from your IP, which is exactly the thing that
gets blocked. This runs through rotating residential addresses with the cost already inside
the per-transcript price. For a handful of videos from your laptop, the library is free and
fine — use it.

**"Do I get charged when a video has no captions?"** No. The charge fires on a delivered
transcript and nothing else. You still get a row with an error code, so your pipeline can
tell a video that has no captions from a scrape that failed.

**"Can it do a whole channel?"** Yes — channel, playlist or search URL, up to YouTube's own
ceiling of about 20,000 videos. See the limits section for where YouTube stops paging.

**"Does it handle videos in other languages?"** It returns the language the video is
actually in, and can translate when you ask. Getting this right is harder than it sounds:
YouTube lists caption tracks alphabetically, not original-language-first, so a naive reader
hands you a 3Blue1Brown video in Arabic.

### What this does not do

Stated here rather than discovered later:

- **No retry or backoff on a transient HTTP error.** Nothing in hundreds of measured
  videos hit one, so it has not been built, and advertising an untested branch as
  resilience is how reliability claims become refund requests.
- **No "long-form only" channel filter.** See the limits section.
- **No tokenizer.** Chunk sizes are approximate tokens.
- **No private, members-only or region-locked videos.** Nothing signs in.

# Actor input Schema

## `startUrls` (type: `array`):

Videos, channels, playlists or search result pages. A channel or playlist is expanded into its videos; a watch URL that happens to carry a \&list= is treated as the single video, not the playlist.

## `maxVideos` (type: `integer`):

Cap per input URL. Also caps the paging, so a smaller number is a faster run. YouTube's own ceilings apply above this: playlist and channel paging stops at 20,000 videos, and a search goes dry at about 260 results however high you set this.

## `language` (type: `array`):

Language codes, best first, e.g. en, de, pt-BR. Leave empty to take whatever language the video is in. A regional code matches its base language both ways: en answers en-GB.

## `languageFallback` (type: `string`):

How far to fall back. Machine translation is last because it is the lowest-quality answer. With no preferred language set, this only decides whether auto-generated captions are acceptable.

## `outputFormats` (type: `array`):

What each dataset row carries. Plain text is the default; JSON adds the timed segments; SRT and WebVTT add subtitle files. Chunks are controlled separately below.

## `includeChunks` (type: `boolean`):

Split the transcript into overlapping chunks, each with its own youtu.be?t= link back to the moment it starts. This is what makes the output ingestible without a second pass.

## `chunkSize` (type: `integer`):

Target length per chunk in approximate tokens, estimated as words / 0.75 — we do not ship a tokenizer, because its vocabulary would have to match whatever model you use. Caption segments are atomic, so a chunk ends on a segment boundary and the real size lands near this rather than on it.

## `chunkOverlap` (type: `integer`):

Approximate tokens repeated from the end of the previous chunk, so a sentence split across two chunks is still retrievable from either. Must be smaller than the chunk size; it is clamped to half of it if not.

## `chunkBoundary` (type: `string`):

Where a chunk is allowed to end. Chapter boundaries need timestamps in the video description; videos without them fall back to sentences.

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

Leave this alone unless you know you need to change it. YouTube serves datacenter addresses for about twenty videos and then answers every request with a bot check, so residential is the default and is what the published reliability number was measured on. Turning the proxy off makes the run come from Apify's own addresses, which is the case that does not work.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://www.youtube.com/@veritasium"
    }
  ],
  "maxVideos": 50,
  "language": [],
  "languageFallback": "translated",
  "outputFormats": [
    "text"
  ],
  "includeChunks": true,
  "chunkSize": 512,
  "chunkOverlap": 64,
  "chunkBoundary": "sentence",
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}
```

# Actor output Schema

## `transcripts` (type: `string`):

One record per video requested — successes carry the transcript and the chunks, failures carry an error code and were not charged for.

## `runSummary` (type: `string`):

Counts for the run: attempted, succeeded, failed, how many of those failures were ours, and whether the run stopped at the cost limit.

# 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 = {
    "startUrls": [
        {
            "url": "https://www.youtube.com/@veritasium"
        }
    ],
    "language": [],
    "proxyConfiguration": {
        "useApifyProxy": true,
        "apifyProxyGroups": [
            "RESIDENTIAL"
        ]
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("darius.c.andrei/youtube-transcripts-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 = {
    "startUrls": [{ "url": "https://www.youtube.com/@veritasium" }],
    "language": [],
    "proxyConfiguration": {
        "useApifyProxy": True,
        "apifyProxyGroups": ["RESIDENTIAL"],
    },
}

# Run the Actor and wait for it to finish
run = client.actor("darius.c.andrei/youtube-transcripts-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 '{
  "startUrls": [
    {
      "url": "https://www.youtube.com/@veritasium"
    }
  ],
  "language": [],
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}' |
apify call darius.c.andrei/youtube-transcripts-rag --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,darius.c.andrei/youtube-transcripts-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/oaB34y3PlluNdwyzb/builds/lBqRGwaWBRyPF6coz/openapi.json
