> ## 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 the Vercel AI SDK

> Give the model in your AI SDK app tools that transcribe, download and describe any video or audio link: three tool() definitions over the REST API and a Next.js route handler.

If your app built on the [AI SDK](https://ai-sdk.dev) lets users paste a video or podcast link, the model needs a way to read it. Fetching the media yourself tends to break once the app is deployed: sites block the datacenter IPs your server runs on, and many videos have no captions. Give the model Importly tools instead. They call the REST API from your server and return the transcript, a download link for the file, or the video's details.

This page uses plain `tool()` definitions, so the only packages you need are `ai` and `zod`.

## 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.local theme={null}
IMPORTLY_API_KEY=your_api_key
```

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

## 2. Define the tools

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.

```ts lib/importly-tools.ts theme={null}
import { tool } from 'ai'
import { z } from 'zod'

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

type Job = { jobId: string, status: string, result?: Record<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({
  description:
    'Transcribe a video or audio link (YouTube, TikTok, X, Instagram, podcasts and 1,000+ other sites). ' +
    'Returns the text and timestamped segments.',
  inputSchema: z.object({
    url: z.string().describe('Public page URL of the video or audio'),
    language: z.string().optional().describe('Language hint, e.g. "en"'),
  }),
  execute: async ({ url, language }) =>
    runJob('/transcribe', { url, language, mode: 'auto', wait: 30, maxCostDollars: 0.5 }),
})

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

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

`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. Call the model with the tools

A Next.js route handler that summarizes the video behind a link:

```ts app/api/summarize/route.ts theme={null}
import { generateText, stepCountIs } from 'ai'
import { transcribeMedia, importMedia, getMediaDetails } from '@/lib/importly-tools'

export const maxDuration = 120

export const POST = async (req: Request) => {
  const { url } = await req.json()

  const { text } = await generateText({
    model: 'openai/gpt-5-mini',
    tools: { transcribeMedia, importMedia, getMediaDetails },
    stopWhen: stepCountIs(3),
    prompt: `Transcribe ${url} and summarize it in five bullet points.`,
  })

  return Response.json({ summary: text })
}
```

The model calls `transcribeMedia`, reads `result.text`, and answers in the next step. `stopWhen` lets it take more than one step, which it needs to use a tool result. Swap in any model your AI SDK setup supports. The same `tools` object works with `streamText` for a chat UI. `stepCountIs` works in AI SDK 5, 6 and 7 (7 also calls it `isStepCount`).

## What each tool returns

The tools hand the job object back to the model:

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

A job that can't finish, for example because the video is private, comes back with `status: 'failed'` and a `code` the model 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 route, store the `jobId`, and save `mediaUrl` when the webhook arrives. The [Next.js guide](/docs/integrations/nextjs.md) shows that flow.

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