YouTube Transcript API with LangChain: RAG over a channel

By the YouTubeTranscriptAPI engineering team · Published · Updated

LangChain's YouTube loader worked on my machine in 1.4 seconds. Its video-info option failed with HTTP 400, and the package it lives in is being shut down.

To use the YouTube Transcript API with LangChain, write a small document loader that fetches each video's timestamped transcript, splits it into 90-second windows, and keeps the title, start time and a ?t= link in each chunk's metadata. Embed those chunks, retrieve the closest ones for a question, and have the model cite the links, so every answer points to the exact minute.

The pipeline: list a channel's videos, fetch timestamped transcripts, cut 90-second windows with 15 seconds of overlap, embed them, retrieve the closest windows and answer with title and minute links
Five steps, and the timestamp survives every one of them.

We make YouTubeTranscriptAPI, so the loader in this guide calls our API. The chunking, the citations and the agent tool work the same with any source that gives you segments with start times.

I installed LangChain 1.5.2 and langchain-community 0.4.2 on November 30, 2026, ran the built-in loader, and wrote and tested the script below. Every number here comes from those runs or from a source I link.

How do you load YouTube transcripts into LangChain?

Subclass LangChain's BaseLoader and implement lazy_load, which yields one Document at a time. For each video, call a transcript API with timestamps turned on, group the caption segments into time windows, and put the title, channel, start, end and a ?t= link in each document's metadata. The free youtube_rag.py below does this for single videos, whole channels and playlists.

Here's the whole thing in use:

python
from youtube_rag import YouTubeTranscriptLoader

loader = YouTubeTranscriptLoader(channel="@3blue1brown", limit=20)
for doc in loader.lazy_load():
    print(doc.metadata["title"], doc.metadata["source"])

Each document is one 90-second window of one video. Its source is a link like watch?v=aircAruvnKk&t=75s, which opens the video at that moment.

lazy_load matters for channels. A channel of 100 twenty-minute videos is about 1,500 chunks, and a generator lets you embed and save them in batches instead of holding everything in memory.

Under the hood it's one call per video to the transcript endpoint, with format=json, include_timestamp=true and send_metadata=true. That returns the caption segments with start times, plus the title and channel name, for 1 credit.

One detail worth knowing: if a video has no track in the language you ask for, the API may return another one. The language field says which, and the loader logs it and stores it in each chunk's metadata.

The loader reads YTT_API_KEY from the environment. Get a key from the sign-up page; new accounts get 100 free credits, which covers a first channel.

Why does LangChain's built-in YoutubeLoader break?

It scrapes YouTube from your own server, it depends on a package with no release since 2023, and it lives in langchain-community, which LangChain is shutting down. On my home connection it fetched a transcript in 1.4 seconds. With add_video_info=True it failed with HTTP 400, and on cloud servers the scraping itself is what gets blocked.

The import printed a warning that langchain-community "is being sunset and is no longer actively maintained." The announcement, dated May 22, 2026, says the package has been effectively deprecated for more than a year.

The same announcement says it's often simpler now to implement tools directly in application code. That's what this guide does.

Next, video info. add_video_info=True needs pytube, whose last release on PyPI was 15.0.0 in May 2023. I installed it, and the loader died with "HTTP Error 400: Bad Request."

So the built-in loader gives you chunks with no title. That's a problem for RAG, because "this is explained in a video" is a much worse citation than a title and a minute.

Then the part I couldn't reproduce at home: cloud servers. The loader calls YouTube from wherever your code runs.

A GitHub issue from May 2026 describes the usual pattern: the same code worked on local machines and was blocked on AWS. A Hugging Face forum thread reports the same loader failing in a Space while working locally.

We measured why in our guide to scraping YouTube transcripts at scale. The short version is that data center IPs often get bot checks, and caption URLs came back empty in our November tests.

Last, scope. The built-in loader takes one video URL. For a channel you write the loop, the listing and the error handling yourself.

What does a YouTube document loader need for RAG?

A loader that's good for RAG keeps four things the built-in one drops or makes hard: the video title on every chunk, a start time and a deep link for citations, a way to load a whole channel, and clear handling of videos without captions. It should also be lazy, so a big channel doesn't sit in memory, and it shouldn't charge you twice for the same video.

Here's how the two loaders compare on what I tested:

NeedBuilt-in YoutubeLoader (0.4.2)YouTubeTranscriptLoader in this guide
Works from cloud serversScrapes YouTube from your IPCalls a hosted API
Video title in metadataNeeds pytube; failed with HTTP 400Yes, from the API
Start time per chunkYes, with TranscriptFormat.CHUNKSYes, plus end time
Link to the exact momentYes, in sourceYes, in source
Whole channel or playlistNo, one URLYes, up to 100 newest videos
Video without captionsReturns an empty list, silentlySkipped, logged, not charged
Language you asked for is missingFalls back to English, silentlyReturns another track and logs which
Rate limitsNot handledWaits for Retry-After, then retries
Package statusIn a sunset packageOne file in your repo
LangChain's built-in YoutubeLoader against this guide's loader: the built-in one scrapes YouTube, fails on video titles with HTTP 400, loads one video, and silently returns nothing for videos without captions
Tested on November 30, 2026.

Those two silent rows matter more than they look. In RAG, a video that quietly contributes nothing is invisible: your bot just doesn't know that channel's best talk, and nothing tells you why.

I read both behaviors in the 0.4.2 source and confirmed the language one by asking for a track a video doesn't have.

The built-in loader does get one thing right. Its CHUNKS mode splits by time and keeps start_seconds, which is the idea this whole guide builds on.

Popular tutorials on this topic mostly lose it. I read five in full: a vendor's LangChain guide, a DEV pipeline tutorial, LogRocket's LangChain.js app, Neo4j's knowledge-graph post and Apify's chat-with-a-channel guide.

Four of the five drop the timestamps before the chunks reach the vector store. One defines a timestamp chunker and never calls it.

Only the Apify guide keeps minute links, and it does that in Markdown files for a Claude Project, not in LangChain.

How should you chunk YouTube transcripts for RAG?

Chunk by time, not by characters. Group caption segments into 90-second windows that start and end on segment boundaries, with 15 seconds of overlap so an answer that spans a boundary is still found. On three real caption tracks I measured about 180 spoken words a minute, so a 90-second window comes out at roughly 270 words, and every chunk keeps an exact start time to cite.

Two of the five tutorials, and LangChain's own semantic search tutorial, use RecursiveCharacterTextSplitter with 1,000 characters and 200 of overlap. For retrieval alone, that works.

But it throws away time. A character window has no start second, so the answer can't link to a moment.

It's also smaller than it looks for speech. At the 1,550 or so characters I measured per 90 seconds, a 1,000-character chunk is under a minute of talk, which often cuts an explanation in half.

Here's what I measured on three videos from the same neural-network series:

Video lengthWordsWords per minute90-second windowsMedian words per window
18.4 min3,35718214280
20.2 min3,60217816279
12.5 min2,22317910266
Three real caption tracks cut into 90-second windows: about 180 spoken words a minute and about 275 words per window; 14, 16 and 10 windows
Measured, not assumed.

That's one channel with one speaker, so treat 180 words a minute as a starting point. Fast talkers and two-host podcasts may run higher, so measure your own channel.

The script also puts the video title at the top of each chunk's text before embedding. A question like "what does the backpropagation video say about the chain rule" then matches on the title as well as the words.

Change the window with --window if your videos are dense. I'd test 60 and 120 seconds on 20 real questions before going further.

If you're preparing training data rather than a search index, chunking works differently. Our guide to building a YouTube dataset for AI training covers permissions, cleaning and splits by channel.

How do you index a whole YouTube channel?

Run youtube_rag.py index --channel @handle. It lists the channel's newest uploads for 20 credits, fetches each transcript for 1 credit, cuts the windows, embeds them and saves an InMemoryVectorStore to a JSON file. Run it with --dry-run first to see the video count and cost. Rerun it later and it skips every video already in the file, so you never pay for a transcript twice.

The commands:

bash
pip install "langchain>=1.0" langchain-openai langchain-anthropic
export YTT_API_KEY=tk_live_...
python youtube_rag.py index --channel @3blue1brown --limit 30 --dry-run
python youtube_rag.py index --channel @3blue1brown --limit 30

The script embeds in batches of 200 chunks and saves after each batch. If something stops the run halfway, the work so far is on disk.

That includes running out of credits. A 402 stops the run with "out of credits: top up, then re-run," saves what's done, and the next run picks up with the videos that are left.

Videos without captions are logged and skipped. They cost nothing; the error reference lists which responses are free.

If the API returns a 429, 408 or 503, the loader waits for the Retry-After header and tries again, up to three times. Our rate limit is 300 requests a minute per key, which a single loader can't reach.

The channel listing returns up to the 100 newest uploads. For older videos, our guide to YouTube channel transcripts shows how to reach them by searching inside the channel by topic.

InMemoryVectorStore keeps everything in RAM and saves to one JSON file. That's fine for a few thousand chunks. Past that, swap in a persistent store; the loader doesn't care which one you use.

How do you get answers that cite the exact minute?

Retrieve the six closest windows, give the model each window with a source line in the form title, m:ss, and tell it to copy those links after every claim and say so when the excerpts don't answer the question. Then check the answer: any link that wasn't in the retrieved excerpts is invented, and the script warns you about it.

Here's the part of the prompt that does the work:

text
After each claim, cite the excerpt it came from by copying its SOURCE link
exactly, in the form [title, m:ss](link). If the excerpts don't answer the
question, say so plainly instead of guessing.
The citation check: retrieved excerpts carry SOURCE links; an answer that cites a minute that was never retrieved gets flagged
The script checks every link instead of trusting it.

Run it with python youtube_rag.py ask "How does backpropagation work?".

The default model is Claude Sonnet 5.5 through init_chat_model. Any chat model LangChain supports works with --model, for example an OpenAI or Ollama model.

The link check is the piece I'd keep even if you change everything else. A model that rounds 1:15 to 1:00, or blends two sources into one link, produces a citation that looks fine and lands on the wrong moment.

In my tests, a fake model that answered with one real link and one made-up link got a warning naming the made-up one. Without that check, a wrong minute looks just as convincing as a right one.

Captions can also mishear names and numbers. The prompt asks the model to say when a detail looks garbled rather than repeat it with confidence.

Wrap the same retrieval in a tool with @tool(response_format="content_and_artifact") and pass it to create_agent. The model sees the excerpts with their source links, and your app gets the original documents as the tool message's artifact, so you can show the matching clips in your UI. The script's search_youtube_tool(store) returns that tool ready to use.

In code it's three lines:

python
from langchain.agents import create_agent
from youtube_rag import SYSTEM, search_youtube_tool

agent = create_agent("anthropic:claude-sonnet-5-5", tools=[search_youtube_tool(store)], system_prompt=SYSTEM)

LangChain's agents docs describe create_agent and how tools plug into it. I tested this with create_agent from LangChain 1.5.2 and a scripted fake model. The agent called the tool, got two excerpts back with their documents attached, and answered with a link to the right video.

An agent is the better fit when questions need more than one search. Asking it to "compare what the second and third videos say about gradients" lets it search twice.

If you'd rather not index at all, give the agent live YouTube access instead. Our hosted MCP server exposes transcripts, search and channel listings as tools, and LangChain agents can load MCP tools through the langchain-mcp-adapters package.

The two mix well. Index the channels you care about, and use MCP for the one-off video someone pastes into the chat.

What does a YouTube RAG chatbot cost?

For a 100-video channel of 20-minute talks, transcripts cost about 120 credits and embeddings cost about 2 cents. At our founding prices that's $3 a month for 1,000 credits, or $30 a year for 15,000, and new accounts get 100 free credits. Most of the ongoing cost is the chat model answering questions, not the data.

Here's the math, using what I measured:

Item100 videos, 20 min eachHow it's counted
Channel listing20 creditsOne call, up to 100 videos
Transcripts100 credits1 per video; no captions is free
Chunksabout 1,50015 windows per 20-minute video
Embedding tokensabout 600,000about 390 tokens per window
Embedding costabout $0.012$0.02 per million tokens
Cost of indexing 100 twenty-minute videos: 120 credits, about 1,500 chunks, about 600,000 embedding tokens for about $0.012, and about $0.24 for the credits at the Annual price
The data is cheap; the chat model is the real bill.

The embedding price is from OpenAI's model page for text-embedding-3-small. Tokens are estimated at four characters each, which is a rule of thumb, not a measurement.

At Annual pricing, 120 credits is about 24 cents. Founding prices hold if you subscribe within 7 days of signing up; after that, the standard prices on the pricing page apply.

Every question then sends six windows, about 2,400 tokens, to the chat model. That's the number to watch once real users start asking.

What did I test, and what didn't I?

The script ships with 11 tests, all passing on Python 3.12 with LangChain 1.5.2. They cover the time windows, video ID parsing, lazy loading, channel listing with duplicates, a 404 skip, 429 and 503 retries, a 402 stop that saves partial work, reruns that fetch nothing twice, link checking in answers, and a full create_agent loop with the tool.

The API, the embeddings and the chat model were all fakes in those tests. The API mock returned real status codes and Retry-After headers; the embeddings were LangChain's deterministic fake; the chat model was LangChain's scripted fake.

So the tests show the plumbing works with LangChain's real classes. They don't show answer quality.

I didn't run a real model or the real API on this machine, because there are no keys here. The chunking numbers are real: they come from three caption tracks fetched on November 30, 2026, run through the script's own windows() function.

Before you trust it with users, write 20 questions you know the answers to and check the minutes it cites.

Download youtube_rag.py

Frequently asked questions

Does LangChain have a YouTube transcript loader?

Yes. YoutubeLoader in langchain-community loads one video's transcript and can split it into timed chunks. But that package is being sunset, its video-info option needs pytube, which failed with HTTP 400 in my November 2026 test, and it scrapes YouTube from your own server. A custom BaseLoader that calls a transcript API avoids all three problems.

Why does YoutubeLoader work locally but fail on my server?

It requests YouTube from wherever your code runs. YouTube often blocks data center IP addresses from AWS, Google Cloud and similar hosts, so the same code that works on a home connection gets bot checks or empty captions in production. Proxies help, but they cost money and can still get blocked. A hosted transcript API fetches from its own infrastructure, so your server's IP doesn't matter.

How do I chunk YouTube transcripts for RAG?

Chunk by time rather than characters. Group caption segments into windows of about 90 seconds with 15 seconds of overlap, never cutting a segment, and keep the start time and a link in each chunk's metadata. At about 180 spoken words a minute, a 90-second window is roughly 270 words, a good size for retrieval.

Can a LangChain RAG chatbot cite the exact minute in a video?

Yes, if the timestamps survive chunking. Store each chunk's start time and a watch?v=ID&t=SECONDSs link in metadata, show those links to the model with each excerpt, and tell it to copy them after every claim. Then check that every link in the answer was in the retrieved excerpts, because models sometimes invent or change a timestamp.

How much does it cost to build a RAG chatbot over a YouTube channel?

For 100 twenty-minute videos, transcripts cost about 120 credits including the channel listing, which is about 24 cents at our Annual price. Embedding about 1,500 chunks with text-embedding-3-small costs about a cent. The ongoing cost is the chat model: each question sends about 2,400 tokens of excerpts plus the answer.

Can a LangChain agent search YouTube videos by itself?

Yes. Wrap your vector search in a tool with response_format="content_and_artifact" and pass it to create_agent, so the agent decides when to search your indexed videos. For videos you haven't indexed, connect a YouTube MCP server, which gives the agent live transcript, search and channel tools without building an index first.

Index 20 videos and ask 20 questions

Run the dry run on one channel, index 20 videos, and ask 20 questions you already know the answers to. Click every cited minute. If the links land on the right moments, index the rest of the channel and wire the tool into your agent. If they don't, try 60-second windows before changing anything else.


About the author: the YouTubeTranscriptAPI engineering team builds and runs the hosted YouTube Transcript API and its MCP server. We test every script we publish against mocks or the live product, and say which.