> ## Documentation Index
> Fetch the complete documentation index at: https://docs.comfy.org/llms.txt
> Use this file to discover all available pages before exploring further.

# 通过 Comfy Router 使用 Kling Image 4.0

> 通过 Comfy Router 调用 kling/kling-image-4.0：端点、请求形状以及 Router 返回的响应。

`kling/kling-image-4.0` 的 API 参考，由 Comfy Router 从 Kling 提供。

**输入：** 文本、图像 · **输出：** 图像

## 快速开始

在[你的 Comfy 工作区](https://platform.comfy.org/profile/api-keys?onboarding=router)中创建密钥，并将其导出为 `COMFY_API_KEY`。Python 和 TypeScript 片段使用 Comfy SDK（`pip install comfy-sdk` 和 `npm install @comfyorg/sdk`）；cURL 片段则是通过原始 HTTP 执行的同一调用。

**模型 ID：** `kling/kling-image-4.0`

**端点：** `POST https://api.comfy.org/v2/models/kling/kling-image-4.0`

> [tab] 等待结果
>
> ```python Python theme={null}
> from comfy_sdk import Comfy
>
> # 从环境中读取 COMFY_API_KEY。
> # SDK 会自动创建幂等键，并在自动重试时复用它。
> with Comfy() as client:
>     result = client.models.run(
>         "kling/kling-image-4.0",
>         {
>             "contents": [
>                 {
>                     "text": "A knitted fox asleep on a pile of old books, soft window light.",
>                     "type": "prompt",
>                 },
>             ],
>             "settings": {
>                 "aspect_ratio": "1:1",
>                 "n": 1,
>                 "resolution": "2k",
>                 "result_type": "single",
>             },
>         },
>     )
>
> print(result)
> ```
>
> ```typescript TypeScript theme={null}
> import { comfy } from "@comfyorg/sdk";
>
> // 从环境中读取 COMFY_API_KEY。
> // SDK 会自动创建幂等键，并在自动重试时复用它。
> const { data } = await comfy.models.run("kling/kling-image-4.0", {
>   contents: [
>     {
>       text: "A knitted fox asleep on a pile of old books, soft window light.",
>       type: "prompt",
>     },
>   ],
>   settings: {
>     aspect_ratio: "1:1",
>     n: 1,
>     resolution: "2k",
>     result_type: "single",
>   },
> });
>
> console.log(data);
> ```
>
> ```bash cURL theme={null}
> curl https://api.comfy.org/v2/models/kling/kling-image-4.0 \
>   -H "X-API-Key: $COMFY_API_KEY" \
>   -H "Idempotency-Key: $(uuidgen)" \
>   -H "Content-Type: application/json" \
>   -d "{\"contents\": [{\"text\":\"A knitted fox asleep on a pile of old books, soft window light.\",\"type\":\"prompt\"}], \"settings\": {\"aspect_ratio\":\"1:1\",\"n\":1,\"resolution\":\"2k\",\"result_type\":\"single\"}}"
> ```

> [tab] 加入队列并稍后收集
>
> 相同的请求体，发送到 `POST https://api.comfy.org/v2/models/kling/kling-image-4.0/requests`。运行一旦被接纳，Router 就会以 `201` 返回 `request_id`，结果准备就绪后，可从当前进程或另一个进程收集。[队列交付](https://docs.comfy.org/zh/development/comfy-router/queue.md) 介绍了状态、取消和结果收集。
>
> ```python Python theme={null}
> import asyncio
> from comfy_sdk import AsyncComfy
>
> # 从环境中读取 COMFY_API_KEY。
> # 每次 submit() 调用都会生成自己的 Idempotency-Key，并在自动重试时复用它。
> async def main():
>     async with AsyncComfy() as client:
>         handle = await client.models.submit(
>             "kling/kling-image-4.0",
>             {
>                 "contents": [
>                     {
>                         "text": "A knitted fox asleep on a pile of old books, soft window light.",
>                         "type": "prompt",
>                     },
>                 ],
>                 "settings": {
>                     "aspect_ratio": "1:1",
>                     "n": 1,
>                     "resolution": "2k",
>                     "result_type": "single",
>                 },
>             },
>         )
>         print("request_id:", handle.request_id)  # 加上模型 ID，就是另一个进程所需的全部信息
>
>         # 轮询直到请求完成，等待服务器指定的 Retry-After。
>         async for update in handle.iter_events():
>             print(update.status, update.queue_position)
>
>         # 提供商自身的负载，与 models.run() 返回的值相同。
>         # 失败或已取消的请求会在此处抛出类型化的 Router 错误。
>         result = await handle.get()
>
>     print(result)
>
> asyncio.run(main())
> ```
>
> ```typescript TypeScript theme={null}
> import { comfy } from "@comfyorg/sdk";
>
> // 从环境中读取 COMFY_API_KEY。
> // 每次 submit() 调用都会生成自己的 Idempotency-Key，并在自动重试时复用它。
> const handle = await comfy.models.submit("kling/kling-image-4.0", {
>   contents: [
>     {
>       text: "A knitted fox asleep on a pile of old books, soft window light.",
>       type: "prompt",
>     },
>   ],
>   settings: {
>     aspect_ratio: "1:1",
>     n: 1,
>     resolution: "2k",
>     result_type: "single",
>   },
> });
> console.log("requestId:", handle.requestId); // 加上模型 ID，就是另一个进程所需的全部信息
>
> // 轮询直到请求完成，等待服务器指定的 Retry-After。
> for await (const update of handle.events()) {
>   console.log(update.status, update.queuePosition);
> }
>
> // 与 models.run() 返回的结果相同。失败或已取消的请求会在此处被拒绝。
> const result = await handle.get();
>
> console.log(result.data);
> ```
>
> ```bash cURL theme={null}
> # 1. 提交。Router 会以 201 返回 request_id、status_url、response_url 和 cancel_url。
> curl https://api.comfy.org/v2/models/kling/kling-image-4.0/requests \
>   -H "X-API-Key: $COMFY_API_KEY" \
>   -H "Idempotency-Key: $(uuidgen)" \
>   -H "Content-Type: application/json" \
>   -d "{\"contents\": [{\"text\":\"A knitted fox asleep on a pile of old books, soft window light.\",\"type\":\"prompt\"}], \"settings\": {\"aspect_ratio\":\"1:1\",\"n\":1,\"resolution\":\"2k\",\"result_type\":\"single\"}}"
>
> # 2. 轮询直到状态为 COMPLETED，每次响应都会指定需要等待的 Retry-After 秒数。
> REQUEST_ID="<request_id from the 201 body>"
> curl -i https://api.comfy.org/v2/models/kling/kling-image-4.0/requests/$REQUEST_ID/status \
>   -H "X-API-Key: $COMFY_API_KEY"
>
> # 3. 收集。200 表示模型的原生输出，202 表示仍在运行时返回状态正文。
> curl https://api.comfy.org/v2/models/kling/kling-image-4.0/requests/$REQUEST_ID \
>   -H "X-API-Key: $COMFY_API_KEY"
> ```

## Schema

### 输入

**contents** `object[]` *required*

提示词以及最多 10 张参考图像和元素。

**contents\[].element\_id** `string`

元素 ID，当 type 为 "element" 时使用。仅支持多图像元素。

**contents\[].id** `string`

该输入的参考 ID，在提示词中用作 @id。必须在任务内唯一。

**contents\[].text** `string`

文本提示词，当 type 为 "prompt" 时使用。最多 50,000 个英文字符或 21,000 个非英文字符。通过 @id 引用其他输入。

**contents\[].type** `string` *required*

输入类型。取值为 "prompt"、"refer\_image" 或 "element" 之一。必须包含一个 prompt 项。参考图像和元素合计最多 10 个。

可能的值：`prompt`、`refer_image`、`element`

**contents\[].url** `string`

图片网址或 Base64 数据，当 type 为 "refer\_image" 时使用。图像为 .jpg、.jpeg 或 .png 格式，最大 30MB，每边至少 300px，宽高比在 2:5 到 5:2 之间。

**options** `object`

常规配置，例如水印选项。Kling 4.0 不支持 `options.callback_url` 和 `options.external_task_id`；如果请求在 `options` 中设置其中任意一个，Comfy Router 会拒绝该请求。顶层的 `callback_url` 或 `external_task_id` 不属于此 schema，会在请求到达 Kling 之前被移除。

**options.watermark\_info** `object`

是否同时生成带水印的结果。不支持自定义水印。显式传入的 null 会被视为未提供，与 /proxy 的 Kling 4.0 检查以及 Kling 的处理方式一致。

**options.watermark\_info.enabled** `boolean`

true 表示生成带水印的结果，false 表示不生成。默认 false。

**settings** `object`

输出配置，例如结果类型、图像数量、分辨率和宽高比。

**settings.aspect\_ratio** `string`

已生成图像的宽高比（宽度:高度）。默认 "auto"，即跟随输入。

可能的值：`16:9`、`9:16`、`1:1`、`4:3`、`3:4`、`3:2`、`2:3`、`21:9`、`auto`

**settings.n** `integer`

单图模式下独立图像的数量，1 到 9。默认 1。系列模式下忽略。

范围：`1` 到 `9`

**settings.resolution** `string`

输出分辨率。取值为 "2k"、"4k" 或 "8k" 之一。默认 "2k"。

可能的值：`2k`、`4k`、`8k`

**settings.result\_type** `string`

取值为 "single"（独立图像，由 `n` 计数）或 "series"（一组相关图像，由 `series_amount` 计数）之一。默认 "single"。

可能的值：`single`、`series`

**settings.series\_amount** `integer | `auto\`\`

一组图像的数量，2 到 10，或 "auto" 表示由 Kling 根据输入在 2 到 10 之间选择。默认 4。仅在系列模式下使用。

范围：`2` 到 `10`

根据 Router 在 `GET /v2/models/kling/kling-image-4.0/openapi.json` 提供的 schema 生成，这也是它在请求到达提供商之前校验调用时所依据的同一份文档。

### 输出

**code** `integer`

错误码。0 表示成功。

**data** `object[]`

符合查询条件的任务。

**data\[].billing** `object[]`

任务的计费详情。

**data\[].billing\[].amount** `string`

消费金额，精确到小数点后两位。

**data\[].billing\[].cash\_type** `string`

扣费所使用的现金账户（仅当 charge\_type 为 "cash" 时存在），例如 "balance"。部分任务会返回该字段，其他任务可能省略。

**data\[].billing\[].charge\_type** `string`

消费账户类型。"cash" 表示余额，"unit" 表示资源包。

**data\[].billing\[].currency** `string`

`amount` 和 `list_price` 的 ISO 4217 货币代码，例如 "USD"。部分任务会返回该字段，其他任务可能省略。

**data\[].billing\[].list\_price** `string`

任务在未享受任何折扣前的标价，以十进制字符串表示。部分任务会返回该字段，其他任务可能省略。

**data\[].billing\[].package\_type** `string`

可消耗资源包类型（仅当 charge\_type 为 "unit" 时存在）。取值为 "video"、"image" 或 "audio" 之一。

**data\[].create\_time** `integer`

任务创建时间。Unix 时间戳，单位为毫秒。

格式：`int64`

**data\[].external\_id** `string`

该任务的自定义任务 ID（如有）。

**data\[].id** `string`

任务 ID。

**data\[].message** `string`

任务状态信息，当任务失败时显示失败原因。

**data\[].outputs** `object[]`

该任务的已生成输出。

**data\[].outputs\[].duration** `string`

已生成视频的时长，单位为秒。

**data\[].outputs\[].group\_id** `string`

分组标记，仅已分组的图像会返回。

**data\[].outputs\[].id** `string`

系统生成的输出 ID。

**data\[].outputs\[].mp3\_duration** `string`

已生成 MP3 音频的时长，单位为秒。

**data\[].outputs\[].mp3\_url** `string`

已生成音频的 MP3 URL（受防盗链保护）。

**data\[].outputs\[].name** `string`

已生成素材的名称。

**data\[].outputs\[].owned\_by** `string`

素材来源。"kling" 表示官方素材库；数字为创作者 ID。

**data\[].outputs\[].status** `string`

素材状态。取值为 "succeeded" 或 "deleted" 之一。

**data\[].outputs\[].type** `string`

输出内容类型。取值为 "video"、"image"、"audio"、"voice" 或 "element" 之一。

**data\[].outputs\[].url** `string`

已生成结果的 URL（受防盗链保护）。30 天后清除。

**data\[].outputs\[].watermark\_url** `string`

带水印结果的 URL（受防盗链保护）。

**data\[].outputs\[].wav\_duration** `string`

已生成 WAV 音频的时长，单位为秒。

**data\[].outputs\[].wav\_url** `string`

已生成音频的 WAV URL（受防盗链保护）。

**data\[].status** `string`

任务状态。取值为 "submitted"、"processing"、"succeeded" 或 "failed" 之一。

**data\[].update\_time** `integer`

任务更新时间。Unix 时间戳，单位为毫秒。

格式：`int64`

**message** `string`

报错信息。

**request\_id** `string`

系统生成的请求 ID。

## 示例

### 输入

```json theme={null}
{
  "contents": [
    {
      "text": "A knitted fox asleep on a pile of old books, soft window light.",
      "type": "prompt"
    }
  ],
  "settings": {
    "aspect_ratio": "1:1",
    "n": 1,
    "resolution": "2k",
    "result_type": "single"
  }
}
```

### 输出

```json theme={null}
{
  "code": 0,
  "data": [
    {
      "create_time": 1798761600000,
      "id": "kling-v2-task-7c8d9e0f1a2b",
      "message": "",
      "outputs": [
        {
          "duration": "5",
          "id": "kling-v2-output-2b1a0f9e8d7c",
          "type": "video",
          "url": "https://example.invalid/kling/v2/generated.mp4"
        }
      ],
      "status": "succeeded",
      "update_time": 1798761820000
    }
  ],
  "message": "SUCCEED",
  "request_id": "3d7e5c91-0b42-4f68-9a13-8e2c6d4b0a75"
}
```

## 发布前须知

SDK 会生成 `Idempotency-Key` 并在自动重试中复用它。手动重试时，请复用原始 key。Router 最长可保持连接 10 分钟。

请求失败时，Router 会发送 `X-Comfy-Error-Type` 响应头说明原因。`422` 表示 Router 在调用提供商之前就拒绝了输入，`413` 表示请求体超出了 Router 可接受的大小。已生成的资源请及时下载，因为[结果 URL 会过期](https://docs.comfy.org/zh/development/comfy-router/reference.md#结果资产)。

上文任何字段描述中提到的尺寸限制，都是提供商对该字段自身的限定，引自提供商的规范。Router 会对整个请求体另行设置上限，base64 编码的媒体内容也计入其中：参见[请求体大小](https://docs.comfy.org/zh/development/comfy-router/limitations.md)。

本页记录的是通过 Comfy Router 调用的某一个合作伙伴模型。同一个 `comfy-sdk` / `@comfyorg/sdk` 包还提供第二个客户端，用于在 Comfy Cloud 上运行完整的 ComfyUI 工作流图：`Comfy(api_key=...)` / `new Comfy({ apiKey })`，并带有 `client.workflows`、`client.assets` 和 `client.jobs`。请参阅 [Comfy SDKs](https://docs.comfy.org/zh/development/api-development/sdks.md)。

> [card] [请求头](https://docs.comfy.org/zh/development/comfy-router/headers.md)
>
> 身份验证、幂等性、请求 ID、错误分类、重试节奏、消费限额。

> [card] [使用 Router API](https://docs.comfy.org/zh/development/comfy-router/api.md)
>
> 模型发现、验证错误、重试与计费。

> [card] [限制](https://docs.comfy.org/zh/development/comfy-router/limitations.md)
>
> Router 目前不支持的功能，以及替代方案。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.