Integrations
LangChain YouTube Transcript Loader
Load public YouTube transcripts into LangChain Document objects without fighting datacenter IP rejections from youtube-transcript-api. Social Media Scraper exposes a hosted GET /v1/youtube/transcript endpoint that you wrap in a 25-line custom BaseLoader—no separate langchain-community connector required.
- Replaces fragile local
YoutubeLoaderscrapes on AWS, GCP, and Docker hosts with authenticated HTTPS calls toGET /v1/youtube/transcript. - Maps
data.text,data.language, anddata.source_urldirectly into standard LangChainDocument(page_content, metadata)objects. - Pairs with
youtube.playlist,youtube.channel_videos, andyoutube.postfor multi-video discovery and title enrichment. - Priced at $0.003 (3 credits) per request (
$3.00per 1,000 transcripts) on one-time USD packs with zero recurring subscriptions.

youtube.transcriptSocial Media Scraper is a read-only HTTP data layer, not a published PyPI langchain-community package, vector database, or audio speech-to-text engine. Your LangChain codebase owns chunking, embeddings, storage, and prompts while the API retrieves available public caption tracks and video metadata.
- Verify one transcript over cURL
- Map response fields into Document objects
- Split text and index into your vector store
Why YoutubeLoader Breaks Once You Deploy to the Cloud
Most LangChain video Q&A prototypes begin with from langchain_community.document_loaders import YoutubeLoader. Under the hood, that helper delegates to youtube-transcript-api from the local machine's IP address. On a developer laptop it usually passes; once the exact same code ships to an AWS EC2 container, GitHub Actions runner, or cloud notebook, YouTube frequently answers datacenter IP ranges with HTTP 429 throttles, consent interstitials, or empty caption responses.
Maintaining rotating residential proxies inside a Python ingestion worker quickly costs more engineering time than the RAG chain itself. Calling GET /v1/youtube/transcript from a small subclass of langchain_core.document_loaders.BaseLoader moves HTTP retrieval behind an authenticated REST contract while keeping your LangChain splitters, retrievers, and prompt templates completely unchanged.
Because the API returns normalized JSON containing data.text, data.language, and data.source_url plus a traceable request_id, every chunk stored in Pinecone, pgvector, Qdrant, or Chroma keeps verifiable provenance back to the original watch URL.
Custom BaseLoader vs YoutubeLoader and Proxy Stacks
Before installing extra community dependencies or wiring proxy pools, compare how each ingestion approach behaves in cloud production.
| Dimension | Default YoutubeLoader | Custom BaseLoader + REST API | Self-hosted proxy pool |
|---|---|---|---|
| Cloud IP reliability | Frequently throttled or refused on AWS, GCP, and Azure IPs | Managed behind GET /v1/youtube/transcript over HTTPS | Depends on ongoing proxy rotation and ban monitoring |
| Python dependencies | langchain-community, youtube-transcript-api, optional pytube | langchain-core plus Python stdlib urllib or httpx | Custom HTTP client, proxy SDK, and retry middleware |
| Metadata enrichment | Optional add_video_info often breaks on upstream HTML shifts | Explicit GET /v1/youtube/post call when title/channel fields are needed | Requires separate HTML or Data API parsing |
| Cost structure | Free locally, unpredictable failures in cloud jobs | Fixed $0.003 (3 credits) per request, pay-as-you-go prepaid USD | Monthly residential bandwidth minimum plus proxy ops |
YouTube Endpoints for Single Videos, Playlists, and Channels
A production RAG index rarely stops at one URL. Combine four documented YouTube endpoints—each billed at $0.003 (3 credits) per request—to discover video URLs, pull caption text, and attach bibliographic metadata to every Document.
| Operation | Key query parameters | Role in a LangChain loader | Rate / request |
|---|---|---|---|
| youtube.transcript | url (required), language, original_audio, cache_max_age (1d–30d) | Fetches data.text, data.language, and data.source_url for Document.page_content | $0.003 |
| youtube.post | url (required), language, cache_max_age (1d–30d) | Adds title, published_at, author.display_name, and media.duration_ms to Document.metadata | $0.003 |
| youtube.playlist | playlist_id (required), continuationToken | Enumerates public playlist video URLs before calling youtube.transcript | $0.003 |
| youtube.channel_videos | channel_id or handle (exactly one), sort (latest | popular), continuationToken | Lists a channel's public uploads for incremental corpus indexing | $0.003 |
Inspect exact parameter validation rules and JSON schemas in the OpenAPI specification or the individual operation pages under the API directory.
Step-by-Step Setup for the LangChain YouTube Transcript Loader
Verify a single transcript response from the command line before wiring your custom Python or TypeScript loader into an embedding pipeline.
Step 1: Verify one transcript over cURL
Export
SOCIALSCRAPER_API_KEYin your shell and run the starter command below against a known public YouTube watch URL. The quick cURL snippet illustrates the endpoint andx-api-keyheader; when moving into application code, always include a uniqueIdempotency-Keyheader (8–128 ASCII characters matching[A-Za-z0-9._:-]+) on every logical request.Step 2: Map response fields into Document objects
Inspect
data.text,data.language, anddata.source_urlfrom the JSON response alongside the top-levelrequest_id. Check thatdata.textis a non-empty string before instantiatingDocument(page_content=..., metadata={...})so captionless videos never pollute your vector index.Step 3: Split text and index into your vector store
Pass yielded
Documentinstances throughRecursiveCharacterTextSplitter(keepingsource,language, andrequest_idattached to every chunk) and write embeddings to your chosen store. Cap concurrency at or below your live account limit (default 5 in-flight requests, 60 accepted requests per minute).
curl --get "https://socialmediascraper.org/v1/youtube/transcript" \
--header "x-api-key: $SOCIALSCRAPER_API_KEY" \
--data-urlencode "url=https://www.youtube.com/watch?v=dQw4w9WgXcQ"
Implementing a Custom Python BaseLoader
There is no third-party langchain-socialmediascraper package to maintain or upgrade across LangChain releases. Subclassing BaseLoader from langchain_core takes roughly 30 lines of standard Python and works across LangChain v0.3+ and v1.x chains, LCEL pipelines, and LangGraph nodes.
import json
import os
import urllib.parse
import urllib.request
import uuid
from typing import Iterator
from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
class YouTubeTranscriptAPILoader(BaseLoader):
def __init__(self, urls: list[str], language: str | None = None, cache_max_age: str = "7d"):
self.urls = urls
self.language = language
self.cache_max_age = cache_max_age
self.api_key = os.environ["SOCIALSCRAPER_API_KEY"]
def lazy_load(self) -> Iterator[Document]:
for video_url in self.urls:
params = {"url": video_url, "cache_max_age": self.cache_max_age}
if self.language:
params["language"] = self.language
endpoint = "https://socialmediascraper.org/v1/youtube/transcript?" + urllib.parse.urlencode(params)
req = urllib.request.Request(
endpoint,
headers={
"x-api-key": self.api_key,
"Idempotency-Key": str(uuid.uuid4()),
},
)
with urllib.request.urlopen(req, timeout=45) as resp:
payload = json.loads(resp.read().decode("utf-8"))
data = payload.get("data") or {}
text = (data.get("text") or "").strip()
if not text:
continue
yield Document(
page_content=text,
metadata={
"source": data.get("source_url") or video_url,
"language": data.get("language"),
"request_id": payload.get("request_id"),
},
)
- Chunking defaults: Follow
loader.load()withRecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)so spoken paragraphs stay coherent across retrieval boundaries. - Optional bibliographic metadata: Call
GET /v1/youtube/postonce per video when you needtitle,published_at, orauthor.display_namestored on every chunk, leaving missing fields asNone(null) rather than empty placeholders. - TypeScript / LangChain.js parity: The same pattern translates directly to
BaseDocumentLoaderin@langchain/core/document_loaders/baseusing Node 18+fetchandcrypto.randomUUID().
Practical LangChain Workflows Built on YouTube Transcripts
Video Q&A with clickable source links
Keep data.source_url in every chunk's metadata['source'] so create_retrieval_chain or custom LCEL prompts cite the exact YouTube watch page behind each synthesized answer.
Channel-wide technical knowledge bases
Enumerate conference talks or engineering deep dives via youtube.channel_videos, track already-indexed video IDs in your database, and only request youtube.transcript for new uploads.
Authorized course and lecture search
Pull public playlist entries through youtube.playlist, enrich titles with youtube.post, and expose semantic search across lecture material you hold permission to index.
Handling Empty Captions, HTTP 202, and Prompt Safety
Videos without public captions
Instrumental clips, uncaptioned livestreams, and uploads with disabled subtitles can return empty or missing data.text. Skip empty payloads cleanly in lazy_load() and log the video URL as uncaptioned; the endpoint reads available caption tracks rather than running audio transcription.
Idempotency, HTTP 202, and 429 backoff
Generate one Idempotency-Key per logical video lookup and reuse that exact key only if you retry the identical URL after a transient error. If a response returns HTTP 202, poll GET /v1/requests/{request_id} before issuing another call; on HTTP 429, sleep for the duration in Retry-After.
Untrusted transcript text in RAG prompts
YouTube captions originate from third-party speakers and auto-caption engines. Wrap retrieved chunks inside explicit delimiters (such as <transcript_excerpt>...</transcript_excerpt>) and instruct your LangChain system prompt to treat retrieved text strictly as reference data, never as tool-calling instructions.
Request Pricing and Batch Ingestion Math
Every call to GET /v1/youtube/transcript, GET /v1/youtube/post, GET /v1/youtube/playlist, and GET /v1/youtube/channel_videos uses the standard flat rate of $0.003 (3 credits) per request ($3.00 per 1,000 requests; 1,000 credits = $1), regardless of video duration or transcript length.
| Ingestion job | API calls made | Published USD cost |
|---|---|---|
| 100 videos (transcripts only) | 100 × youtube.transcript | $0.30 |
| 1,000 videos (transcripts only) | 1,000 × youtube.transcript | $3.00 |
| 1,000 videos + title/date metadata | 1,000 × transcript + 1,000 × post | $6.00 |
| 500-video channel crawl (10 listing pages + transcripts) | 10 × channel_videos + 500 × transcript | $1.53 |
Every new account receives 100 starter credits ($0.10, ~33 standard calls) upon signup; scale up with one-time prepaid packs—$5 (5,000 credits, ~1,666 standard requests), $20 (20,000 credits, ~6,666 requests), or $50 (50,000 credits, ~16,666 requests)—at the identical per-request rate, with no monthly seat fees or auto-renewal. Review live catalog rates on the pricing page or machine-readable pricing JSON.
Operational Limits and Content Boundaries
- Public caption tracks only: Private, unlisted-restricted, members-only, age-gated, or deleted videos are outside scope. The endpoint does not return raw MP4/audio downloads or synthesize transcripts from raw audio.
- No bundled RAG infrastructure: Chunking, embedding models, vector storage, re-ranking, and scheduled sync loops live in your own LangChain application.
- Null preservation: When pairing transcripts with
youtube.postmetadata, keep missing counts or dates asnull(None) instead of defaulting to0. - Pre-production checks and rights: Check current telemetry on service status and contract notes in API documentation before running large backfills. Publicly readable captions do not automatically convey redistribution or commercial republishing rights; verify source terms and copyright compliance.
LangChain YouTube Transcript Loader Questions
Is there an official langchain-community package for Social Media Scraper?
No. Rather than wrapping another third-party dependency that can drift behind langchain-core upgrades, you subclass BaseLoader directly in roughly 30 lines of Python (or BaseDocumentLoader in TypeScript) and call GET /v1/youtube/transcript over HTTPS.
Why does YoutubeLoader fail when deployed to AWS, GCP, or Docker?
LangChain's built-in YoutubeLoader relies on youtube-transcript-api, which sends unauthenticated requests directly from your host IP. YouTube routinely rate-limits or rejects requests originating from shared datacenter IP ranges. Routing caption fetches through a hosted REST API avoids maintaining your own proxy pool.
Does youtube.transcript run Whisper if a video has no subtitles?
No. GET /v1/youtube/transcript retrieves available public caption tracks (manual or YouTube auto-generated captions where exposed). It does not download video files or run speech-to-text transcription on raw audio.
How do I include the video title, channel name, and publish date in Document metadata?
The transcript endpoint returns data.text, data.language, and data.source_url. When your RAG retriever needs filtering by channel, publish date, or video title, pair it with GET /v1/youtube/post ($0.003 / 3 credits per video) and merge those fields into Document.metadata.
Can I load an entire YouTube playlist or channel into LangChain?
Yes, using a two-step loader. First page through GET /v1/youtube/playlist (with playlist_id and continuationToken) or GET /v1/youtube/channel_videos (with either channel_id or handle plus continuationToken) to collect public video URLs, then fetch each transcript via GET /v1/youtube/transcript.
How should my loader handle videos that return empty transcript text?
Check (data.get('text') or '').strip() before yielding a Document. Skipping empty strings prevents blank vectors in your index while letting you record the URL in a separate dead-letter or uncaptioned log.
How much does it cost to index 1,000 YouTube videos into a RAG pipeline?
Fetching 1,000 transcripts via GET /v1/youtube/transcript costs $3.00 ($0.003 / 3 credits per request), regardless of whether a video is 3 minutes or 3 hours long. Adding GET /v1/youtube/post metadata for all 1,000 videos doubles the call count to 2,000 requests ($6.00).
Does this pattern work with LangChain.js and TypeScript?
Yes. Extend BaseDocumentLoader from @langchain/core/document_loaders/base, call GET /v1/youtube/transcript with Node 18+ built-in fetch, attach x-api-key and crypto.randomUUID() as Idempotency-Key, and return Document instances. See the Node.js YouTube transcript tutorial for a JavaScript baseline.
What does the cache_max_age parameter do on transcript requests?
cache_max_age accepts 1d, 3d, 7d, 14d, or 30d to specify the maximum acceptable age of a cached transcript result. Setting 7d or 30d is practical for archived lectures or historical talks whose captions rarely change.
What concurrency and rate limits apply during a large backfill?
Accounts default to 60 accepted requests per minute (sliding window) and 5 concurrent in-flight requests. Pace your Python or Node worker within those limits, respect Retry-After if you receive HTTP 429, and reuse the same Idempotency-Key only when retrying the identical request.
Can this loader pull captions from private or members-only YouTube videos?
No. Social Media Scraper accesses supported public social data only and cannot authenticate as a YouTube member or bypass private video permissions.