# Kling 4.0 视频生成 API 对接文档

## 概述

Kling 4.0（可灵）提供两种视频生成方式：

- **参考生视频**（`/aigc/kling-4.0`）：用参考图、参考视频、主体元素和音色来生成视频，在提示词里用 `@image_1`、`@video_1` 或自定义 `@name` 引用素材。四类素材都可以不传，此时等同于普通文生视频。
- **关键帧生视频**（`/aigc/kling-4.0-keyframe`）：用首帧、中间帧和尾帧串起一段连续画面，在提示词里用 `@first_frame`、`@keyframe_1`、`@last_frame` 引用帧。

主体和音色有两种给法：在生视频请求里直接带素材 URL（内联），或先通过「主体与音色素材接口」创建素材，再在生视频请求里用 `assetId` 引用。同一个素材可以在多次任务里反复使用。

两种方式的时长范围都是 3-30 秒，分辨率支持 720p / 1080p，画幅支持 `16:9`、`9:16`、`1:1`、`21:9`。

**Base URL**: `https://mm-internal-cn.leonecloud.com`

---

## 认证方式

所有接口均需要在请求头中携带 Token 进行认证：

```
Authorization: Bearer {YOUR_AUTH_TOKEN}
```

## 快速开始

### cURL 示例

**参考生视频（参考图 + 主体元素）**
```bash
curl -X POST "https://mm-internal-cn.leonecloud.com/api/v2/open/aigc/kling-4.0" \
  -H "Authorization: Bearer your_auth_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "@Hero 在 @image_1 的房间里坐下，对着镜头微笑",
    "duration": 10,
    "resolution": "1080p",
    "aspectRatio": "16:9",
    "imageUrls": ["https://example.com/room.png"],
    "elements": [
      {
        "name": "Hero",
        "imageUrls": [
          "https://example.com/hero-front.jpg",
          "https://example.com/hero-side.jpg"
        ],
        "tag": "character",
        "description": "穿红色外套的年轻人"
      }
    ]
  }'
```

**参考生视频（参考视频，保留原声）**
```bash
curl -X POST "https://mm-internal-cn.leonecloud.com/api/v2/open/aigc/kling-4.0" \
  -H "Authorization: Bearer your_auth_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "镜头跟随 @video_1 中的舞者，背景换成赛博朋克街道",
    "duration": 5,
    "resolution": "720p",
    "videoUrls": ["https://example.com/dance.mp4"],
    "keepOriginalSound": true
  }'
```

**关键帧生视频（首帧 → 中间帧 → 尾帧）**
```bash
curl -X POST "https://mm-internal-cn.leonecloud.com/api/v2/open/aigc/kling-4.0-keyframe" \
  -H "Authorization: Bearer your_auth_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "@first_frame 中的女孩走出家门，经过 @keyframe_1 的街道，最后抵达 @last_frame 的派对现场",
    "duration": 10,
    "resolution": "720p",
    "firstFrameUrl": "https://example.com/home.png",
    "keyframeUrls": ["https://example.com/street.png"],
    "lastFrameUrl": "https://example.com/party.png"
  }'
```

**查询任务状态**
```bash
curl -X GET "https://mm-internal-cn.leonecloud.com/api/v2/open/aigc/task_abc123" \
  -H "Authorization: Bearer your_auth_token_here"
```

**查询账户余额**
```bash
curl -X GET "https://mm-internal-cn.leonecloud.com/api/v2/open/balance" \
  -H "Authorization: Bearer your_auth_token_here"
```

---

## 接口列表

### 1. 创建 Kling 4.0 参考生视频任务

**POST** `/api/v2/open/aigc/kling-4.0`

用参考图、参考视频、主体元素和音色生成视频。四类素材都不传时即为文生视频。

**Content-Type**: `application/json`

#### 请求参数

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| prompt | string | 是 | 视频描述，最多 8000 字符。用 `@image_1`、`@video_1`、`@name` 引用本请求携带的素材 |
| duration | int | 否 | 输出时长 3-30 秒，默认 5 |
| resolution | string | 否 | 输出分辨率：`720p`(默认) / `1080p` |
| aspectRatio | string | 否 | 画幅：`auto` / `16:9` / `9:16` / `1:1` / `21:9`。不传时：有素材按素材自适应，无素材按 `16:9` |
| imageUrls | string[] | 否 | 参考图，最多 10 张。按数组顺序对应 `@image_1`、`@image_2`… |
| videoUrls | string[] | 否 | 参考视频，最多 5 段，每段 2-30 秒。按数组顺序对应 `@video_1`、`@video_2`… |
| keepOriginalSound | boolean | 否 | 是否保留参考视频原声，默认 false。仅在传了 `videoUrls` 时生效；未传参考视频时始终生成原生音频 |
| elements | object[] | 否 | 主体元素，最多 7 个（其中视频主体最多 3 个） |
| elements[].name | string | 是 | 元素名称，不带 `@`，在 prompt 中用 `@name` 引用 |
| elements[].assetId | string | 条件 | 主体素材 ID（「创建主体素材」返回）。传了 `assetId` 就不再传 `imageUrls` / `videoUrl` / `tag` / `description` / `voiceUrl` |
| elements[].imageUrls | string[] | 条件 | 图片主体的参考图，2-4 张。第一张为主视角（正脸或主角度），其余为辅助视角。`assetId`、`imageUrls`、`videoUrl` 三选一 |
| elements[].videoUrl | string | 条件 | 视频主体的角色视频：1 段，3-8 秒，单镜头不剪辑。与 `imageUrls` 二选一 |
| elements[].tag | string | 否 | 主体类别：`character` / `animal` / `prop` / `costume` / `scene` / `effect` / `others`。图片主体不传则自动识别；视频主体只能是 `character` |
| elements[].description | string | 否 | 主体描述，最多 100 字符 |
| elements[].voiceUrl | string | 否 | 绑定到该主体的参考音频，仅人物主体可用，不计入 `voices` 配额 |
| voices | object[] | 否 | 独立音色，最多 3 个 |
| voices[].name | string | 是 | 音色名称，不带 `@`，在 prompt 中用 `@name` 引用 |
| voices[].assetId | string | 条件 | 音色素材 ID（「创建音色素材」返回），与 `audioUrl` 二选一 |
| voices[].audioUrl | string | 条件 | 参考音频 URL。若无法从音频中识别出可用人声，任务会失败 |
| callbackUrl | string | 否 | 任务完成后的回调通知 URL |
| taskNickname | string | 否 | 任务昵称 |

> **说明**：
> - 四类素材可以任意组合；`imageUrls`、`videoUrls`、`elements`、`voices` 合计最多 15 个
> - 参考视频与视频主体共用一份配额：合计最多 5 段，时长合计不超过 30 秒
> - 名称需为 1-20 位中文、字母、数字或下划线，且在本请求内不重名（不区分大小写）
> - 不能使用保留名：`image_N`、`video_N`、`keyframe_N`、`object_N`、`audio_N`、`first_frame`、`last_frame`
> - prompt 中每个 `@` 引用都必须对应本请求声明过的素材，否则请求会被拒绝
> - 用 `assetId` 引用的主体/音色须是本账号创建、且状态为 `succeeded` 的素材
> - 同一请求里，`assetId` 引用的主体/音色不能与内联主体/音色（`imageUrls` / `videoUrl` / `audioUrl`）混用，也不能与 `keepOriginalSound: true` 同时使用
> - `elementType` 为 `video` 的主体素材与 `videoUrl` 视频主体一样计入视频输入（占参考视频配额，按有视频输入计费）
> - 参考图每边边长 300-65536 像素，宽高比在 0.40-2.5 之间
> - 创建任务时会预扣费，余额不足将返回错误

#### 请求示例

**纯文生视频（不传任何素材）：**
```json
{
  "prompt": "一只橘猫在午后的窗台上打盹，阳光缓慢移动",
  "duration": 5,
  "resolution": "1080p",
  "aspectRatio": "16:9"
}
```

**参考图 + 音色：**
```json
{
  "prompt": "@image_1 中的女孩对着镜头说了一段开场白，声音像 @Narrator",
  "duration": 8,
  "resolution": "720p",
  "imageUrls": ["https://example.com/girl.png"],
  "voices": [
    {
      "name": "Narrator",
      "audioUrl": "https://example.com/narrator.mp3"
    }
  ]
}
```

**引用已创建的主体与音色素材：**
```json
{
  "prompt": "@Hero 在海边奔跑，回头用 @Narrator 的声音喊出一句台词",
  "duration": 8,
  "resolution": "1080p",
  "elements": [
    { "name": "Hero", "assetId": "kel-20261029083000-a1b2c" }
  ],
  "voices": [
    { "name": "Narrator", "assetId": "kvo-20261029083100-d3e4f" }
  ]
}
```

**完整素材组合（参考图 + 参考视频 + 主体 + 音色）：**
```json
{
  "prompt": "@Hero 坐在 @video_1 的办公桌前，从 @image_1 中拿起玩偶，用 @Narrator 的声音打招呼",
  "duration": 10,
  "resolution": "1080p",
  "imageUrls": ["https://example.com/doll.png"],
  "videoUrls": ["https://example.com/room.mp4"],
  "keepOriginalSound": false,
  "elements": [
    {
      "name": "Hero",
      "imageUrls": [
        "https://example.com/hero-front.jpg",
        "https://example.com/hero-side.jpg"
      ],
      "tag": "character",
      "description": "穿红色外套的年轻人"
    }
  ],
  "voices": [
    {
      "name": "Narrator",
      "audioUrl": "https://example.com/narrator.mp3"
    }
  ]
}
```

#### 响应参数

| 参数 | 类型 | 说明 |
|-----|------|------|
| code | int | 状态码，0 表示成功 |
| msg | string | 状态信息 |
| data.taskId | string | 任务 ID，用于查询任务状态 |
| data.status | string | 任务状态，创建时固定为 `processing` |
| data.createdAt | string | 创建时间 |

#### 响应示例

**成功**
```json
{
  "code": 0,
  "msg": "success",
  "data": {
    "taskId": "task_20261023103000_abc12345",
    "status": "processing",
    "createdAt": "2026-10-23 10:30:00"
  }
}
```

**余额不足**
```json
{
  "code": 40001,
  "msg": "余额不足: 当前余额 0.5000, 需要 0.7500",
  "data": null
}
```

**参数错误**
```json
{
  "code": 10002,
  "msg": "prompt 不能超过 8000 字符",
  "data": null
}
```

---

### 2. 创建 Kling 4.0 关键帧生视频任务

**POST** `/api/v2/open/aigc/kling-4.0-keyframe`

用首帧、中间帧和尾帧生成一段连续视频。不传任何帧时等同于文生视频。

**Content-Type**: `application/json`

#### 请求参数

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| prompt | string | 是 | 视频描述，最多 8000 字符。用 `@first_frame`、`@keyframe_1`、`@keyframe_2`…、`@last_frame` 引用帧 |
| duration | int | 否 | 输出时长 3-30 秒，默认 5。同时限制帧总数，见下方说明 |
| resolution | string | 否 | 输出分辨率：`720p`(默认) / `1080p` |
| aspectRatio | string | 否 | 画幅：`auto` / `16:9` / `9:16` / `1:1` / `21:9`。仅在未传任何帧（文生视频）时生效；传了帧时画幅跟随首帧 |
| firstFrameUrl | string | 条件 | 首帧图片 URL，在 prompt 中用 `@first_frame` 引用 |
| keyframeUrls | string[] | 否 | 中间帧图片 URL，按时间顺序，最多 8 张。对应 `@keyframe_1`、`@keyframe_2`… |
| lastFrameUrl | string | 条件 | 尾帧图片 URL，在 prompt 中用 `@last_frame` 引用 |
| callbackUrl | string | 否 | 任务完成后的回调通知 URL |
| taskNickname | string | 否 | 任务昵称 |

> **说明**：
> - 传了 `keyframeUrls` 或 `lastFrameUrl` 时，`firstFrameUrl` 必填
> - 帧总数（首帧 + 中间帧 + 尾帧）受 `duration` 限制：3 秒最多 4 帧、4 秒 5 帧、5 秒 6 帧、6 秒 7 帧、7 秒 8 帧、8 秒 9 帧、9 秒及以上最多 10 帧
> - prompt 中每个 `@` 引用都必须对应本请求实际传过的帧，否则请求会被拒绝
> - 创建任务时会预扣费，余额不足将返回错误

#### 请求示例

**首尾帧：**
```json
{
  "prompt": "从 @first_frame 的清晨平滑过渡到 @last_frame 的黄昏",
  "duration": 5,
  "resolution": "1080p",
  "firstFrameUrl": "https://example.com/morning.png",
  "lastFrameUrl": "https://example.com/dusk.png"
}
```

**首帧 + 中间帧 + 尾帧：**
```json
{
  "prompt": "@first_frame 中的女孩走出家门，经过 @keyframe_1 的街道，最后抵达 @last_frame 的派对现场",
  "duration": 10,
  "resolution": "720p",
  "firstFrameUrl": "https://example.com/home.png",
  "keyframeUrls": ["https://example.com/street.png"],
  "lastFrameUrl": "https://example.com/party.png"
}
```

**仅首帧：**
```json
{
  "prompt": "@first_frame 中的人物转身走向镜头，镜头缓慢推进",
  "duration": 5,
  "resolution": "720p",
  "firstFrameUrl": "https://example.com/portrait.png"
}
```

#### 响应参数

与参考生视频接口一致（`code` / `msg` / `data.taskId` / `data.status` / `data.createdAt`）。

---

### 3. 主体素材管理

先创建主体素材，再在参考生视频请求的 `elements[].assetId` 里引用。素材只对创建它的账号可见。

#### 3.1 创建主体素材

**POST** `/api/v2/open/kling-4.0/element/create`

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| name | string | 是 | 素材名称，1-20 字符 |
| description | string | 是 | 主体描述，最多 100 字符 |
| imageUrls | string[] | 条件 | 多图主体：2-4 张。第一张为正面图，其余为其他角度或特写，需与正面图有差异。jpg / jpeg / png，单张不超过 10MB，宽高不小于 300px，宽高比 1:2.5 ~ 2.5:1 |
| videoUrl | string | 条件 | 视频角色主体：1 段 3-8 秒、1080P、16:9 或 9:16 的写实人物视频，mp4 / mov，不超过 200MB。与 `imageUrls` 二选一 |
| tag | string | 否 | 主体类别：`character` / `animal` / `prop` / `costume` / `scene` / `effect` / `others`。视频角色主体只能是 `character` |
| voiceAssetId | string | 否 | 绑定音色素材，仅人物主体可用 |

素材是异步创建的：接口最多等待约 15 秒，就绪则直接返回 `succeeded`，否则返回 `processing`，之后用查询接口确认状态。

**请求示例**
```bash
curl -X POST "https://mm-internal-cn.leonecloud.com/api/v2/open/kling-4.0/element/create" \
  -H "Authorization: Bearer your_auth_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Hero",
    "description": "穿红色外套的年轻人",
    "imageUrls": [
      "https://example.com/hero-front.jpg",
      "https://example.com/hero-side.jpg"
    ],
    "tag": "character"
  }'
```

**响应参数**

| 参数 | 类型 | 说明 |
|-----|------|------|
| data.assetId | string | 素材 ID，生视频时填入 `elements[].assetId` |
| data.name | string | 素材名称 |
| data.description | string | 主体描述 |
| data.elementType | string | 主体类型：`image`（多图主体）/ `video`（视频角色主体） |
| data.status | string | `processing` / `succeeded` / `failed` |
| data.failReason | string | 失败原因（`failed` 时返回） |
| data.createdAt | string | 创建时间 |

**响应示例**
```json
{
  "code": 0,
  "msg": "success",
  "data": {
    "assetId": "kel-20261029083000-a1b2c",
    "name": "Hero",
    "description": "穿红色外套的年轻人",
    "elementType": "image",
    "status": "succeeded",
    "createdAt": "2026-10-29 16:30:00"
  }
}
```

#### 3.2 查询主体素材

**GET** `/api/v2/open/kling-4.0/element/get?assetId={assetId}`

响应同创建接口。

#### 3.3 主体素材列表

**GET** `/api/v2/open/kling-4.0/element/list?page=1&pageSize=20`

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| page | int | 是 | 页码，从 1 开始 |
| pageSize | int | 是 | 每页数量，1-100 |

响应 `data` 为 `{ "list": [...], "total": 1, "page": 1, "pageSize": 20 }`，`list` 中每项字段同创建接口。只返回本账号创建的素材，按创建时间倒序。

#### 3.4 删除主体素材

**POST** `/api/v2/open/kling-4.0/element/delete`

```json
{ "assetId": "kel-20261029083000-a1b2c" }
```

删除后不能再被引用；已提交的任务不受影响。

---

### 4. 音色素材管理

先创建音色素材，再在参考生视频请求的 `voices[].assetId` 里引用，或在创建人物主体时通过 `voiceAssetId` 绑定。

#### 4.1 创建音色素材

**POST** `/api/v2/open/kling-4.0/voice/create`

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| name | string | 是 | 素材名称，1-20 字符 |
| audioUrl | string | 是 | 参考音频：5-30 秒，人声干净无杂音且只有一种人声。支持 mp3 / wav / mp4 / mov |

**请求示例**
```bash
curl -X POST "https://mm-internal-cn.leonecloud.com/api/v2/open/kling-4.0/voice/create" \
  -H "Authorization: Bearer your_auth_token_here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Narrator",
    "audioUrl": "https://example.com/narrator.mp3"
  }'
```

响应字段同主体素材（无 `description` / `elementType`），`assetId` 用于 `voices[].assetId`。

#### 4.2 查询 / 列表 / 删除

| 接口 | 说明 |
|-----|------|
| **GET** `/api/v2/open/kling-4.0/voice/get?assetId={assetId}` | 查询单个音色素材 |
| **GET** `/api/v2/open/kling-4.0/voice/list?page=1&pageSize=20` | 音色素材列表 |
| **POST** `/api/v2/open/kling-4.0/voice/delete` | 删除，请求体 `{ "assetId": "..." }` |

参数与响应格式同主体素材接口。

---

### 5. 查询任务状态

**GET** `/api/v2/open/aigc/{taskId}`

查询单个任务的执行状态。

#### 路径参数

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| taskId | string | 是 | 任务 ID |

#### 响应参数

| 参数 | 类型 | 说明 |
|-----|------|------|
| code | int | 状态码，0 表示成功 |
| msg | string | 状态信息 |
| data.taskId | string | 任务 ID |
| data.status | string | 任务状态：`processing` / `success` / `failed` |
| data.result | string[] | 生成的视频 URL 列表（成功时返回） |
| data.errorMsg | string | 错误信息（失败时返回） |
| data.createdAt | string | 创建时间 |
| data.updatedAt | string | 更新时间 |

#### 响应示例

**处理中**
```json
{
  "code": 0,
  "msg": "success",
  "data": {
    "taskId": "task_20261023103000_abc12345",
    "status": "processing",
    "createdAt": "2026-10-23 10:30:00",
    "updatedAt": "2026-10-23 10:30:05"
  }
}
```

**成功**
```json
{
  "code": 0,
  "msg": "success",
  "data": {
    "taskId": "task_20261023103000_abc12345",
    "status": "success",
    "result": [
      "https://fc-gw-sh.oss-accelerate.aliyuncs.com/videos/2026/10/23/output_001.mp4"
    ],
    "createdAt": "2026-10-23 10:30:00",
    "updatedAt": "2026-10-23 10:33:45"
  }
}
```

**失败**
```json
{
  "code": 0,
  "msg": "success",
  "data": {
    "taskId": "task_20261023103000_abc12345",
    "status": "failed",
    "errorMsg": "生成失败：内容不符合规范",
    "createdAt": "2026-10-23 10:30:00",
    "updatedAt": "2026-10-23 10:30:45"
  }
}
```

---

### 6. 批量查询任务状态

**POST** `/api/v2/open/aigc/batch`

批量查询多个任务的执行状态（最多 100 个）。

#### 请求参数

| 参数 | 类型 | 必填 | 说明 |
|-----|------|-----|------|
| taskIds | string[] | 是 | 任务 ID 列表，最多 100 个 |

#### 请求示例

```json
{
  "taskIds": ["task_20261023103000_abc12345", "task_20261023103200_def67890"]
}
```

---

### 7. 查询账户余额

**GET** `/api/v2/open/balance`

查询当前用户的账户余额。

#### 响应示例

```json
{
  "code": 0,
  "msg": "success",
  "data": {
    "userId": "user@example.com",
    "balance": "19.9250",
    "frozenBalance": "1.5000",
    "currency": "USD"
  }
}
```

---

## 回调通知

当任务完成（成功或失败）时，如果创建任务时提供了 `callbackUrl`，系统会向该 URL 发送 POST 请求。

### 回调请求

**Headers**
```
Content-Type: application/json
X-Funcloud-Event: task.completed
X-Funcloud-Signature: {签名}
```

**Body**
```json
{
  "event": "task.completed",
  "taskId": "task_20261023103000_abc12345",
  "status": "success",
  "result": ["https://fc-gw-sh.oss-accelerate.aliyuncs.com/videos/output_001.mp4"],
  "errorMsg": "",
  "timestamp": "2026-10-23T10:33:45+08:00",
  "signature": "a1b2c3d4e5f6..."
}
```

### 回调响应

接收方应返回 HTTP 2xx 状态码表示成功接收：

```json
{
  "code": 0,
  "msg": "ok"
}
```

---

## 错误码

| code | 说明 |
|------|------|
| 0 | 成功 |
| 10002 | 参数缺失或格式错误 |
| 10005 | API Key 无效或缺失 |
| 30003 | 任务不存在 |
| 40001 | 余额不足 |
| 60001 | 服务暂未开放 |
| 90003 | 服务器内部错误 |

---

## 最佳实践

### 1. 轮询策略

建议的轮询间隔：
- 前 30 秒：每 3 秒查询一次
- 30 秒 ~ 3 分钟：每 5 秒查询一次
- 3 分钟后：每 10 秒查询一次

### 2. 使用回调

对于生产环境，建议使用回调通知而非轮询，可以：
- 减少 API 调用次数
- 更快获得结果通知
- 降低服务器压力

### 3. 处理时间参考

- 720p（5s）：通常 1 ~ 2 分钟
- 1080p（5s）：通常 2 ~ 3 分钟
- 时长越长，处理时间越长（大约按比例增加）
- 带参考视频或视频主体的任务会比纯文生稍慢

### 4. 余额管理

- 创建任务前建议先查询余额，避免因余额不足导致任务失败
- 任务成功后会从冻结余额中扣费
- 任务失败后冻结金额会自动退还到可用余额

### 5. 两种生成方式怎么选

- **参考生视频**：想让画面里出现指定人物、道具、场景，或想复刻一段运动/镜头
- **关键帧生视频**：已经确定了关键画面的构图，需要模型把几张图之间补成连续动作

### 6. 参考素材使用

- 参考图按数组顺序对应 `@image_1`、`@image_2`…，顺序就是引用编号
- 参考视频与视频主体合计不超过 5 段、总时长不超过 30 秒
- 人物主体建议给 2-4 张不同角度的图，第一张为主视角（正脸）
- 视频主体必须是单镜头、3-8 秒的连续片段，有剪辑会被拒绝
- 同一个人物/音色要在多条任务里复用时，建议先创建素材再用 `assetId` 引用，省去每次上传，形象也更稳定

### 7. 关键帧使用

- 中间帧按时间顺序传入，顺序决定画面演进的节奏
- 帧数受时长限制：5 秒最多 6 帧，10 秒最多 10 帧
- 传了帧之后画幅由首帧决定，此时 `aspectRatio` 不再生效
