> ## 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 OpenAI Agents SDK

> Give an agent built with the OpenAI Agents SDK tools that transcribe, download and describe any video or audio link: three tool() definitions over the REST API and a run() call.

If your app runs an agent built with the [OpenAI Agents SDK](https://openai.github.io/openai-agents-js/) and users send it video or podcast links, the agent needs a way to read them. 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 agent 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 the TypeScript SDK and plain `tool()` definitions, so the only packages you need are `@openai/agents` 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 OpenAI key:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
OPENAI_API_KEY=your_openai_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 '@openai/agents'
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({
  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.',
  parameters: z.object({
    url: z.string().describe('Public page URL of the video or audio'),
    language: z.string().nullable().describe('Language hint, e.g. "en", or null to detect it'),
  }),
  execute: async ({ url, language }) =>
    runJob('/transcribe', { url, language: language ?? undefined, mode: 'auto', wait: 30, maxCostDollars: 0.5 }),
})

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

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

The SDK runs tools in strict mode, where the model has to send every field. That's why `language` is `nullable()` rather than `optional()`: the model sends `null` when it has no hint.

`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

A backend function that summarizes the video behind a link:

```ts lib/summarize.ts theme={null}
import { Agent, run } from '@openai/agents'
import { transcribeMedia, importMedia, getMediaDetails } from './importly-tools'

const mediaAgent = new Agent({
  name: 'Media agent',
  instructions:
    '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.',
  model: 'gpt-5-mini',
  tools: [transcribeMedia, importMedia, getMediaDetails],
})

export const summarize = async (url: string) => {
  const result = await run(mediaAgent, `Transcribe ${url} and summarize it in five bullet points.`, {
    maxTurns: 4,
  })
  return result.finalOutput
}
```

The agent calls `transcribe_media`, reads `result.text`, and answers on its next turn. `maxTurns` caps how many model calls one run can make. The same agent works with `run(agent, input, { stream: true })` for a chat UI. These examples typecheck against `@openai/agents` 0.22.

## What each tool returns

The tools hand the job object back to the agent:

| 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, for example because the video is private, 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.

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