> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Importly with LangChain and LangGraph

> Replace YoutubeLoader in a deployed LangChain or LangGraph app: tools that transcribe, download and describe any video or audio link, plus a loader that returns Documents, in TypeScript and Python.

`YoutubeLoader` tends to work on your laptop and fail once the app is deployed. On Lambda, Cloud Run, Vercel or any other cloud host, YouTube blocks the server's IP, so the loader returns an empty list or reports that the video has no transcript, even when it does. Videos that really have no captions fail the same way, and other sites aren't covered at all.

This page swaps it for Importly. You get tools a LangChain or LangGraph agent can call, and a small loader that returns `Document` objects for your splitters and vector stores. Both call the REST API from your server, work for YouTube, TikTok, X, podcasts and 1,000+ other sites, and fall back to speech-to-text when a video has no captions.

## 1. Store your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once) and add it to your server environment, next to your model provider's key:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
```

The tools and the loader run on your server, so the key never reaches the browser.

## 2. Define the tools and the loader

Each tool starts an Importly job and polls its status until it finishes. A transcript of a video with captions usually comes back within the first request, because `wait` holds it open for up to 30 seconds. The only packages you need are LangChain itself and `zod` (TypeScript) or `httpx` (Python).

```ts src/importly.ts theme={null}
import { tool } from 'langchain'
import { Document } from '@langchain/core/documents'
import { z } from 'zod'

const API = 'https://api.importly.io'

type Job = {
  jobId: string
  status: string
  code?: string
  message?: string
  result?: { text?: string, title?: string, mediaUrl?: string, [key: string]: unknown }
}

const call = async (method: 'GET' | 'POST', path: string, body?: object): Promise<Job> => {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: body ? JSON.stringify(body) : undefined,
  })
  const json = await res.json()
  if (!json.success) throw new Error(`${json.code}: ${json.error}`)
  return json.data
}

// Start a job, then poll until it finishes (or return the jobId after about 2 minutes)
const runJob = async (path: string, body: object): Promise<Job> => {
  let job = await call('POST', path, body)
  for (let i = 0; i < 40 && job.status !== 'completed' && job.status !== 'failed'; i++) {
    await new Promise((resolve) => setTimeout(resolve, 3000))
    job = await call('GET', `${path}/status?id=${job.jobId}`)
  }
  return job
}

export const transcribeMedia = tool(
  async ({ url, language }) =>
    JSON.stringify(await runJob('/transcribe', { url, language, mode: 'auto', wait: 30, maxCostDollars: 0.5 })),
  {
    name: 'transcribe_media',
    description:
      'Transcribe a video or audio link (YouTube, TikTok, X, Instagram, podcasts and 1,000+ other sites). ' +
      'Returns the text and timestamped segments.',
    schema: z.object({
      url: z.string().describe('Public page URL of the video or audio'),
      language: z.string().optional().describe('Language hint, e.g. "en"'),
    }),
  },
)

export const importMedia = tool(
  async ({ url, audioOnly }) =>
    JSON.stringify(await runJob('/import', { url, includeVideo: !audioOnly, videoQuality: '720p', maxCostDollars: 1 })),
  {
    name: 'import_media',
    description: 'Download the video or audio behind a link and return a download URL for the file, with its title.',
    schema: z.object({
      url: z.string().describe('Public page URL of the video or audio'),
      audioOnly: z.boolean().optional().describe('Download only the audio'),
    }),
  },
)

export const getMediaDetails = tool(
  async ({ url }) => JSON.stringify(await runJob('/metadata/basic', { url })),
  {
    name: 'get_media_details',
    description: 'Get the title, duration and thumbnail of a video or audio link.',
    schema: z.object({
      url: z.string().describe('Public page URL of the video or audio'),
    }),
  },
)

// Drop-in for YoutubeLoader: one Document per link, for splitters, vector stores and RAG chains
export const loadTranscript = async (url: string): Promise<Document> => {
  const job = await runJob('/transcribe', { url, mode: 'auto', wait: 30, maxCostDollars: 0.5 })
  if (job.status !== 'completed') throw new Error(`${job.code ?? job.status}: ${job.message ?? 'transcript not ready'}`)
  return new Document({
    pageContent: job.result?.text ?? '',
    metadata: { source: url, jobId: job.jobId },
  })
}
```

```python importly_tools.py theme={null}
import json
import os
import time
from typing import Iterator, Optional

import httpx
from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
from langchain_core.tools import tool

importly = httpx.Client(
    base_url="https://api.importly.io",
    headers={"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"},
    timeout=70,  # longer than the 30s wait below
)


def call(method: str, path: str, body: Optional[dict] = None) -> dict:
    res = importly.request(method, path, json=body)
    data = res.json()
    if not data.get("success"):
        raise RuntimeError(f"{data.get('code')}: {data.get('error')}")
    return data["data"]


def run_job(path: str, body: dict) -> dict:
    """Start a job, then poll until it finishes (or return the jobId after about 2 minutes)."""
    job = call("POST", path, body)
    for _ in range(40):
        if job["status"] in ("completed", "failed"):
            break
        time.sleep(3)
        job = call("GET", f"{path}/status?id={job['jobId']}")
    return job


@tool
def transcribe_media(url: str, language: Optional[str] = None) -> str:
    """Transcribe a video or audio link (YouTube, TikTok, X, Instagram, podcasts and 1,000+ other sites).
    Returns the text and timestamped segments."""
    job = run_job("/transcribe", {"url": url, "language": language, "mode": "auto", "wait": 30, "maxCostDollars": 0.5})
    return json.dumps(job)


@tool
def import_media(url: str, audio_only: bool = False) -> str:
    """Download the video or audio behind a link and return a download URL for the file, with its title."""
    job = run_job("/import", {"url": url, "includeVideo": not audio_only, "videoQuality": "720p", "maxCostDollars": 1})
    return json.dumps(job)


@tool
def get_media_details(url: str) -> str:
    """Get the title, duration and thumbnail of a video or audio link."""
    return json.dumps(run_job("/metadata/basic", {"url": url}))


class ImportlyTranscriptLoader(BaseLoader):
    """Drop-in for YoutubeLoader: one Document per link."""

    def __init__(self, urls: list[str]):
        self.urls = urls

    def lazy_load(self) -> Iterator[Document]:
        for url in self.urls:
            job = run_job("/transcribe", {"url": url, "mode": "auto", "wait": 30, "maxCostDollars": 0.5})
            if job["status"] != "completed":
                raise RuntimeError(f"{job.get('code') or job['status']}: {job.get('message')}")
            yield Document(
                page_content=job["result"]["text"],
                metadata={"source": url, "jobId": job["jobId"]},
            )
```

`maxCostDollars` caps what one call can spend. If a job would cost more, it fails with [`MAX_COST_EXCEEDED`](/docs/errors/max-cost-exceeded) and the price instead of running. Raise the caps to suit your app. `mode: 'auto'` uses the video's captions when it has them and speech-to-text when it doesn't.

## 3. Give the tools to an agent

`createAgent` (TypeScript) and `create_agent` (Python) build a LangGraph agent, so the same tools work in a custom LangGraph graph through a `ToolNode` too.

```ts src/agent.ts theme={null}
import { createAgent } from 'langchain'
import { transcribeMedia, importMedia, getMediaDetails } from './importly'

export const mediaAgent = createAgent({
  model: 'openai:gpt-5-mini',
  tools: [transcribeMedia, importMedia, getMediaDetails],
  systemPrompt:
    'When the user sends a video or audio link, use transcribe_media to read it. ' +
    'Use import_media only when they ask for the file, and get_media_details for title or length questions.',
})

export const summarize = async (url: string) => {
  const result = await mediaAgent.invoke({
    messages: [{ role: 'user', content: `Transcribe ${url} and summarize it in five bullet points.` }],
  })
  return result.messages.at(-1)?.content
}
```

```python agent.py theme={null}
from langchain.agents import create_agent

from importly_tools import get_media_details, import_media, transcribe_media

agent = create_agent(
    model="openai:gpt-5-mini",
    tools=[transcribe_media, import_media, get_media_details],
    system_prompt=(
        "When the user sends a video or audio link, use transcribe_media to read it. "
        "Use import_media only when they ask for the file, and get_media_details for title or length questions."
    ),
)


def summarize(url: str) -> str:
    result = agent.invoke(
        {"messages": [{"role": "user", "content": f"Transcribe {url} and summarize it in five bullet points."}]}
    )
    return result["messages"][-1].content
```

The agent calls `transcribe_media`, reads the transcript, and answers in its next step. Swap in any chat model LangChain supports.

## 4. Load transcripts as Documents

Where you used `YoutubeLoader` to feed a RAG pipeline, load the transcript as a `Document` and split it as before:

```ts src/rag.ts theme={null}
import { RecursiveCharacterTextSplitter } from '@langchain/textsplitters'
import { loadTranscript } from './importly'

export const chunks = async (url: string) => {
  const doc = await loadTranscript(url)
  const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000, chunkOverlap: 100 })
  return splitter.splitDocuments([doc])
}
```

```python rag.py theme={null}
from langchain_text_splitters import RecursiveCharacterTextSplitter

from importly_tools import ImportlyTranscriptLoader

docs = ImportlyTranscriptLoader(["https://www.youtube.com/watch?v=jNQXAC9IVRw"]).load()
chunks = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100).split_documents(docs)
```

The loader raises when a transcript can't be made, for example because the video is private, so a failed link never turns into an empty document in your index. If you need timestamps for citations, read `result.data.segments` from the same job: each segment has its start and end time.

These examples typecheck against `langchain` 1.6 and `@langchain/core` 1.5 (TypeScript), and run on `langchain` 1.5 with `langchain-core` 1.8 (Python).

## What each tool returns

The tools hand the job back to the agent as JSON:

| Tool | Endpoint | `result` when `status` is `completed` |
| - | - | - |
| `transcribe_media` | [`POST /transcribe`](/docs/endpoints/transcribe) | `text`, `language`, `source` (captions or speech-to-text) and `data.segments` with start and end times |
| `import_media` | [`POST /import`](/docs/endpoints/import) | `mediaUrl` (a download link for the file) and `title` |
| `get_media_details` | [`POST /metadata/basic`](/docs/endpoints/basic-metadata) | `title`, `duration`, `thumbnail` |

A job that can't finish comes back with `status: 'failed'` and a `code` the agent can explain to the user ([error codes](/docs/error-handling.md)). A long download may still be `running` when the tool stops polling. For files, a [webhook](/docs/webhooks.md) is the better fit in production: start the import from your backend, store the `jobId`, and save `mediaUrl` when the webhook arrives. The [Next.js guide](/docs/integrations/nextjs.md) shows that flow, and the [Python guide](/docs/integrations/python.md) shows it in FastAPI.

## Costs

Each tool call is billed like the same API request: a caption transcript is $0.003, speech-to-text $0.01 a minute, and downloads are priced by size. See [Billing](/docs/billing.md). Importly is free to try, no card required.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.