> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Kling V4

POST https://api.beatapi.io/v1/videos/tasks
Content-Type: application/json

根据文本、按时间顺序排列的画面帧，或参考图、参考视频、参考声音和命名元素，生成 720p 或 1080p、时长 3–30 秒、自带生成音频的视频；按秒计费。- 异步：创建请求返回任务 ID，任务成功后才能拿到视频。
- 四种输入方式：纯文本、画面帧（按时间顺序排列的 `images`）、参考图 / 参考视频 / 参考声音，以及最多七个命名的 `elements`。画面帧不能与参考素材或元素一起使用。
- 在提示词里为每个输入写上引用：`@image_1`、`@video_1`、`@voice_1`、`@` 加元素名、`@first_frame`、`@keyframe_1` 和 `@last_frame`。每个 `@` 都必须对应同一请求中的输入。
- 视频始终带有生成的音频。`keep_original_sound` 改为保留参考视频自身的声音。
- `duration` 为 3 到 30 秒（默认 5），分辨率为 `720p`（默认）或 `1080p`。按所选分辨率下的视频秒数计费；失败的任务不收费。POST/v1/videos/tasks试一试在调试窗口里打开本模型，填入你的 BeatAPI API 密钥即可创建任务。调用是真实的，费用从你自己的余额中扣除。## 模型 ID这个端点上有两个 Kling 生成模型。下表数值直接取自网关契约；只有 Kling V4 接受参考素材、两张以上的画面帧和最多七个元素。| 模型 ID          | `duration`（秒） | `resolution`    | 画面帧上限 | 参考图上限 | 元素上限 | 适合的场景                                     |
| -------------- | ------------- | --------------- | ----- | ----- | ---- | ----------------------------------------- |
| **`kling-v4`** | 3–30          | `720p`, `1080p` | 10    | 10    | 7    | 需要最长 30 秒、参考图 / 参考视频 / 参考声音、中间帧，或三个以上的元素。 |
| `kling-v3`     | 3–15          | `std`, `pro`    | 2     | —     | 3    | 需要多镜头分镜、不带声音的视频，或更低的每秒单价。                 |## 接口与鉴权`POST https://api.beatapi.io/v1/videos/tasks`Authorization
string
必需你的 BeatAPI API 密钥，以 `Bearer <BEATAPI_API_KEY>` 形式发送。在[控制台](https://beatapi.io/dashboard)创建密钥。密钥只能保存在你的服务端，不要放进浏览器或移动端应用。请求体使用 JSON，并设置 `Content-Type: application/json`。`Idempotency-Key` 为可选：每个逻辑请求发送一个唯一值（最长 255 个字符），仅在重试完全相同的请求体时复用。24 小时内，用相同的键和请求体重试会再次返回第一次的响应，并带上 `Idempotent-Replayed: true`；相同的键搭配不同的请求体则返回 `409 idempotency_conflict`。非 2xx 的响应不会被保存，因此 400 或 402 之后的重试会重新执行。## 请求流程向接口 `POST` 下方的参数。返回 `201` 表示任务已被接受，其价格已从你的余额中预留；任务在后台运行。保存 `data.id`。调用 `GET /v1/tasks/{task_id}`，两次调用之间等待 `data.poll_after_seconds` 秒（图片 5 秒，视频 8 秒），直到 `status` 为 `succeeded` 或 `failed`。也可以为 `task.succeeded` 和 `task.failed` 注册 [Webhook](/webhooks)；仍需保留轮询作为兜底，因为因处理超时而终止的任务不会发送事件。状态为 `succeeded` 时，下载每个 `data.output.media[].url` 并保存你需要的文件；BeatAPI 不承诺结果链接的保留时长。状态为 `failed` 时，读取 `data.error_code` 和 `data.error_message`：预扣的金额已退回你的余额，`data.retryable` 表示再次发送相同请求是否可能成功。## 输入模式| 模式      | 必填输入                                                                                           | 说明                                             |
| ------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| 文生视频    | `model`、`prompt`                                                                               | 不传任何素材。不传 `aspect_ratio` 时视频为 16:9。            |
| 首帧      | `model`、`prompt`、`images`（1 个链接）                                                               | 视频从这张图开始，并沿用它的画面比例。                            |
| 首帧和尾帧   | `model`、`prompt`、`images`（2 个链接）                                                               | `images[0]` 是首帧，`images[1]` 是尾帧。               |
| 多帧      | `model`、`prompt`、`images`（3 到 10 个链接）                                                          | 按时间顺序依次为首帧、中间帧和尾帧；图片数最多比视频秒数多一张。               |
| 参考素材和元素 | `model`、`prompt`，以及 `reference_images`、`reference_videos`、`reference_audios`、`elements` 中的任意一项 | 在下文限制内可任意组合。不能与 `images` 一起使用。请在提示词里为每个输入写上引用。 |## 请求参数model
string
必需要运行的模型。**取值**：`kling-v4`**取值有误时**- 未传：`"model" is required`
- 把图片模型发到了这个端点：`"model" nano-banana-2 is served by POST /v1/images/tasks, not this endpoint`prompt
string
必需视频里发生什么：主体、动作、运镜、风格和声音，并用 `@` 引用写明每个输入。**长度**：1–5000 个字符- 长度按字符数计算（一个中日韩字符算一个字符）。
- 引用方式：`reference_images` 是 `@image_1`、`@image_2` …，`reference_videos` 是 `@video_1` …，`reference_audios` 是 `@voice_1` …，元素是 `@` 加它的 `name`。画面帧是 `@first_frame`、`@keyframe_1`、`@keyframe_2` … 和 `@last_frame`。
- 每个 `@` 都必须对应同一请求中的输入。编号引用或画面帧引用找不到对应输入时（例如只传了两张参考图却写了 `@image_3`，或只传了一张图却写了 `@last_frame`），创建任务时会被拒绝。**取值有误时**- 未传：`"prompt" is required`
- 为空或超过长度上限：`"prompt" has an unsupported length`
- 引用了请求中没有的输入：`the prompt names @image_3, which this request does not send`images
string[]
可选按时间顺序排列的画面帧：一个链接是首帧，两个是首帧和尾帧，更多则在两者之间加入中间帧。**数量**：1–10  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 有三个或更多链接时，`images[0]` 是首帧，最后一个链接是尾帧，中间的链接是中间帧：`images[1]` 是 `@keyframe_1`，`images[2]` 是 `@keyframe_2`，依此类推。
- 图片数最多比视频秒数多一张（`duration` + 1；不传 `duration` 时按 5 秒算），且无论如何不超过 10 张。
- 画面帧不能与 `reference_images`、`reference_videos`、`reference_audios`、`elements` 或 `aspect_ratio` 一起传：视频沿用首帧的画面比例。**取值有误时**- 多于 10 个链接：`"images" accepts at most 10 items`
- 链接数超过 `duration` + 1（此例为 5 秒视频传了 7 个链接）：`Kling V4 takes at most 6 images for a 5-second video`
- 与任一 reference\_\* 字段同时传入：`Cannot combine "images" with reference inputs in one task`
- 与 `elements` 同时传入：`Kling V4 cannot combine elements with images`
- 与 `aspect_ratio` 同时传入：`Kling V4 takes the first frame's shape; do not send aspect_ratio with images`
- 不是 https\:// 链接：`"images[0]" must be a public HTTPS URL`reference_images
string[]
可选引导视频内容、角色、商品或风格的图片。在提示词里按列表顺序写成 `@image_1`、`@image_2` …。**数量**：1–10  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 不能与 `images` 一起使用。
- 计入参考素材与元素合计 15 个的上限。**取值有误时**- 超过上限：`"reference_images" accepts at most 10 items`
- 参考素材与元素合计超过 15 个：`Kling V4 takes at most 15 reference inputs and elements together`reference_videos
string[]
可选用来借鉴动作、运镜或内容的视频。在提示词里按列表顺序写成 `@video_1`、`@video_2` …。**数量**：1–5  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 每段 2 到 30 秒，所有片段合计不超过 30 秒。网关在创建任务前会逐段测量，超出限制的片段会被拒绝，并在报错中指明是哪一段。
- 参考视频与视频元素合计最多 5 个，并计入参考素材与元素合计 15 个的上限。
- 成片默认带生成的音频；传 `keep_original_sound: true` 则保留参考视频自身的声音。**取值有误时**- 超过上限：`"reference_videos" accepts at most 5 items`
- 某段短于 2 秒或长于 30 秒：`reference_videos[0] is 35 seconds long; this model takes reference video of 2 to 30 seconds.`
- 所有片段合计超过 30 秒：`The reference videos run 36 seconds in total; this model takes at most 30.`
- 参考视频与视频元素合计超过 5 个：`Kling V4 takes at most 5 reference videos and video elements together`reference_audios
string[]
可选视频中使用的声音。在提示词里按列表顺序写成 `@voice_1`、`@voice_2` …。**数量**：1–3  \
每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。- 不能与 `images` 一起使用。
- 计入参考素材与元素合计 15 个的上限。**取值有误时**- 超过上限：`"reference_audios" accepts at most 3 items`elements
object[]
可选最多七个命名的主体，例如角色、动物、道具、服装、场景或特效；每个只需定义一次，在提示词里写成 `@` 加它的 `name`。**数量**：≤ 7- 最多七个对象组成的数组。每个对象只接受以下字段：
- `elements[].name`（字符串，必填）：1 到 20 个字母、数字、下划线或汉字，同一请求内不区分大小写不得重复。不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。
- `elements[].element_input_urls`（字符串数组）：2 到 4 个公网 HTTPS 链接，是这个元素的图片；第一张是主视图。
- `elements[].element_input_video_urls`（字符串数组）：恰好一个公网 HTTPS 链接，是一段 3 到 8 秒、单镜头的角色视频。它与 `element_input_urls` 二选一，不能同时传。
- `elements[].element_input_audio_urls`（字符串数组，可选）：恰好一个公网 HTTPS 音频链接，是角色元素的声音。
- `elements[].tag`（字符串，可选）：元素的类别。视频元素或带声音的元素必须是角色：不传 `tag`，或传 `character`。
- `elements[].description`（字符串，可选）：对元素的描述，最多 100 个字符。
- 视频元素最多 3 个，与 `reference_videos` 合计最多 5 个。每个元素都计入参考素材与元素合计 15 个的上限。
- 元素不能与 `images` 一起传。**取值有误时**- 多于七个元素：`"elements" accepts at most 7 items`
- 某个元素不是对象：`"elements[0]" must be an object`
- 某个元素缺少 `name`：`"name" is required in "elements[0]"`
- `name` 为空或超过 20 个字符：`"elements[0].name" has an unsupported length`
- `name` 含其他字符，或使用了保留名：`elements[0].name "image_1" is not a name Kling V4 accepts`
- 同一个 `name` 出现两次（不区分大小写）：`elements[1].name "Hero" is used twice`
- 同时有图片和视频，或两者都没有：`elements[0] takes either element_input_urls or element_input_video_urls`
- 图片少于两张：`"elements[0].element_input_urls" requires at least 2 item`
- 图片多于四张：`"elements[0].element_input_urls" accepts at most 4 items`
- 视频元素的 `tag` 不是 `character`：`elements[0] is a video element, which is always a character`
- `tag` 不是 `character` 的元素带了声音：`elements[0] has a voice, which only a character element takes`
- `tag` 不在列表中：`"elements[0].tag" must be one of: [character animal prop costume scene effect others]`
- `description` 超过 100 个字符：`"elements[0].description" has an unsupported length`
- 元素里有不接受的字段：`field "start_time" is not supported in "elements[0]"`
- 视频元素多于三个：`Kling V4 takes at most 3 video elements`
- 与 `images` 同时传入：`Kling V4 cannot combine elements with images`duration
integer
可选默认值: 5视频时长，单位为秒，须为整数。计费以它为准。**默认值**：`5`  \
**范围**：3–30- 不传时使用并按 `5` 计费。
- 使用画面帧时，它还决定图片数上限：最多 `duration` + 1 张，且不超过 10 张。**取值有误时**- 超出范围、不是整数，或以字符串传入：`"duration" is outside its supported range`aspect_ratio
string
可选默认值: 16:9视频的宽高比（宽:高）。**可选值**：`16:9`, `9:16`, `1:1`, `21:9`  \
**默认值**：`16:9`- 不传时使用 `16:9`。
- 不要与 `images` 一起传：视频沿用首帧的画面比例。**取值有误时**- 取值不在列表中：`"aspect_ratio" must be one of: [16:9 9:16 1:1 21:9]`
- 与 `images` 同时传入：`Kling V4 takes the first frame's shape; do not send aspect_ratio with images`resolution
string
可选默认值: 720p输出分辨率。`1080p` 的每秒价格高于 `720p`。**可选值**：`720p`, `1080p`  \
**默认值**：`720p`- 不传时使用并按 `720p` 计费。
- 该模型不提供 4K。**取值有误时**- 取值不在列表中（例如 `4K` 或 `pro`）：`"resolution" must be one of: [720p 1080p]`keep_original_sound
boolean
可选在成片中保留参考视频自身的声音，而不是使用生成的音频。- 只能与 `reference_videos` 一起使用；没有参考视频时传入（即使是 `false`）也会被拒绝。
- 不传时视频带有生成的音频。没有关闭音频的字段。**取值有误时**- 不是 true 或 false：`"keep_original_sound" must be a boolean`
- 没有 `reference_videos` 时传入：`"keep_original_sound" needs reference_videos`网关还会在创建任务之前检查以下组合：- `images` 不能与参考素材字段同时使用。
- `images` 是按时间顺序排列的画面帧：一张是首帧，两张是首帧和尾帧，更多则在两者之间加入中间帧；提示词中分别写作 `@first_frame`、`@keyframe_1`、`@keyframe_2` … 和 `@last_frame`。
- 图片数最多比视频秒数多一张，且无论如何不超过 10 张。
- 提示词中，`reference_images` 写作 `@image_1`、`@image_2` …，`reference_videos` 写作 `@video_1` …，`reference_audios` 写作 `@voice_1` …，元素写作 `@` 加元素名；提示词中的每个 `@` 都必须对应同一请求中的输入。
- 参考视频每段 2–30 秒，合计不超过 30 秒；参考视频与视频元素合计最多 5 个，其中视频元素最多 3 个；`reference_images`、`reference_videos`、`reference_audios` 与 `elements` 合计最多 15 个。
- 一个元素由 `element_input_urls` 中的 2–4 张图片组成（第一张是主视图），或由 `element_input_video_urls` 中一段 3–8 秒、单镜头的角色视频组成；`element_input_audio_urls` 为角色元素提供声音。
- 元素名为 1–20 个字母、数字、下划线或汉字，不区分大小写不得重复，且不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。
- `elements` 和 `aspect_ratio` 不能与 `images` 一起传：输出沿用首帧的画面比例；没有 `images` 时，`aspect_ratio` 默认 16:9。
- `keep_original_sound` 保留参考视频自身的声音，需要同时传 `reference_videos`；否则视频带有生成的音频。## 输入素材限制网关会在创建任务之前读取每一项输入，超出这些限制的输入会被拒绝，并返回点名该输入的 `400 bad_request`。不扣费。| 素材 | 创建任务前检查的限制                           |
| -- | ------------------------------------ |
| 图片 | 宽和高均为 300–65536 像素；宽高比（宽 ÷ 高）0.4–2.5 |
| 视频 | 每段 2–30 秒；合计不超过 30 秒                 |- 网关在创建任务前会测量 `images`、`reference_images` 和 `reference_videos`，超出下表限制的输入会被拒绝，报错按列表和位置指明是哪一个，例如 `reference_videos[0] is 35 seconds long; this model takes reference video of 2 to 30 seconds.`，不会扣费。
- 元素链接和 `reference_audios` 在创建任务前只检查是否为公网 HTTPS 链接。元素视频须为 3 到 8 秒。
- 素材在本地？先用 `POST /v1/files` 上传，再传入返回的 `data.url`。## 提示词中的引用每类输入有各自的引用写法，按列表顺序从 1 开始编号：| 引用                            | 对应的输入                | 可用条件              |
| ----------------------------- | -------------------- | ----------------- |
| `@image_1`、`@image_2` …       | `reference_images`   | 传入的参考图不少于该编号      |
| `@video_1`、`@video_2` …       | `reference_videos`   | 传入的参考视频不少于该编号     |
| `@voice_1`、`@voice_2` …       | `reference_audios`   | 传入的参考音频不少于该编号     |
| `@` + 元素名                     | `name` 相同的元素         | 该元素在 `elements` 中 |
| `@first_frame`                | `images[0]`          | 至少传了一张图片          |
| `@keyframe_1`、`@keyframe_2` … | 中间帧，从 `images[1]` 开始 | 传了三张或更多图片         |
| `@last_frame`                 | `images` 中的最后一个链接    | 传了两张或更多图片         |- 编号引用或画面帧引用找不到对应输入时，创建任务时会被拒绝，例如 `the prompt names @last_frame, which this request does not send`。## 组合规则以下规则在创建任务时检查；违反任意一条的请求会以 `400 bad_request` 被拒绝，不收费。| 规则                                              | 报错                                                                             |
| ----------------------------------------------- | ------------------------------------------------------------------------------ |
| `images` 与任一 `reference_*` 字段同时传入               | `Cannot combine "images" with reference inputs in one task`                    |
| `images` 与 `elements` 同时传入                      | `Kling V4 cannot combine elements with images`                                 |
| `images` 与 `aspect_ratio` 同时传入                  | `Kling V4 takes the first frame's shape; do not send aspect_ratio with images` |
| 图片数超过 `duration` + 1（此例为 5 秒视频）                 | `Kling V4 takes at most 6 images for a 5-second video`                         |
| 没有 `reference_videos` 却传了 `keep_original_sound` | `"keep_original_sound" needs reference_videos`                                 |
| 视频元素多于 3 个                                      | `Kling V4 takes at most 3 video elements`                                      |
| 参考视频与视频元素合计多于 5 个                               | `Kling V4 takes at most 5 reference videos and video elements together`        |
| 参考图、参考视频、参考音频与元素合计多于 15 个                       | `Kling V4 takes at most 15 reference inputs and elements together`             |## 该模型不接受的字段传入以下字段会在扣费前被拒绝，而不是被忽略：- `sound`、`generate_audio`、`seed`、`multi_shots`、`multi_prompt`、`quality`、`watermark`、`task_type`、`output_format` → `field "sound" is not supported by model kling-v4`（报错中是你传入的字段名）。
- 其他未知字段 → `unknown field: <name>`。## 请求示例```bash title="cURL"
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4",
  "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
  "duration": 5,
  "aspect_ratio": "16:9",
  "resolution": "720p"
}'
``````python title="Python"
import os
import requests

response = requests.post(
    "https://api.beatapi.io/v1/videos/tasks",
    headers={"Authorization": f"Bearer {os.environ['BEATAPI_API_KEY']}"},
    json={
      "model": "kling-v4",
      "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
      "duration": 5,
      "aspect_ratio": "16:9",
      "resolution": "720p"
    },
    timeout=60,
)
body = response.json()
if not response.ok:
    raise RuntimeError(f"{response.status_code} {body['error']['code']}: {body['error']['message']}")
task = body["data"]
print(task["id"], task["status"])
``````javascript title="JavaScript"
const response = await fetch('https://api.beatapi.io/v1/videos/tasks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.BEATAPI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "model": "kling-v4",
    "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
    "duration": 5,
    "aspect_ratio": "16:9",
    "resolution": "720p"
  }),
});
const body = await response.json();
if (!response.ok) throw new Error(`${response.status} ${body.error.code}: ${body.error.message}`);
console.log(body.data.id, body.data.status);
```### 文生视频一段 5 秒、16:9、720p、带生成音频的视频。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4",
  "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
  "duration": 5,
  "aspect_ratio": "16:9",
  "resolution": "720p"
}'
```### 首帧和尾帧视频以 1080p 从第一张图过渡到第二张图，画面比例沿用首帧。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4",
  "prompt": "The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot",
  "images": [
    "https://media.beatapi.io/samples/smart-bottle.png",
    "https://media.beatapi.io/samples/neon-singer.png"
  ],
  "duration": 5,
  "resolution": "1080p"
}'
```### 参考图和声音两张参考图和一段声音，都在提示词里写明引用。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4",
  "prompt": "The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1",
  "reference_images": [
    "https://media.beatapi.io/samples/neon-singer.png",
    "https://media.beatapi.io/samples/smart-bottle.png"
  ],
  "reference_audios": [
    "https://media.beatapi.io/samples/neon-singer-preview.mp3"
  ],
  "duration": 8,
  "aspect_ratio": "9:16",
  "resolution": "720p"
}'
```### 保留原声的参考视频把占位链接换成你自己的 2–30 秒片段；`keep_original_sound` 保留它的声音，而不使用生成的音频。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4",
  "prompt": "Restyle @video_1 as a neon-lit night scene and keep its camera movement",
  "reference_videos": [
    "https://your-cdn.example.com/clips/source.mp4"
  ],
  "keep_original_sound": true,
  "duration": 10,
  "resolution": "720p"
}'
```### 命名元素一个角色和一个道具，各用两张图片定义（第一张是主视图）。请把占位链接换成你自己的图片。```bash
curl --request POST \
  --url https://api.beatapi.io/v1/videos/tasks \
  --header "Authorization: Bearer $BEATAPI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "kling-v4",
  "prompt": "@singer walks across a neon stage holding @bottle and smiles at the camera",
  "duration": 6,
  "aspect_ratio": "16:9",
  "resolution": "720p",
  "elements": [
    {
      "name": "singer",
      "tag": "character",
      "description": "A performer in a silver jacket",
      "element_input_urls": [
        "https://your-cdn.example.com/elements/singer-front.png",
        "https://your-cdn.example.com/elements/singer-side.png"
      ]
    },
    {
      "name": "bottle",
      "tag": "prop",
      "element_input_urls": [
        "https://your-cdn.example.com/elements/bottle-front.png",
        "https://your-cdn.example.com/elements/bottle-back.png"
      ]
    }
  ]
}'
```## 响应### 创建任务（201）任务对象。任务成功之前 `output` 为 `null`。标注“运行中”的字段会在任务结束后消失。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "video",
    "capability_id": "kling-v4",
    "capability_version": 1,
    "media_type": "video",
    "model": "kling-v4",
    "status": "queued",
    "stage": "queued",
    "created_at": 1791993600,
    "updated_at": 1791993600,
    "completed_at": null,
    "poll_after_seconds": 8,
    "output": null,
    "usage": {
      "credits_reserved": 1,
      "credits_settled": 0,
      "credits_refunded": 0,
      "credits_charged": 1,
      "billable_duration_seconds": 5
    },
    "request_id": "req_5f0c2a9e4b7d4e31",
    "error_code": null,
    "error_message": null
  }
}
```| 字段                                     | 类型                | 说明                                                                        |
| -------------------------------------- | ----------------- | ------------------------------------------------------------------------- |
| `data.id`                              | `string`          | 任务 ID：`task_` 后接 32 位字母和数字。用于轮询以及匹配 Webhook 事件。                           |
| `data.object`                          | `string`          | 固定为 `task`。                                                               |
| `data.task_kind`                       | `string`          | `image` 或 `video`。                                                        |
| `data.capability_id`                   | `string`          | 你发送的模型 ID。                                                                |
| `data.capability_version`              | `integer`         | 模型的契约版本，当前为 `1`。                                                          |
| `data.media_type`                      | `string`          | `image` 或 `video`。                                                        |
| `data.model`                           | `string`          | 你发送的模型 ID（与 `capability_id` 相同）。                                          |
| `data.status`                          | `string`          | `queued`、`processing`、`succeeded` 或 `failed`。只有后两个是终态。                    |
| `data.stage`                           | `string`          | 与 `status` 相同；为旧版客户端保留。                                                   |
| `data.created_at`                      | `integer`         | 任务创建时间，Unix 秒。                                                            |
| `data.updated_at`                      | `integer`         | 最后一次变更时间，Unix 秒。                                                          |
| `data.completed_at`                    | `integer \| null` | 任务结束时间，Unix 秒；运行中为 `null`。                                                |
| `data.poll_after_seconds`              | `integer`         | 运行中：下一次轮询前需要等待的秒数（图片 5，视频 8）。                                             |
| `data.typical_seconds`                 | `object`          | 运行中且近期样本足够时出现：在最近的 `window` 内，根据 `samples` 个任务统计的完成时间 `p50` 和 `p90`，单位为秒。 |
| `data.output`                          | `object \| null`  | 任务结果；`status` 为 `succeeded` 之前为 `null`。见下方输出字段。                           |
| `data.usage.credits_reserved`          | `number`          | 创建任务时从你的余额中预扣的美元金额。                                                       |
| `data.usage.credits_charged`           | `number`          | 该任务的费用（美元）；失败的任务为 `0`。                                                    |
| `data.usage.credits_settled`           | `number`          | 最终结算扣除的美元金额；任务成功时设置，否则为 `0`。                                              |
| `data.usage.credits_refunded`          | `number`          | 退回你余额的美元金额；失败的任务在退款记录完成后等于预扣金额。                                           |
| `data.usage.billable_duration_seconds` | `integer`         | 仅视频：计价所依据的秒数。模型未上报时长时不出现。                                                 |
| `data.request_id`                      | `string`          | 请求 ID。联系支持时请附上。                                                           |
| `data.error_code`                      | `string \| null`  | 失败码；任务未失败时为 `null`。                                                       |
| `data.error_message`                   | `string \| null`  | 出了什么问题以及该改什么；任务未失败时为 `null`。                                              |### 任务完成`GET /v1/tasks/{task_id}` 返回 HTTP 200 和 `status: "succeeded"`，结果在 `data.output` 中。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "video",
    "capability_id": "kling-v4",
    "capability_version": 1,
    "media_type": "video",
    "model": "kling-v4",
    "status": "succeeded",
    "stage": "succeeded",
    "created_at": 1791993600,
    "updated_at": 1791993690,
    "completed_at": 1791993690,
    "output": {
      "media": [
        {
          "type": "video",
          "url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.mp4",
          "mime_type": "video/mp4"
        }
      ],
      "r2_url": "https://media.beatapi.io/outputs/task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ/0.mp4"
    },
    "usage": {
      "credits_reserved": 1,
      "credits_settled": 1,
      "credits_refunded": 0,
      "credits_charged": 1,
      "billable_duration_seconds": 5
    },
    "request_id": "req_5f0c2a9e4b7d4e31",
    "error_code": null,
    "error_message": null
  }
}
```#### 输出字段| 字段                         | 类型         | 说明                                |
| -------------------------- | ---------- | --------------------------------- |
| `output.media`             | `object[]` | 生成的文件；该模型为一个视频。                   |
| `output.media[].type`      | `string`   | 固定为 `video`。                      |
| `output.media[].url`       | `string`   | 已存储视频的 HTTPS 链接。请下载并自行保存；不承诺保留期限。 |
| `output.media[].mime_type` | `string`   | 文件的媒体类型，通常为 `video/mp4`。          |
| `output.r2_url`            | `string`   | 同一个视频链接，供旧客户端使用。请改读 `media`。      |### 任务失败失败的任务在 `GET /v1/tasks/{task_id}` 上仍然是 HTTP 200：失败信息在响应体里。预扣金额会全额退回，因此不会扣费。```json
{
  "data": {
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "object": "task",
    "task_kind": "video",
    "capability_id": "kling-v4",
    "capability_version": 1,
    "media_type": "video",
    "model": "kling-v4",
    "status": "failed",
    "stage": "failed",
    "created_at": 1791993600,
    "updated_at": 1791993690,
    "completed_at": 1791993690,
    "output": null,
    "usage": {
      "credits_reserved": 1,
      "credits_settled": 0,
      "credits_refunded": 1,
      "credits_charged": 0,
      "billable_duration_seconds": 5
    },
    "retryable": true,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "error_code": "processing_failed",
    "error_message": "The task failed during processing on our side. Retry; a failed task is refunded."
  }
}
```| 字段                   | 类型        | 说明                                                                                                                                                                          |
| -------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data.error_code`    | `string`  | `bad_request` 和 `content_policy_violation`（需修改请求）之一，或 `processing_unavailable`、`processing_timeout`、`processing_failed` 和 `result_transfer_failed`（稍后重试）之一。见[错误码](/errors)。 |
| `data.error_message` | `string`  | 一句话，指出问题和处理方式。                                                                                                                                                              |
| `data.retryable`     | `boolean` | 仅在任务失败时出现：为 `true` 表示再次发送相同请求可能成功。                                                                                                                                          |
| `data.usage`         | `object`  | 退款记录完成后（通常就在任务失败的那一刻）：`credits_charged` 和 `credits_settled` 为 `0`；`credits_refunded` 等于 `credits_reserved`。                                                                 |## 完整示例创建任务，按服务端给出的轮询提示等待，然后打印结果链接。请在环境变量中设置 `BEATAPI_API_KEY` 并安装 `requests`。```python
import os
import time
import uuid

import requests

API = "https://api.beatapi.io"
HEADERS = {"Authorization": f"Bearer {os.environ['BEATAPI_API_KEY']}"}


def create_task(body: dict) -> dict:
    # One Idempotency-Key per logical request: a retry with the same key cannot create a second task.
    headers = {**HEADERS, "Idempotency-Key": str(uuid.uuid4())}
    for attempt in range(3):
        response = requests.post(f"{API}/v1/videos/tasks", headers=headers, json=body, timeout=60)
        if response.status_code in (429, 503) and attempt < 2:
            time.sleep(int(response.headers.get("Retry-After", 10)))
            continue
        break
    try:
        payload = response.json()
    except ValueError:  # an edge error page is not JSON
        response.raise_for_status()
        raise
    if not response.ok:
        error = payload["error"]
        raise RuntimeError(f"{response.status_code} {error['code']}: {error['message']} (request_id={error.get('request_id')})")
    return payload["data"]


def wait_for_task(task_id: str, timeout_seconds: int = 1800) -> dict:
    deadline = time.monotonic() + timeout_seconds
    while time.monotonic() < deadline:
        response = requests.get(f"{API}/v1/tasks/{task_id}", headers=HEADERS, timeout=30)
        if response.status_code == 429 or response.status_code >= 500:
            time.sleep(int(response.headers.get("Retry-After", 10)))
            continue
        response.raise_for_status()
        task = response.json()["data"]
        if task["status"] in ("succeeded", "failed"):
            return task
        time.sleep(task.get("poll_after_seconds", 5))
    raise TimeoutError(f"task {task_id} is still running; keep polling later")


task = create_task({
  "model": "kling-v4",
  "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
  "duration": 5,
  "aspect_ratio": "16:9",
  "resolution": "720p"
})
print("created", task["id"])
task = wait_for_task(task["id"])
if task["status"] == "failed":
    raise SystemExit(f"{task['error_code']}: {task['error_message']}")
for item in task["output"]["media"]:
    print(item["url"])
```## 计费- 按所选分辨率下的视频秒数计费：`720p` 每秒 $0.20，`1080p` 每秒 $0.30。下表列出的是 8 秒片段的价格。
- 秒数即 `duration`，不传时为 5。任务的 `usage.billable_duration_seconds` 会显示它。
- 每个视频都带音频（生成的，或保留的参考视频原声），不另外收费。
- 创建任务时预留费用，视频完成时结算。失败的任务（包括提交后被审核拒绝的）全额退还。当前牌价，与[价格页](https://beatapi.io/pricing)一致。享有协商折扣的账户实付更低；任务的 `data.usage` 始终显示实际扣费金额。| 选项          | 牌价（美元） |
| ----------- | ------ |
| 8 秒 · 720p  | \$1.6  |
| 8 秒 · 1080p | \$2.4  |## 常见错误| 错误或现象                                                                                              | 原因                                                                               | 处理方式                                               |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------- |
| 400 `the prompt names @image_3, which this request does not send`                                  | 引用了请求中没有的输入，例如只传了两张参考图却写了第三张。                                                    | 让每个 `@` 都对应同一请求中的输入，编号按列表顺序从 1 开始。                 |
| 400 `Cannot combine "images" with reference inputs in one task`                                    | `images` 中的画面帧与 `reference_images`、`reference_videos` 或 `reference_audios` 同时传入。 | 画面帧和参考素材二选一。只想引导画面、不作为帧的图片请放进 `reference_images`。  |
| 400 `Kling V4 cannot combine elements with images`                                                 | `elements` 与画面帧同时传入。                                                             | 去掉 `images`，或去掉 `elements`。                        |
| 400 `Kling V4 takes the first frame's shape; do not send aspect_ratio with images`                 | `aspect_ratio` 与画面帧同时传入。                                                         | 去掉 `aspect_ratio`，并把首帧裁成你想要的画面比例。                  |
| 400 `Kling V4 takes at most 6 images for a 5-second video`                                         | 画面帧多于 `duration` + 1 张。                                                          | 减少画面帧，或加长 `duration`；无论如何最多 10 张。                  |
| 400 `elements[0] takes either element_input_urls or element_input_video_urls`                      | 某个元素同时有图片和视频，或两者都没有。                                                             | 每个元素给 2 到 4 张图片，或一段角色视频。                           |
| 400 `"elements[0].element_input_urls" requires at least 2 item`                                    | 某个元素只有一张图片。                                                                      | 为元素传 2 到 4 张图片，主视图放在第一张。                           |
| 400 `elements[0].name "image_1" is not a name Kling V4 accepts`                                    | 名字含有字母、数字、下划线和汉字以外的字符，或使用了 `image_1`、`first_frame` 这类保留名。                        | 给元素换个名字，例如 `singer` 或 `hero_bottle`，并在提示词里用这个名字引用。 |
| 400 `"keep_original_sound" needs reference_videos`                                                 | 没有 `reference_videos` 却传了 `keep_original_sound`。                                 | 去掉它，或加上你想保留其声音的参考视频。                               |
| 400 `reference_videos[0] is 35 seconds long; this model takes reference video of 2 to 30 seconds.` | 某段参考视频短于 2 秒或长于 30 秒；所有片段合计最多 30 秒。                                              | 把片段剪到你需要的部分。                                       |
| 400 `field "sound" is not supported by model kling-v4`                                             | 音频始终会生成，没有声音开关（`generate_audio`、`seed`、`multi_shots` 同样会被拒绝）。                    | 去掉该字段。想保留参考视频的原声，请传 `keep_original_sound: true`。   |
| 400 `"resolution" must be one of: [720p 1080p]`                                                    | 传了 `4K` 或 `pro` 这类档位名。                                                           | 传 `720p` 或 `1080p`。                                |
| 400 `"duration" is outside its supported range`                                                    | 不是 3 到 30 之间的整数，或以字符串传入。                                                         | 传一个整数，例如 `5`。                                      |
| 任务 `failed`，错误为 `content_policy_violation`                                                         | 提示词、某个输入或生成结果被内容审核拒绝。                                                            | 修改提示词或输入。原样重试仍会失败；不会扣费。                            |
| 402 `insufficient_credits`                                                                         | 余额低于这个时长和分辨率所需的预留金额。                                                             | 充值、缩短 `duration`，或改用 `720p`。                       |## HTTP 错误速查任务生成之前的错误会以非 2xx 响应返回，不扣费。请根据 `error.code` 或 `error.retryable` 判断处理方式；`message` 会指出问题所在。完整列表和重试策略见[错误码](/errors)。```json
{
  "error": {
    "code": "bad_request",
    "message": "\"prompt\" is required",
    "retryable": false,
    "request_id": "req_5f0c2a9e4b7d4e31"
  }
}
```| HTTP 状态码 | `error.code`                                                                                  | 处理方式                                                   |
| -------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| 400      | `bad_request`, `content_policy_violation`                                                     | 修改请求；message 会点名出错的字段。不要原样重试。                          |
| 401      | `missing_api_key`, `invalid_api_key`（旧版客户端可能看到 `unauthorized`）                                | 以 `Authorization: Bearer <key>` 发送有效的密钥。               |
| 402      | `insufficient_credits`                                                                        | 充值，或提高密钥的额度，然后重新发送。                                    |
| 403      | `forbidden`                                                                                   | 该密钥或账户不能使用此模型（例如免费额度只覆盖部分模型）。不要原样重试。                   |
| 404      | `not_found`                                                                                   | 在 `GET /v1/tasks/{task_id}` 上：该任务在此密钥所属账户下不存在。请检查 ID。  |
| 409      | `idempotency_conflict`                                                                        | 换一个新的 `Idempotency-Key`，或等待使用该键的第一个请求完成。               |
| 429      | `rate_limit_exceeded`                                                                         | 等待 `Retry-After` 秒（也见 `error.retry_after_seconds`）后重试。 |
| 500      | `internal_error`                                                                              | 退避重试；若持续出现，请带上 `request_id` 联系支持。                      |
| 503      | `processing_unavailable`, `processing_timeout`, `processing_failed`, `result_transfer_failed` | 未扣费。使用指数退避重试。                                          |

Reference: https://docs.beatapi.io/api-reference/video-api/kling-v4

## Authentication

- `Authorization` header (bearer token, required) — Send your API key as `Authorization: Bearer <BEATAPI_API_KEY>`.

## Servers

- `https://api.beatapi.io` (Direct, default)
- `https://api.beatapi.io` (API)

## Request

### Headers

- `Idempotency-Key` (string, optional) — 请求体使用 JSON，并设置 `Content-Type: application/json`。`Idempotency-Key` 为可选：每个逻辑请求发送一个唯一值（最长 255 个字符），仅在重试完全相同的请求体时复用。24 小时内，用相同的键和请求体重试会再次返回第一次的响应，并带上 `Idempotent-Replayed: true`；相同的键搭配不同的请求体则返回 `409 idempotency_conflict`。非 2xx 的响应不会被保存，因此 400 或 402 之后的重试会重新执行。

### Body (application/json)

This endpoint expects a KlingV4VideoRequest.

- `model` (enum, required) — 要运行的模型。 **取值**：`kling-v4` **取值有误时** - 未传：`"model" is required` - 把图片模型发到了这个端点：`"model" nano-banana-2 is served by POST /v1/images/tasks, not this endpoint`
  - Allowed values: `kling-v4`
- `prompt` (string, required) — 视频里发生什么：主体、动作、运镜、风格和声音，并用 `@` 引用写明每个输入。 **长度**：1–5000 个字符 - 长度按字符数计算（一个中日韩字符算一个字符）。 - 引用方式：`reference_images` 是 `@image_1`、`@image_2` …，`reference_videos` 是 `@video_1` …，`reference_audios` 是 `@voice_1` …，元素是 `@` 加它的 `name`。画面帧是 `@first_frame`、`@keyframe_1`、`@keyframe_2` … 和 `@last_frame`。 - 每个 `@` 都必须对应同一请求中的输入。编号引用或画面帧引用找不到对应输入时（例如只传了两张参考图却写了 `@image_3`，或只传了一张图却写了 `@last_frame`），创建任务时会被拒绝。 **取值有误时** - 未传：`"prompt" is required` - 为空或超过长度上限：`"prompt" has an unsupported length` - 引用了请求中没有的输入：`the prompt names @image_3, which this request does not send`
- `aspect_ratio` (enum, optional, default: 16:9) — 视频的宽高比（宽:高）。 **可选值**：`16:9`, `9:16`, `1:1`, `21:9` **默认值**：`16:9` - 不传时使用 `16:9`。 - 不要与 `images` 一起传：视频沿用首帧的画面比例。 **取值有误时** - 取值不在列表中：`"aspect_ratio" must be one of: [16:9 9:16 1:1 21:9]` - 与 `images` 同时传入：`Kling V4 takes the first frame's shape; do not send aspect_ratio with images`
  - Allowed values: `16:9`, `9:16`, `1:1`, `21:9`
- `duration` (integer, optional, default: 5) — 视频时长，单位为秒，须为整数。计费以它为准。 **默认值**：`5` **范围**：3–30 - 不传时使用并按 `5` 计费。 - 使用画面帧时，它还决定图片数上限：最多 `duration` + 1 张，且不超过 10 张。 **取值有误时** - 超出范围、不是整数，或以字符串传入：`"duration" is outside its supported range`
- `elements` (list of KlingV4VideoRequestElementsItems, optional) — 最多七个命名的主体，例如角色、动物、道具、服装、场景或特效；每个只需定义一次，在提示词里写成 `@` 加它的 `name`。 **数量**：≤ 7 - 最多七个对象组成的数组。每个对象只接受以下字段： - `elements[].name`（字符串，必填）：1 到 20 个字母、数字、下划线或汉字，同一请求内不区分大小写不得重复。不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。 - `elements[].element_input_urls`（字符串数组）：2 到 4 个公网 HTTPS 链接，是这个元素的图片；第一张是主视图。 - `elements[].element_input_video_urls`（字符串数组）：恰好一个公网 HTTPS 链接，是一段 3 到 8 秒、单镜头的角色视频。它与 `element_input_urls` 二选一，不能同时传。 - `elements[].element_input_audio_urls`（字符串数组，可选）：恰好一个公网 HTTPS 音频链接，是角色元素的声音。 - `elements[].tag`（字符串，可选）：元素的类别。视频元素或带声音的元素必须是角色：不传 `tag`，或传 `character`。 - `elements[].description`（字符串，可选）：对元素的描述，最多 100 个字符。 - 视频元素最多 3 个，与 `reference_videos` 合计最多 5 个。每个元素都计入参考素材与元素合计 15 个的上限。 - 元素不能与 `images` 一起传。 **取值有误时** - 多于七个元素：`"elements" accepts at most 7 items` - 某个元素不是对象：`"elements[0]" must be an object` - 某个元素缺少 `name`：`"name" is required in "elements[0]"` - `name` 为空或超过 20 个字符：`"elements[0].name" has an unsupported length` - `name` 含其他字符，或使用了保留名：`elements[0].name "image_1" is not a name Kling V4 accepts` - 同一个 `name` 出现两次（不区分大小写）：`elements[1].name "Hero" is used twice` - 同时有图片和视频，或两者都没有：`elements[0] takes either element_input_urls or element_input_video_urls` - 图片少于两张：`"elements[0].element_input_urls" requires at least 2 item` - 图片多于四张：`"elements[0].element_input_urls" accepts at most 4 items` - 视频元素的 `tag` 不是 `character`：`elements[0] is a video element, which is always a character` - `tag` 不是 `character` 的元素带了声音：`elements[0] has a voice, which only a character element takes` - `tag` 不在列表中：`"elements[0].tag" must be one of: [character animal prop costume scene effect others]` - `description` 超过 100 个字符：`"elements[0].description" has an unsupported length` - 元素里有不接受的字段：`field "start_time" is not supported in "elements[0]"` - 视频元素多于三个：`Kling V4 takes at most 3 video elements` - 与 `images` 同时传入：`Kling V4 cannot combine elements with images`
- `images` (list of string, optional) — 按时间顺序排列的画面帧：一个链接是首帧，两个是首帧和尾帧，更多则在两者之间加入中间帧。 **数量**：1–10 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 有三个或更多链接时，`images[0]` 是首帧，最后一个链接是尾帧，中间的链接是中间帧：`images[1]` 是 `@keyframe_1`，`images[2]` 是 `@keyframe_2`，依此类推。 - 图片数最多比视频秒数多一张（`duration` + 1；不传 `duration` 时按 5 秒算），且无论如何不超过 10 张。 - 画面帧不能与 `reference_images`、`reference_videos`、`reference_audios`、`elements` 或 `aspect_ratio` 一起传：视频沿用首帧的画面比例。 **取值有误时** - 多于 10 个链接：`"images" accepts at most 10 items` - 链接数超过 `duration` + 1（此例为 5 秒视频传了 7 个链接）：`Kling V4 takes at most 6 images for a 5-second video` - 与任一 reference_* 字段同时传入：`Cannot combine "images" with reference inputs in one task` - 与 `elements` 同时传入：`Kling V4 cannot combine elements with images` - 与 `aspect_ratio` 同时传入：`Kling V4 takes the first frame's shape; do not send aspect_ratio with images` - 不是 https:// 链接：`"images[0]" must be a public HTTPS URL`
- `keep_original_sound` (boolean, optional) — 在成片中保留参考视频自身的声音，而不是使用生成的音频。 - 只能与 `reference_videos` 一起使用；没有参考视频时传入（即使是 `false`）也会被拒绝。 - 不传时视频带有生成的音频。没有关闭音频的字段。 **取值有误时** - 不是 true 或 false：`"keep_original_sound" must be a boolean` - 没有 `reference_videos` 时传入：`"keep_original_sound" needs reference_videos`
- `reference_audios` (list of string, optional) — 视频中使用的声音。在提示词里按列表顺序写成 `@voice_1`、`@voice_2` …。 **数量**：1–3 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 不能与 `images` 一起使用。 - 计入参考素材与元素合计 15 个的上限。 **取值有误时** - 超过上限：`"reference_audios" accepts at most 3 items`
- `reference_images` (list of string, optional) — 引导视频内容、角色、商品或风格的图片。在提示词里按列表顺序写成 `@image_1`、`@image_2` …。 **数量**：1–10 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 不能与 `images` 一起使用。 - 计入参考素材与元素合计 15 个的上限。 **取值有误时** - 超过上限：`"reference_images" accepts at most 10 items` - 参考素材与元素合计超过 15 个：`Kling V4 takes at most 15 reference inputs and elements together`
- `reference_videos` (list of string, optional) — 用来借鉴动作、运镜或内容的视频。在提示词里按列表顺序写成 `@video_1`、`@video_2` …。 **数量**：1–5 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。 - 每段 2 到 30 秒，所有片段合计不超过 30 秒。网关在创建任务前会逐段测量，超出限制的片段会被拒绝，并在报错中指明是哪一段。 - 参考视频与视频元素合计最多 5 个，并计入参考素材与元素合计 15 个的上限。 - 成片默认带生成的音频；传 `keep_original_sound: true` 则保留参考视频自身的声音。 **取值有误时** - 超过上限：`"reference_videos" accepts at most 5 items` - 某段短于 2 秒或长于 30 秒：`reference_videos[0] is 35 seconds long; this model takes reference video of 2 to 30 seconds.` - 所有片段合计超过 30 秒：`The reference videos run 36 seconds in total; this model takes at most 30.` - 参考视频与视频元素合计超过 5 个：`Kling V4 takes at most 5 reference videos and video elements together`
- `resolution` (enum, optional, default: 720p) — 输出分辨率。`1080p` 的每秒价格高于 `720p`。 **可选值**：`720p`, `1080p` **默认值**：`720p` - 不传时使用并按 `720p` 计费。 - 该模型不提供 4K。 **取值有误时** - 取值不在列表中（例如 `4K` 或 `pro`）：`"resolution" must be one of: [720p 1080p]`
  - Allowed values: `720p`, `1080p`

## Response

### 201

任务对象。任务成功之前 `output` 为 `null`。标注“运行中”的字段会在任务结束后消失。

- `map from string to any`

## Errors

### 400 Bad Request Error

`bad_request`, `content_policy_violation` 修改请求；message 会点名出错的字段。不要原样重试。

- `map from string to any`

### 401 Unauthorized Error

`missing_api_key`, `invalid_api_key`（旧版客户端可能看到 `unauthorized`） 以 `Authorization: Bearer <key>` 发送有效的密钥。

- `map from string to any`

### 402 Payment Required Error

`insufficient_credits` 充值，或提高密钥的额度，然后重新发送。

- `map from string to any`

### 403 Forbidden Error

`forbidden` 该密钥或账户不能使用此模型（例如免费额度只覆盖部分模型）。不要原样重试。

- `map from string to any`

### 409 Conflict Error

`idempotency_conflict` 换一个新的 `Idempotency-Key`，或等待使用该键的第一个请求完成。

- `map from string to any`

### 429 Too Many Requests Error

`rate_limit_exceeded` 等待 `Retry-After` 秒（也见 `error.retry_after_seconds`）后重试。

- `map from string to any`

### 500 Internal Server Error

`internal_error` 退避重试；若持续出现，请带上 `request_id` 联系支持。

- `map from string to any`

### 503 Service Unavailable Error

`processing_unavailable`, `processing_timeout`, `processing_failed`, `result_transfer_failed` 未扣费。使用指数退避重试。

- `map from string to any`

## Types

### KlingV4VideoRequestElementsItems

- `name` (string, required) — `elements[].name`（字符串，必填）：1 到 20 个字母、数字、下划线或汉字，同一请求内不区分大小写不得重复。不能是 `image_N`、`video_N`、`voice_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame` 或 `last_frame`。 **长度**：1–20 个字符
- `description` (string, optional) — `elements[].description`（字符串，可选）：对元素的描述，最多 100 个字符。 **长度**：≤ 100 个字符
- `element_input_audio_urls` (list of string, optional) — `elements[].element_input_audio_urls`（字符串数组，可选）：恰好一个公网 HTTPS 音频链接，是角色元素的声音。 **数量**：1–1 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。
- `element_input_urls` (list of string, optional) — `elements[].element_input_urls`（字符串数组）：2 到 4 个公网 HTTPS 链接，是这个元素的图片；第一张是主视图。 **数量**：2–4 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。
- `element_input_video_urls` (list of string, optional) — `elements[].element_input_video_urls`（字符串数组）：恰好一个公网 HTTPS 链接，是一段 3 到 8 秒、单镜头的角色视频。它与 `element_input_urls` 二选一，不能同时传。 **数量**：1–1 每一项都必须是公网 `https://` 链接。本地文件请先[上传](/quick-guide#upload-an-input-file)（`POST /v1/files`），再传入返回的 `data.url`。
- `tag` (enum, optional) — `elements[].tag`（字符串，可选）：元素的类别。视频元素或带声音的元素必须是角色：不传 `tag`，或传 `character`。 **可选值**：`character`, `animal`, `prop`, `costume`, `scene`, `effect`, `others`
  - Allowed values: `character`, `animal`, `prop`, `costume`, `scene`, `effect`, `others`

## Examples

### 文生视频

**Request**

```json
{
  "model": "kling-v4",
  "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
  "aspect_ratio": "16:9",
  "duration": 5,
  "resolution": "720p"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "video",
    "model": "kling-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 8,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "video",
    "updated_at": 1791993600,
    "usage": {
      "billable_duration_seconds": 5,
      "credits_charged": 1,
      "credits_refunded": 0,
      "credits_reserved": 1,
      "credits_settled": 0
    }
  }
}
```

**SDK Code**

```python 文生视频
import requests

url = "https://api.beatapi.io/v1/videos/tasks"

payload = {
    "model": "kling-v4",
    "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
    "aspect_ratio": "16:9",
    "duration": 5,
    "resolution": "720p"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 文生视频
const url = 'https://api.beatapi.io/v1/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4","prompt":"A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone","aspect_ratio":"16:9","duration":5,"resolution":"720p"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 文生视频
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5,\n  \"resolution\": \"720p\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 文生视频
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/videos/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5,\n  \"resolution\": \"720p\"\n}"

response = http.request(request)
puts response.read_body
```

```java 文生视频
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5,\n  \"resolution\": \"720p\"\n}")
  .asString();
```

```php 文生视频
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4",
  "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
  "aspect_ratio": "16:9",
  "duration": 5,
  "resolution": "720p"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 文生视频
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 5,\n  \"resolution\": \"720p\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 文生视频
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4",
  "prompt": "A dramatic product reveal of a glass water bottle, slow orbiting camera, soft studio reflections, a low ambient synth tone",
  "aspect_ratio": "16:9",
  "duration": 5,
  "resolution": "720p"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 首帧和尾帧

**Request**

```json
{
  "model": "kling-v4",
  "prompt": "The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot",
  "duration": 5,
  "images": [
    "https://media.beatapi.io/samples/smart-bottle.png",
    "https://media.beatapi.io/samples/neon-singer.png"
  ],
  "resolution": "1080p"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "video",
    "model": "kling-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 8,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "video",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 首帧和尾帧
import requests

url = "https://api.beatapi.io/v1/videos/tasks"

payload = {
    "model": "kling-v4",
    "prompt": "The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot",
    "duration": 5,
    "images": ["https://media.beatapi.io/samples/smart-bottle.png", "https://media.beatapi.io/samples/neon-singer.png"],
    "resolution": "1080p"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 首帧和尾帧
const url = 'https://api.beatapi.io/v1/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4","prompt":"The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot","duration":5,"images":["https://media.beatapi.io/samples/smart-bottle.png","https://media.beatapi.io/samples/neon-singer.png"],"resolution":"1080p"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 首帧和尾帧
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://media.beatapi.io/samples/smart-bottle.png\",\n    \"https://media.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"1080p\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 首帧和尾帧
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/videos/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://media.beatapi.io/samples/smart-bottle.png\",\n    \"https://media.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"1080p\"\n}"

response = http.request(request)
puts response.read_body
```

```java 首帧和尾帧
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://media.beatapi.io/samples/smart-bottle.png\",\n    \"https://media.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"1080p\"\n}")
  .asString();
```

```php 首帧和尾帧
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4",
  "prompt": "The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot",
  "duration": 5,
  "images": [
    "https://media.beatapi.io/samples/smart-bottle.png",
    "https://media.beatapi.io/samples/neon-singer.png"
  ],
  "resolution": "1080p"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 首帧和尾帧
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot\",\n  \"duration\": 5,\n  \"images\": [\n    \"https://media.beatapi.io/samples/smart-bottle.png\",\n    \"https://media.beatapi.io/samples/neon-singer.png\"\n  ],\n  \"resolution\": \"1080p\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 首帧和尾帧
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4",
  "prompt": "The camera moves from the bottle in @first_frame to the singer on a neon stage in @last_frame in one continuous shot",
  "duration": 5,
  "images": ["https://media.beatapi.io/samples/smart-bottle.png", "https://media.beatapi.io/samples/neon-singer.png"],
  "resolution": "1080p"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 参考图和声音

**Request**

```json
{
  "model": "kling-v4",
  "prompt": "The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1",
  "aspect_ratio": "9:16",
  "duration": 8,
  "reference_audios": [
    "https://media.beatapi.io/samples/neon-singer-preview.mp3"
  ],
  "reference_images": [
    "https://media.beatapi.io/samples/neon-singer.png",
    "https://media.beatapi.io/samples/smart-bottle.png"
  ],
  "resolution": "720p"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "video",
    "model": "kling-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 8,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "video",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 参考图和声音
import requests

url = "https://api.beatapi.io/v1/videos/tasks"

payload = {
    "model": "kling-v4",
    "prompt": "The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1",
    "aspect_ratio": "9:16",
    "duration": 8,
    "reference_audios": ["https://media.beatapi.io/samples/neon-singer-preview.mp3"],
    "reference_images": ["https://media.beatapi.io/samples/neon-singer.png", "https://media.beatapi.io/samples/smart-bottle.png"],
    "resolution": "720p"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 参考图和声音
const url = 'https://api.beatapi.io/v1/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4","prompt":"The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1","aspect_ratio":"9:16","duration":8,"reference_audios":["https://media.beatapi.io/samples/neon-singer-preview.mp3"],"reference_images":["https://media.beatapi.io/samples/neon-singer.png","https://media.beatapi.io/samples/smart-bottle.png"],"resolution":"720p"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 参考图和声音
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_audios\": [\n    \"https://media.beatapi.io/samples/neon-singer-preview.mp3\"\n  ],\n  \"reference_images\": [\n    \"https://media.beatapi.io/samples/neon-singer.png\",\n    \"https://media.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"720p\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 参考图和声音
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/videos/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_audios\": [\n    \"https://media.beatapi.io/samples/neon-singer-preview.mp3\"\n  ],\n  \"reference_images\": [\n    \"https://media.beatapi.io/samples/neon-singer.png\",\n    \"https://media.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"720p\"\n}"

response = http.request(request)
puts response.read_body
```

```java 参考图和声音
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_audios\": [\n    \"https://media.beatapi.io/samples/neon-singer-preview.mp3\"\n  ],\n  \"reference_images\": [\n    \"https://media.beatapi.io/samples/neon-singer.png\",\n    \"https://media.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"720p\"\n}")
  .asString();
```

```php 参考图和声音
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4",
  "prompt": "The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1",
  "aspect_ratio": "9:16",
  "duration": 8,
  "reference_audios": [
    "https://media.beatapi.io/samples/neon-singer-preview.mp3"
  ],
  "reference_images": [
    "https://media.beatapi.io/samples/neon-singer.png",
    "https://media.beatapi.io/samples/smart-bottle.png"
  ],
  "resolution": "720p"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 参考图和声音
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1\",\n  \"aspect_ratio\": \"9:16\",\n  \"duration\": 8,\n  \"reference_audios\": [\n    \"https://media.beatapi.io/samples/neon-singer-preview.mp3\"\n  ],\n  \"reference_images\": [\n    \"https://media.beatapi.io/samples/neon-singer.png\",\n    \"https://media.beatapi.io/samples/smart-bottle.png\"\n  ],\n  \"resolution\": \"720p\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 参考图和声音
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4",
  "prompt": "The singer from @image_1 lifts the bottle from @image_2 toward the camera and says a short line in the voice of @voice_1",
  "aspect_ratio": "9:16",
  "duration": 8,
  "reference_audios": ["https://media.beatapi.io/samples/neon-singer-preview.mp3"],
  "reference_images": ["https://media.beatapi.io/samples/neon-singer.png", "https://media.beatapi.io/samples/smart-bottle.png"],
  "resolution": "720p"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 保留原声的参考视频

**Request**

```json
{
  "model": "kling-v4",
  "prompt": "Restyle @video_1 as a neon-lit night scene and keep its camera movement",
  "duration": 10,
  "keep_original_sound": true,
  "reference_videos": [
    "https://your-cdn.example.com/clips/source.mp4"
  ],
  "resolution": "720p"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "video",
    "model": "kling-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 8,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "video",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 保留原声的参考视频
import requests

url = "https://api.beatapi.io/v1/videos/tasks"

payload = {
    "model": "kling-v4",
    "prompt": "Restyle @video_1 as a neon-lit night scene and keep its camera movement",
    "duration": 10,
    "keep_original_sound": True,
    "reference_videos": ["https://your-cdn.example.com/clips/source.mp4"],
    "resolution": "720p"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 保留原声的参考视频
const url = 'https://api.beatapi.io/v1/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4","prompt":"Restyle @video_1 as a neon-lit night scene and keep its camera movement","duration":10,"keep_original_sound":true,"reference_videos":["https://your-cdn.example.com/clips/source.mp4"],"resolution":"720p"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 保留原声的参考视频
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"Restyle @video_1 as a neon-lit night scene and keep its camera movement\",\n  \"duration\": 10,\n  \"keep_original_sound\": true,\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ],\n  \"resolution\": \"720p\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 保留原声的参考视频
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/videos/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"Restyle @video_1 as a neon-lit night scene and keep its camera movement\",\n  \"duration\": 10,\n  \"keep_original_sound\": true,\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ],\n  \"resolution\": \"720p\"\n}"

response = http.request(request)
puts response.read_body
```

```java 保留原声的参考视频
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"Restyle @video_1 as a neon-lit night scene and keep its camera movement\",\n  \"duration\": 10,\n  \"keep_original_sound\": true,\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ],\n  \"resolution\": \"720p\"\n}")
  .asString();
```

```php 保留原声的参考视频
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4",
  "prompt": "Restyle @video_1 as a neon-lit night scene and keep its camera movement",
  "duration": 10,
  "keep_original_sound": true,
  "reference_videos": [
    "https://your-cdn.example.com/clips/source.mp4"
  ],
  "resolution": "720p"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 保留原声的参考视频
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"Restyle @video_1 as a neon-lit night scene and keep its camera movement\",\n  \"duration\": 10,\n  \"keep_original_sound\": true,\n  \"reference_videos\": [\n    \"https://your-cdn.example.com/clips/source.mp4\"\n  ],\n  \"resolution\": \"720p\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 保留原声的参考视频
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4",
  "prompt": "Restyle @video_1 as a neon-lit night scene and keep its camera movement",
  "duration": 10,
  "keep_original_sound": true,
  "reference_videos": ["https://your-cdn.example.com/clips/source.mp4"],
  "resolution": "720p"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### 命名元素

**Request**

```json
{
  "model": "kling-v4",
  "prompt": "@singer walks across a neon stage holding @bottle and smiles at the camera",
  "aspect_ratio": "16:9",
  "duration": 6,
  "elements": [
    {
      "name": "singer",
      "description": "A performer in a silver jacket",
      "element_input_urls": [
        "https://your-cdn.example.com/elements/singer-front.png",
        "https://your-cdn.example.com/elements/singer-side.png"
      ],
      "tag": "character"
    },
    {
      "name": "bottle",
      "element_input_urls": [
        "https://your-cdn.example.com/elements/bottle-front.png",
        "https://your-cdn.example.com/elements/bottle-back.png"
      ],
      "tag": "prop"
    }
  ],
  "resolution": "720p"
}
```

**Response**

```json
{
  "data": {
    "capability_id": "kling-v4",
    "capability_version": 1,
    "completed_at": null,
    "created_at": 1791993600,
    "error_code": null,
    "error_message": null,
    "id": "task_7Qm2Xc9LpR4vT8sKa1Nf6YbH3eWdJ0uZ",
    "media_type": "video",
    "model": "kling-v4",
    "object": "task",
    "output": null,
    "poll_after_seconds": 8,
    "request_id": "req_5f0c2a9e4b7d4e31",
    "stage": "queued",
    "status": "queued",
    "task_kind": "video",
    "updated_at": 1791993600
  }
}
```

**SDK Code**

```python 命名元素
import requests

url = "https://api.beatapi.io/v1/videos/tasks"

payload = {
    "model": "kling-v4",
    "prompt": "@singer walks across a neon stage holding @bottle and smiles at the camera",
    "aspect_ratio": "16:9",
    "duration": 6,
    "elements": [
        {
            "name": "singer",
            "description": "A performer in a silver jacket",
            "element_input_urls": ["https://your-cdn.example.com/elements/singer-front.png", "https://your-cdn.example.com/elements/singer-side.png"],
            "tag": "character"
        },
        {
            "name": "bottle",
            "element_input_urls": ["https://your-cdn.example.com/elements/bottle-front.png", "https://your-cdn.example.com/elements/bottle-back.png"],
            "tag": "prop"
        }
    ],
    "resolution": "720p"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript 命名元素
const url = 'https://api.beatapi.io/v1/videos/tasks';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"kling-v4","prompt":"@singer walks across a neon stage holding @bottle and smiles at the camera","aspect_ratio":"16:9","duration":6,"elements":[{"name":"singer","description":"A performer in a silver jacket","element_input_urls":["https://your-cdn.example.com/elements/singer-front.png","https://your-cdn.example.com/elements/singer-side.png"],"tag":"character"},{"name":"bottle","element_input_urls":["https://your-cdn.example.com/elements/bottle-front.png","https://your-cdn.example.com/elements/bottle-back.png"],"tag":"prop"}],"resolution":"720p"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go 命名元素
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/videos/tasks"

	payload := strings.NewReader("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"@singer walks across a neon stage holding @bottle and smiles at the camera\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 6,\n  \"elements\": [\n    {\n      \"name\": \"singer\",\n      \"description\": \"A performer in a silver jacket\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/singer-front.png\",\n        \"https://your-cdn.example.com/elements/singer-side.png\"\n      ],\n      \"tag\": \"character\"\n    },\n    {\n      \"name\": \"bottle\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/bottle-front.png\",\n        \"https://your-cdn.example.com/elements/bottle-back.png\"\n      ],\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"720p\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby 命名元素
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/videos/tasks")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"@singer walks across a neon stage holding @bottle and smiles at the camera\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 6,\n  \"elements\": [\n    {\n      \"name\": \"singer\",\n      \"description\": \"A performer in a silver jacket\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/singer-front.png\",\n        \"https://your-cdn.example.com/elements/singer-side.png\"\n      ],\n      \"tag\": \"character\"\n    },\n    {\n      \"name\": \"bottle\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/bottle-front.png\",\n        \"https://your-cdn.example.com/elements/bottle-back.png\"\n      ],\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"720p\"\n}"

response = http.request(request)
puts response.read_body
```

```java 命名元素
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/videos/tasks")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"@singer walks across a neon stage holding @bottle and smiles at the camera\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 6,\n  \"elements\": [\n    {\n      \"name\": \"singer\",\n      \"description\": \"A performer in a silver jacket\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/singer-front.png\",\n        \"https://your-cdn.example.com/elements/singer-side.png\"\n      ],\n      \"tag\": \"character\"\n    },\n    {\n      \"name\": \"bottle\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/bottle-front.png\",\n        \"https://your-cdn.example.com/elements/bottle-back.png\"\n      ],\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"720p\"\n}")
  .asString();
```

```php 命名元素
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/videos/tasks', [
  'body' => '{
  "model": "kling-v4",
  "prompt": "@singer walks across a neon stage holding @bottle and smiles at the camera",
  "aspect_ratio": "16:9",
  "duration": 6,
  "elements": [
    {
      "name": "singer",
      "description": "A performer in a silver jacket",
      "element_input_urls": [
        "https://your-cdn.example.com/elements/singer-front.png",
        "https://your-cdn.example.com/elements/singer-side.png"
      ],
      "tag": "character"
    },
    {
      "name": "bottle",
      "element_input_urls": [
        "https://your-cdn.example.com/elements/bottle-front.png",
        "https://your-cdn.example.com/elements/bottle-back.png"
      ],
      "tag": "prop"
    }
  ],
  "resolution": "720p"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp 命名元素
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/videos/tasks");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"kling-v4\",\n  \"prompt\": \"@singer walks across a neon stage holding @bottle and smiles at the camera\",\n  \"aspect_ratio\": \"16:9\",\n  \"duration\": 6,\n  \"elements\": [\n    {\n      \"name\": \"singer\",\n      \"description\": \"A performer in a silver jacket\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/singer-front.png\",\n        \"https://your-cdn.example.com/elements/singer-side.png\"\n      ],\n      \"tag\": \"character\"\n    },\n    {\n      \"name\": \"bottle\",\n      \"element_input_urls\": [\n        \"https://your-cdn.example.com/elements/bottle-front.png\",\n        \"https://your-cdn.example.com/elements/bottle-back.png\"\n      ],\n      \"tag\": \"prop\"\n    }\n  ],\n  \"resolution\": \"720p\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift 命名元素
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "kling-v4",
  "prompt": "@singer walks across a neon stage holding @bottle and smiles at the camera",
  "aspect_ratio": "16:9",
  "duration": 6,
  "elements": [
    [
      "name": "singer",
      "description": "A performer in a silver jacket",
      "element_input_urls": ["https://your-cdn.example.com/elements/singer-front.png", "https://your-cdn.example.com/elements/singer-side.png"],
      "tag": "character"
    ],
    [
      "name": "bottle",
      "element_input_urls": ["https://your-cdn.example.com/elements/bottle-front.png", "https://your-cdn.example.com/elements/bottle-back.png"],
      "tag": "prop"
    ]
  ],
  "resolution": "720p"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/videos/tasks")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```