> ## 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 LlamaIndex

> Replace YoutubeTranscriptReader in a deployed LlamaIndex app: a reader that returns Documents and agent tools that transcribe, download and describe any video or audio link.

`YoutubeTranscriptReader` 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 reader raises a blocked-request error, or says 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 a reader that returns `Document` objects for your node parsers and indexes, and tools a LlamaIndex agent can call. 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 reader and the tools run on your server, so the key never reaches the browser.

## 2. Define the reader and the tools

Each call 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. Besides `llama-index-core`, the only package you need is `httpx`.

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

import httpx
from llama_index.core import Document
from llama_index.core.readers.base import BaseReader
from llama_index.core.tools import FunctionTool

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


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)


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)


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}))


importly_tools = [
    FunctionTool.from_defaults(fn=transcribe_media),
    FunctionTool.from_defaults(fn=import_media),
    FunctionTool.from_defaults(fn=get_media_details),
]


class ImportlyTranscriptReader(BaseReader):
    """Drop-in for YoutubeTranscriptReader: one Document per link."""

    def lazy_load_data(self, ytlinks: list[str], **kwargs) -> Iterable[Document]:
        for url in ytlinks:
            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(
                text=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. Load transcripts as Documents

`ImportlyTranscriptReader().load_data(ytlinks=[...])` takes the same argument as `YoutubeTranscriptReader`, so swapping it in is a one-line change. Parse and index the documents as before:

```python rag.py theme={null}
from llama_index.core import VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter

from importly_tools import ImportlyTranscriptReader

docs = ImportlyTranscriptReader().load_data(ytlinks=["https://www.youtube.com/watch?v=jNQXAC9IVRw"])
nodes = SentenceSplitter(chunk_size=1024, chunk_overlap=100).get_nodes_from_documents(docs)
index = VectorStoreIndex(nodes)
```

`VectorStoreIndex` uses the embedding model in your `Settings`, as it did before. The reader 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.

## 4. Give the tools to an agent

`FunctionAgent` takes the three tools as they are. The tool names and descriptions come from the functions' names and docstrings.

```python agent.py theme={null}
import asyncio

from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI

from importly_tools import importly_tools

agent = FunctionAgent(
    tools=importly_tools,
    llm=OpenAI(model="gpt-5-mini"),
    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."
    ),
)


async def summarize(url: str) -> str:
    response = await agent.run(user_msg=f"Transcribe {url} and summarize it in five bullet points.")
    return str(response)


if __name__ == "__main__":
    print(asyncio.run(summarize("https://www.youtube.com/watch?v=jNQXAC9IVRw")))
```

The agent calls `transcribe_media`, reads the transcript, and answers in its next step. Swap in any LLM LlamaIndex supports that can call tools.

These examples run on `llama-index-core` 0.14 with `llama-index-llms-openai` 0.9.

## 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 [Python guide](/docs/integrations/python.md) shows that flow in FastAPI. Using LangChain instead? See the [LangChain guide](/docs/integrations/langchain.md).

## 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.