> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 图像和视频快速入门

图像和视频 API 是异步的。提交生成任务后，完成时可通过签名 URL 下载结果。图像和视频使用不同的端点，但请求和响应结构相同。

有两种方式获取结果。推荐使用[Webhook 推送](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)，下方示例也采用此方式：生成任务进入终止状态后，ElevenLabs 会立即调用你的端点，无需等待。没有可接收回调的端点时，可使用轮询作为备选方案；每个示例都会说明如何切换为轮询。

> **Warning**
>
> 图像和视频 API 需要 Pro 或更高版本套餐。低于此级别的工作区调用会被拒绝，并返回
> `402 paid_plan_required` 错误。API 密钥还必须具有该工作区的图像和视频或
> Flows 权限。

## 生成图像

#### 创建 API 密钥

[在控制台中创建 API 密钥](https://elevenlabs.io/app/api/api-keys)，用于安全地[访问 API](/docs/zh/api-reference/authentication)。

将密钥作为受管理的机密信息存储，并根据偏好，通过 `.env` 文件将其作为环境变量传递给 SDK，或直接写入应用配置。

**`.env`**

```js title=".env"
ELEVENLABS_API_KEY=<your_api_key_here>
```

#### 安装 SDK

#### SDK

我们还会使用 `dotenv` 库从环境变量加载 API 密钥。

```python
pip install elevenlabs
pip install python-dotenv
```

```typescript
npm install @elevenlabs/elevenlabs-js
npm install dotenv
```

#### CLI

安装 ElevenLabs CLI。推荐使用 Homebrew（macOS）和 Scoop（Windows）。

**`Homebrew（macOS）`**

```bash title="Homebrew（macOS）"
brew install elevenlabs/tap/elevenlabs
```

**`Scoop（Windows）`**

```powershell title="Scoop（Windows）"
scoop bucket add elevenlabs https://github.com/elevenlabs/scoop-bucket
scoop install elevenlabs
```

**`npm`**

```bash title="npm"
npm install -g @elevenlabs/cli
```

**`curl`**

```bash title="curl"
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/elevenlabs/cli/releases/latest/download/elevenlabs-cli-installer.sh | sh
```

> **Tip**
>
> 正在使用 AI 编程助手？在项目中运行 `elevenlabs generate-skills`，即可将每个命令组的
> `SKILL.md` 写入 `skills/`，无需粘贴文档，助手就能了解 CLI 的完整功能。使用 `--output-dir`
> 可将其放到其他位置。该命令会读取 CLI 内置的 API 定义，因此无需 API 密钥且可离线运行——还能始终与已安装的 CLI 版本保持同步。

然后进行身份验证——这会打开浏览器以授权 CLI：

```bash
elevenlabs auth login
```

#### 提交生成任务

每个模型都有自己的请求类，其中的字段就是该模型接受的参数。因此，切换模型时可用字段可能会变化。未知字段会被拒绝，而不会被忽略。

`webhook` 会要求将完成的结果推送到工作区的 Webhook，因此任务一进入队列，调用便会返回。它需要订阅生成事件的 Webhook；请参阅[图像和视频 Webhook](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)了解如何设置，或者省略该字段并改用轮询。

#### SDK

```python
# example.py
import os

from dotenv import load_dotenv
from elevenlabs import ImageGenerationRequest_Gemini3ProImage, WebhookTarget_All
from elevenlabs.client import ElevenLabs

load_dotenv()

elevenlabs = ElevenLabs(api_key=os.getenv("ELEVENLABS_API_KEY"))

generation = elevenlabs.flows.image.create(
    request=ImageGenerationRequest_Gemini3ProImage(
        prompt="A corgi in a tiny lifeguard chair on a sunlit beach at golden hour, photorealistic",
        aspect_ratio="16:9",
        resolution="2K",
        webhook=WebhookTarget_All(),
    )
)

print(generation.id, generation.status)
```

```typescript
// example.mts
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import "dotenv/config";

const elevenlabs = new ElevenLabsClient();

const generation = await elevenlabs.flows.image.create({
  modelId: "gemini-3-pro-image",
  prompt:
    "A corgi in a tiny lifeguard chair on a sunlit beach at golden hour, photorealistic",
  aspectRatio: "16:9",
  resolution: "2K",
  webhook: { type: "all" },
});

console.log(generation.id, generation.status);
```

#### CLI

CLI 会以 JSON 提交相同请求，然后轮询直到生成完成并下载结果：

```bash
# 1. Submit the generation (note the returned id)
elevenlabs flows image create --json '{
  "model_id": "gemini-3-pro-image",
  "prompt": "A corgi in a tiny lifeguard chair on a sunlit beach at golden hour, photorealistic",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}'

# 2. Poll until the status is "completed"
elevenlabs flows image get --generation-id <id> --query status

# 3. Read the signed content URL, then download the image
elevenlabs flows image get --generation-id <id> --query content_url
curl -o corgi.png "<content_url>"
```

响应仅包含生成 ID。新创建的生成任务始终为 `pending`：

```json
{
  "id": "JWr5N6X9ZTqf8jD2LmQb",
  "status": "pending"
}
```

#### 获取结果

由于请求启用了 `webhook`，生成任务进入 `completed` 或 `failed` 状态后，ElevenLabs 会向你的端点发送 `flows_generation` 事件。事件的 `data` 与 GET 端点返回的内容相同，[图像和视频 Webhook](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)介绍了接收此事件的处理程序。

如果没有可接收回调的端点，请从上述请求中移除 `webhook`，然后改用轮询。持续获取生成任务，直到其状态为 `completed` 或 `failed`。图像请求之间至少间隔 2 秒——请参阅[轮询指南](#polling-guidelines)了解各类媒体的轮询间隔。

```python maxLines=0
import time

import requests

while True:
    result = elevenlabs.flows.image.get(generation.id)
    if result.status in ("completed", "failed"):
        break
    time.sleep(2)

if result.status == "failed":
    raise RuntimeError(f"{result.failure_reason}: {result.error_message}")

with open("corgi.png", "wb") as f:
    f.write(requests.get(result.content_url).content)
```

```typescript maxLines=0
import { writeFile } from "fs/promises";

let result = await elevenlabs.flows.image.get(generation.id);

while (result.status === "pending" || result.status === "generating") {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  result = await elevenlabs.flows.image.get(generation.id);
}

if (result.status === "failed") {
  throw new Error(`${result.failureReason}: ${result.errorMessage}`);
}

const response = await fetch(result.contentUrl);
await writeFile("corgi.png", Buffer.from(await response.arrayBuffer()));
```

无论使用哪种方式，已完成的生成任务都包含相同字段：

```json
{
  "id": "JWr5N6X9ZTqf8jD2LmQb",
  "status": "completed",
  "content_url": "https://storage.googleapis.com/generations/JWr5N6X9ZTqf8jD2LmQb",
  "content_mime_type": "image/png"
}
```

#### 执行代码

```python
python example.py
```

```typescript
npx tsx example.mts
```

生成任务会进入队列，并打印其 ID。使用 Webhook 推送时，图像会发送到你的端点；使用轮询时，图像会保存为 `corgi.png`。

## 生成视频

视频生成使用 `flows.video`，并遵循相同的提交和获取流程。视频可能需要数分钟，因此此示例通过 `webhook` 启用 Webhook 推送，而非等待结果。

```python
from elevenlabs import VideoGenerationRequest_Veo31FastGenerate001, WebhookTarget_All

generation = elevenlabs.flows.video.create(
    request=VideoGenerationRequest_Veo31FastGenerate001(
        prompt="A corgi rides a tiny surfboard across a sunlit wave at golden hour, cinematic",
        duration_secs=8,
        aspect_ratio="16:9",
        resolution="1080p",
        generate_audio=True,
        webhook=WebhookTarget_All(),
    )
)

print(generation.id)
```

```typescript
const generation = await elevenlabs.flows.video.create({
  modelId: "veo-3.1-fast-generate-001",
  prompt: "A corgi rides a tiny surfboard across a sunlit wave at golden hour, cinematic",
  durationSecs: 8,
  aspectRatio: "16:9",
  resolution: "1080p",
  generateAudio: true,
  webhook: { type: "all" },
});

console.log(generation.id);
```

生成任务进入队列后，调用便会返回；完成的结果会推送到工作区中订阅了生成事件的每个 Webhook。视频输出为 MP4，因此完成后的载荷中 `content_mime_type` 为 `video/mp4`。请参阅[图像和视频 Webhook](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)，了解如何配置 Webhook 并编写接收此结果的处理程序。

> **Warning**
>
> `webhook` 至少需要一个订阅生成事件的工作区 Webhook。否则，创建调用会被拒绝，而不会启动一个无处发送结果的生成任务。移除该字段即可改用 `flows.video.get` 轮询，轮询间隔不得少于 10 秒。

## 获取结果

Webhook 和轮询返回相同的载荷，因此区别在于等待方式，而非获取的内容。

|      | Webhook 推送           | 轮询                 |
| ---- | -------------------- | ------------------ |
| 最适合  | 两类媒体的默认方式，以及所有生产环境用途 | 没有公开端点的脚本和环境       |
| 需要   | 订阅生成事件的 HTTPS 端点     | 无                  |
| 等待成本 | 无；生成完成后会调用你的端点       | 每个生成任务每次轮询发起 1 个请求 |

尽可能使用 Webhook。仅在没有可接收回调的位置时使用轮询，并遵循以下间隔。

### 选择 Webhook 目标

`webhook` 支持两种形式。`WebhookTarget_All` 会发送到订阅生成事件的所有 Webhook，这是正确的默认选择，因为即使 Webhook 轮换或替换，仍可正常工作。`WebhookTarget_Ids` 会将推送范围限定为特定 Webhook，适用于一个工作区服务多个消费者，而某个任务只应发送给其中一个的情况：

```python
from elevenlabs import WebhookTarget_Ids

webhook = WebhookTarget_Ids(ids=["Q8mVr2LpXcT4nB6yJdKw"])
```

```typescript
const webhook = { type: "ids", ids: ["Q8mVr2LpXcT4nB6yJdKw"] };
```

每个 ID 都必须已订阅生成事件；指定未订阅的 Webhook 会被拒绝，而不会被静默忽略。推送的载荷与 GET 端点返回的内容相同，因此针对其中一种编写的处理程序可用于另一种。[Webhook 指南](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)介绍了如何配置 Webhook、验证签名和处理事件。

### 轮询指南

生成任务的耗时取决于模型、分辨率，以及视频时长。因此，应根据请求内容匹配轮询间隔，而非固定循环：

* **图像**：轮询间隔不得少于 2 秒。大多数会在数秒内完成。
* **视频**：轮询间隔不得少于 10 秒。预计耗时为数分钟而非数秒，并应根据 `duration_secs` 和 `resolution` 调整间隔。

两者均适用以下两条规则。生成任务长时间运行时应退避——将间隔逐步加倍至约 1 分钟，可避免缓慢任务产生数百个请求。同时，为循环设置上限，让卡住的生成任务在你的代码中以超时结束，而不是无限循环。

更频繁的轮询没有任何收益：不会因为请求两次，生成任务的状态就更早变化。持续激进轮询可能返回[429 响应](/docs/zh/eleven-api/resources/errors#rate-limiting-and-concurrency)，应使用指数退避处理。

## 生成生命周期

生成任务会经历 4 种状态。两种终止状态包含不同字段，因此读取响应其余内容前，请先根据 `status` 分支处理。

| 状态           | 含义                                              |
| ------------ | ----------------------------------------------- |
| `pending`    | 生成任务已进入队列。所有新创建的生成任务均为此状态。                      |
| `generating` | 模型正在运行。                                         |
| `completed`  | 输出已就绪。响应包含 `content_url` 和 `content_mime_type`。 |
| `failed`     | 生成任务未产生输出。响应包含失败详情。                             |

> **Warning**
>
> `content_url` 是签名 URL，会在返回响应约 1 小时后过期。需要新 URL 时，请重新获取生成任务，而非存储签名 URL 本身。

## 处理失败

失败的生成任务会报告 `failure_reason` 类别，以及便于阅读的 `error_message`：

```json
{
  "id": "JWr5N6X9ZTqf8jD2LmQb",
  "status": "failed",
  "failure_reason": "moderated",
  "error_message": "The prompt was rejected by content moderation. You were not charged for this generation."
}
```

| `failure_reason`     | 原因               |
| -------------------- | ---------------- |
| `timeout`            | 模型未能及时返回结果。      |
| `model_error`        | 模型提供商返回错误或未产生输出。 |
| `moderated`          | 提示词或输入内容被内容审核拒绝。 |
| `invalid_parameters` | 生成任务到达模型后，参数被拒绝。 |
| `dependency_failed`  | 此任务依赖的引用生成任务失败。  |
| `charging_failed`    | 工作区无法为该生成任务扣费。   |
| `internal_error`     | 发生意外错误。          |

失败的生成任务不会收费。可预先检测的参数问题——不支持的字段、超出模型允许范围的值，或无效的参考输入组合——会在创建请求时被拒绝，不会启动任何生成任务。

## 定价

生成任务按积分收费。费用取决于模型、所选参数（如分辨率和时长）以及提供的输入内容。通过 API 创建生成任务的费用与 ElevenLabs 应用中相同，提交前会显示费用。请参阅[Playground 中的图像和视频](/docs/zh/eleven-creative/playground/image-video)，了解如何显示特定模型和设置组合的费用。

## 列出生成任务

每个端点都会列出通过其创建的生成任务，按最新优先排序。结果仅限当前工作区和此 API，因此在 ElevenLabs 应用中创建的生成任务不会显示。

```python
page = elevenlabs.flows.image.list(page_size=20, status="completed")

for item in page.generations:
    print(item.id, item.content_url)

while page.has_more:
    page = elevenlabs.flows.image.list(page_size=20, status="completed", cursor=page.next_cursor)
    for item in page.generations:
        print(item.id, item.content_url)
```

```typescript
let page = await elevenlabs.flows.image.list({ pageSize: 20, status: "completed" });

for (const item of page.generations) {
  console.log(item.id, item.contentUrl);
}

while (page.hasMore) {
  page = await elevenlabs.flows.image.list({
    pageSize: 20,
    status: "completed",
    cursor: page.nextCursor,
  });
  for (const item of page.generations) {
    console.log(item.id, item.contentUrl);
  }
}
```

`page_size` 接受 1 至 100，默认为 30。传入 `status` 可仅返回某个生命周期状态的生成任务，传入 `model_id` 可仅返回某个模型的生成任务。将 `next_cursor` 视为不透明值：原样传回，并在 `has_more` 为 `false` 时停止。

## 可用模型

API 提供 ElevenLabs 应用中部分可用模型。每个模型只接受为其列出的参数——发送其他模型支持的字段会返回验证错误。

> **Warning**
>
> ByteDance 模型默认禁用，使用前需要明确批准。在获得访问权限前，指定其中任一模型的请求都会被拒绝，并返回 `model_access_denied` 错误。企业版客户可联系支持团队申请访问权限。

### 图像模型

| `model_id`                    | 参考图像              | 输出控制                                                      |
| ----------------------------- | ----------------- | --------------------------------------------------------- |
| `gpt-image-1`                 | 最多 5 张，另加 `mask`  | `aspect_ratio`（1:1、3:2、2:3）、`quality`、`background`        |
| `gpt-image-1.5`               | 最多 5 张，另加 `mask`  | `aspect_ratio`（1:1、3:2、2:3）、`quality`、`background`        |
| `gpt-image-2`                 | 最多 10 张，另加 `mask` | 15 种宽高比、`resolution`（1K、2K、4K）、`quality`                  |
| `gpt-image-2.5-sunburst`      | 最多 10 张，另加 `mask` | 15 种宽高比、`resolution`（1K、2K、4K）、`quality`（最高为 `max`）       |
| `gpt-image-2.5-flare`         | 最多 10 张，另加 `mask` | 15 种宽高比、`resolution`（1K、2K、4K）、`quality`（最高为 `max`）       |
| `gemini-2.5-flash-image`      | 最多 5 张            | `aspect_ratio`                                            |
| `gemini-3-pro-image`          | 最多 10 张           | `aspect_ratio`、`resolution`（1K、2K、4K）                     |
| `gemini-3.1-flash-image`      | 最多 14 张           | `aspect_ratio`（包括 1:4、4:1、1:8、8:1）、`resolution`（512 至 4K） |
| `gemini-3.1-flash-lite-image` | 最多 14 张           | `aspect_ratio`、`resolution`（1K）                           |
| `bytedance-seedream-5-lite`   | 最多 10 张           | `aspect_ratio`、`resolution`（2K、3K）、`seed`                 |
| `bytedance-seedream-5-pro`    | 最多 10 张           | `aspect_ratio`、`resolution`（1K、2K）、`seed`                 |

GPT Image 2.5 模型接受 `low`、`medium`、`high`、`xhigh` 和 `max` 作为 `quality` 值，默认值为 `high`。GPT Image 2 最高仅支持 `high`，默认值为 `medium`。

### 视频模型

| `model_id`                   | 媒体输入                                                                   | 输出控制                                                                                          |
| ---------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `veo-3.1-generate-001`       | `start_frame`、`end_frame`、最多 3 个带 `role` 的 `images`                    | `duration_secs`（4、6、8）、`aspect_ratio`（16:9、9:16）、`resolution`（720p、1080p、4K）、`generate_audio` |
| `veo-3.1-fast-generate-001`  | `start_frame`、`end_frame`、最多 3 个带 `role` 的 `images`                    | `duration_secs`（4、6、8）、`aspect_ratio`（16:9、9:16）、`resolution`（720p、1080p、4K）、`generate_audio` |
| `bytedance-seedance-v2`      | `start_frame`、`end_frame`、最多 9 个 `images`、3 个 `videos`、3 个 `audios`    | `duration_secs`（4 至 15）、7 种宽高比、`resolution`（480p 至 4k）、`generate_audio`                       |
| `bytedance-seedance-v2-fast` | `start_frame`、`end_frame`、最多 9 个 `images`、3 个 `videos`、3 个 `audios`    | `duration_secs`（4 至 15）、7 种宽高比、`resolution`（480p、720p）、`generate_audio`                       |
| `bytedance-seedance-v2-mini` | `start_frame`、`end_frame`、最多 9 个 `images`、3 个 `videos`、3 个 `audios`    | `duration_secs`（4 至 15）、7 种宽高比、`resolution`（480p、720p）、`generate_audio`                       |
| `bytedance-seedance-v2.5`    | `start_frame`、`end_frame`、最多 30 个 `images`、10 个 `videos`、10 个 `audios` | `duration_secs`（4 至 30）、7 种宽高比、`resolution`（480p、720p）、`generate_audio`                       |
| `creatify-aurora`            | `image` 和 `audio`，两者均必填                                                | `resolution`（480p、720p）、`guidance_scale`、`audio_guidance_scale`                               |

有关模型能力、可用性和定价，请参阅[图像和视频概览](/docs/zh/overview/capabilities/image-video)。

## 后续步骤

#### [参考内容和资产](/docs/zh/eleven-api/guides/how-to/image-and-video/references)

使用先前生成任务、已上传资产或内联媒体引导生成。

#### [Webhook](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)

接收生成结果，无需轮询。

#### [API 参考文档](/docs/zh/api-reference/flows/image/create)

浏览图像、视频和资产端点。