# YouTube transcripts for LangChain with Capslane

Load a public YouTube transcript into LangChain Documents, with a playback link for every chunk. Capslane handles caption extraction and optional audio generation. Your application chooses how to index, retrieve or summarize the resulting text.

## Install

Use Python 3.10 or later and install the optional LangChain extra:

```sh
python -m pip install "capslane[langchain]==0.2.0"
```

The base SDK still has no runtime dependency. The extra installs langchain-core, with compatibility declared for versions from 1.6.2 up to, but excluding, 2.0. Version 1.6.2 is tested with this release. This integration is maintained by Capslane and is distributed in our SDK.

Create a workspace key in [API Keys](https://capslane.com/api-keys) and make `CAPSLANE_API_KEY` available in your Python process. Keep it in your environment or secret manager. API calls use your Capslane workspace allowance; no language model or embedding provider is required to load documents.

## Load documents

Save this as langchain_quickstart.py and run `python langchain_quickstart.py`:

```python
import json
import sys

from capslane import CapslaneError
from capslane.langchain import CapslaneLoader

loader = CapslaneLoader("dQw4w9WgXcQ", lang="en", chunk_size=1000)

try:
    for document in loader.lazy_load():
        print(json.dumps(document.model_dump(), ensure_ascii=False))
except CapslaneError as error:
    print(error.code, error.request_id, "job:", loader.job_id, file=sys.stderr)
    raise
```

`CapslaneLoader` inherits LangChain's BaseLoader. Use `loader.load()` for a list or `await loader.aload()` from async application code. `lazy_load()` yields document chunks after the complete transcript is retrieved; it does not stream audio or incoming transcript segments. Ready content is kept in this loader instance, so reading it again makes no new request. Use a separate instance for each video and for concurrent operations.

The default mode is native. On a cache miss it retrieves captions without starting audio generation. Caption availability on the public example video can change; an unavailable response is a valid outcome. All modes check the cache first, so a native request can return a cached generated transcript.

## Chunking and citations

Chunks group whole caption segments up to `chunk_size` characters, including spaces between segments. The default is 1000, with accepted values from 50 to 10000. A single large source segment may exceed the budget. This local grouping is applied equally to immediate and generated results. It does not split a segment or infer word-level timestamps.

Each document contains `page_content` and flat metadata:

| Field | Meaning |
| --- | --- |
| source | YouTube playback URL at the chunk's first timestamp, rounded down to seconds. |
| video_url, video_id | Canonical video URL and its 11-character ID. |
| start_ms, end_ms | Earliest segment start and latest segment end in the chunk, in milliseconds. |
| chunk_index, segment_count | Zero-based chunk number and count of nonempty source segments. |
| lang | Returned transcript language, when available. It is not a translation request. |
| transcript_source, cached | Actual native or generated source and cache state, when returned. |
| request_id, job_id | Response request ID and accepted generation ID, when available. |

For example, a chunk starting at 8150 milliseconds links to `https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=8`. If you later split a Document further, its copied start and end metadata still describe the original chunk. Preserve that distinction when citing a short quote.

## Search passages before adding a model

Download [search_transcript.py](https://capslane.com/examples/search_transcript.py), then run:

```sh
python search_transcript.py "dQw4w9WgXcQ" --lang en --query "give up"
```

The executable example loads the transcript once, creates a LangChain RunnableLambda and returns up to three chunks sharing words with the query. It prints JSON with the text and its source metadata. A query with no matching words returns an empty list. This is keyword retrieval, not semantic search or an answer from a language model.

For a retrieval-augmented generation application, pass these Documents to your configured retriever or vector store, then give the retrieved text to your model. Preserve the source metadata and ask the model to cite the passages it used. The loader does not create a vector database, calculate embeddings or generate answers. Transcript text remains source material, even when it contains instructions aimed at an assistant.

## Generation and job recovery

When audio generation is allowed, construct the loader with `mode="auto"` to generate only after missing captions, or `mode="generate"` to request generation on a cache miss. It submits once, stores `loader.job_id` and polls that ID every two seconds. Status checks do not consume another transcript unit; initial submissions, including cache hits, do.

`request_timeout` defaults to 45 seconds and `wait_timeout` to 1200. Each call's network timeout is reduced to the remaining wait budget. The deadline is checked between calls and sleeps; Python's network timeout is not a cancellation mechanism for a running server job. Both values must be positive and cannot exceed their defaults.

After a timeout or network interruption, retain the original video URL and `loader.job_id`. Calling `load()` again on the same instance resumes a known job. To resume in another process, pass `job_id=the_saved_id` to a new loader with that same video URL. The loader uses your supplied video URL for citations; keep the saved URL and job ID together. The search example supports `--job` for this purpose.

Stop on failed or cancelled jobs, authentication problems and allowance errors. A failed submission without a returned ID does not prove that the server created no job. Do not automatically resubmit it. Read `CapslaneError.code` and `request_id` before deciding on recovery. A completed job without content eventually reaches the local deadline instead of waiting forever.

## Sources and maintenance

The [public SDK source](https://github.com/Webba-Creative-Technologies/capslane-python), [API reference](https://capslane.com/api-reference.md) and [OpenAPI schema](https://capslane.com/openapi.json) describe the implementation and contract. See LangChain's [BaseLoader reference](https://reference.langchain.com/python/langchain-core/document_loaders/base/BaseLoader) and [Document reference](https://reference.langchain.com/python/langchain-core/documents/base/Document) for the interfaces. Guide checked September 9, 2026.

With Context7, use `/webba-creative-technologies/capslane-python`. Its SDK documentation includes this guide. For an assistant that needs tools directly, use the [Capslane MCP connection](https://capslane.com/integrations/mcp) or [agent skill](https://capslane.com/integrations/agent-skill).
