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

# Criar uma tarefa de Kling Motion Control

> Crie uma tarefa de Kling Motion Control a partir de uma imagem de personagem e um vídeo de movimento de referência com a rota compatível da CometAPI.

Use este endpoint para criar uma tarefa de Motion Control a partir de uma imagem de personagem e um
vídeo de referência.

<Warning>
  Esta página descreve a rota compatível de Motion Control. O Kling Video 3.0
  Motion Control usa um contrato de API separado.
</Warning>

## Mídia obrigatória

`image_url` aceita uma URL pública ou uma string Base64 bruta.

* Use uma imagem JPG, JPEG ou PNG de 10 MB ou menos.
* Defina cada dimensão da imagem entre 300 e 65.536 pixels.
* Use uma proporção de aspecto entre 1:2,5 e 2,5:1.
* Envie o Base64 como a string codificada bruta, sem um
  `data:image/...;base64,` prefixo.
* Mostre um único personagem sem obstruções, com enquadramento corporal que corresponda à
  referência de movimento.

`video_url` aceita uma URL pública de MP4 ou MOV.

* Use um vídeo de 100 MB ou menos.
* Defina a borda menor com pelo menos 340 pixels.
* Defina a borda maior com no máximo 3.850 pixels.
* Use uma tomada contínua com um personagem visível.
* Evite cortes, mudanças de câmera e movimentos excessivamente rápidos.

<Note>
  Siga os limites de duração e verifique o `task_status` terminal aninhado. Uma
  resposta HTTP 200 externa ou `code: 0` confirma a resposta da consulta, e não um
  resultado de geração bem-sucedido.
</Note>

## Defina o valor de orientação

`character_orientation` é obrigatório e aceita `image` ou `video`.

| Valor   | Duração do vídeo de referência |
| ------- | ------------------------------ |
| `image` | 3–10 segundos                  |
| `video` | 3–30 segundos                  |

Se você usar `element_list`, defina `character_orientation` como `video`.

## Escolha o modelo e o modo

A rota compatível aceita `kling-v2-6` e `kling-v3`. Ambos os valores de modelo
aceitam ambos os valores de modo:

| Modelo       | `std`  | `pro`  |
| ------------ | ------ | ------ |
| `kling-v2-6` | Aceito | Aceito |
| `kling-v3`   | Aceito | Aceito |

Se você omitir `model_name`, a solicitação usará `kling-v2-6`. Se você omitir `mode`,
a solicitação usará `std`. O valor `kling-v3` mantém o formato da solicitação compatível
descrito nesta página; ele não seleciona o contrato separado de versão de caminho do Kling 3.0
.

O contrato compatível não garante uma resolução de saída fixa. Verifique
cada vídeo retornado caso sua aplicação exija dimensões específicas.

`keep_original_sound` aceita `yes` ou `no`. Se você omitir este campo, a
solicitação usará `yes`.

## Fluxo da tarefa

<Steps>
  <Step title="Enviar a solicitação de Motion Control">
    Envie a imagem de origem, o vídeo de referência e o valor de orientação. Selecione um
    modelo, modo e valor de som ou use os respectivos padrões documentados. Armazene o
    `task_id` retornado.
  </Step>

  <Step title="Consultar a tarefa">
    Use [Obter uma tarefa Kling](./individual-queries) com o `task_id` retornado.
    Continue até que o status seja `succeed` ou `failed`.
  </Step>

  <Step title="Armazenar o resultado">
    Baixe e armazene o resultado imediatamente. A documentação da API compatível da Kling
    informa que os vídeos gerados são apagados após 30 dias. Não
    presuma que a URL retornada permanecerá acessível durante todos os 30 dias.
  </Step>
</Steps>

## Campos opcionais

| Campo              | Estrutura                                           | Restrição                                                                                                |
| ------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `prompt`           | String, máximo de 2500 caracteres                   | Campo de texto opcional na estrutura de solicitação compatível.                                          |
| `callback_url`     | String de URI ou string vazia                       | Omita o campo ou use uma string vazia quando nenhuma URI de callback estiver configurada.                |
| `external_task_id` | String exclusiva para sua conta                     | Correlaciona a tarefa com sua aplicação. Não substitui o `task_id` retornado para consultas da CometAPI. |
| `element_list`     | Array com no máximo um objeto `{"element_id": 123}` | Combine este campo somente com `character_orientation: "video"`.                                         |
| `watermark_info`   | `{"enabled": boolean}`                              | A estrutura de marca d'água compatível contém somente o Boolean `enabled`.                               |

## Estrutura de callback

O esquema de callback Legacy tem a seguinte estrutura:

```json theme={null}
{
  "task_id": "<task_id>",
  "task_status": "succeed",
  "task_status_msg": "",
  "created_at": 1785398400000,
  "updated_at": 1785398460000,
  "final_unit_deduction": "<value>",
  "final_balance_deduction": {
    "quota": "<value>",
    "list_price": "<value>"
  },
  "task_info": {
    "external_task_id": "<your_unique_id>"
  },
  "task_result": {
    "videos": [
      {
        "id": "<video_id>",
        "url": "https://media.example.com/<file_id>.mp4",
        "duration": "6.4"
      }
    ]
  }
}
```

O status do callback pode ser `submitted`, `processing`, `succeed` ou `failed`.
Os campos de resultado terminal estão presentes somente quando são retornados para o estado terminal.

## Campos de resultado

| Campo                                | Tipo                                      | Descrição                                                              |
| ------------------------------------ | ----------------------------------------- | ---------------------------------------------------------------------- |
| `task_result.videos[].id`            | String                                    | ID do vídeo gerado.                                                    |
| `task_result.videos[].url`           | String de URI                             | URL de entrega do vídeo gerado.                                        |
| `task_result.videos[].watermark_url` | String de URI                             | URL de entrega do vídeo com marca d'água quando a tarefa retornar uma. |
| `task_result.videos[].duration`      | String                                    | Duração do vídeo gerado em segundos.                                   |
| `final_unit_deduction`               | String                                    | Valor final de dedução de unidades retornado com a tarefa.             |
| `final_balance_deduction`            | `{"quota": string, "list_price": string}` | Valores finais de dedução de saldo retornados com a tarefa.            |

O status da tarefa é `submitted`, `processing`, `succeed` ou `failed`.

<Tip>
  Consulte a [referência da API de Kling Motion Control](https://kling.ai/document-api/api/video/motion-control/legacy)
  e o [protocolo de callback da Kling](https://kling.ai/document-api/api/get-started/callbacks)
  para obter detalhes da API.
</Tip>


## OpenAPI

````yaml api/openapi/video/kling/post-motion-control.openapi.json POST /kling/v1/videos/motion-control
openapi: 3.1.0
info:
  title: Kling Motion Control API
  version: 1.0.0
  description: >-
    Create a Kling Motion Control task from a character image and a reference
    motion video.
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /kling/v1/videos/motion-control:
    post:
      summary: Create a Kling Motion Control task
      description: >-
        Submit a character image and a reference motion video. The response
        contains a task ID that you can use for status queries.
      operationId: create_kling_motion_control
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - image_url
                - video_url
                - character_orientation
              properties:
                model_name:
                  type: string
                  description: >-
                    Model ID for this compatible Motion Control request. Omit
                    this field to use `kling-v2-6`. The `kling-v3` value keeps
                    this compatible request shape; it does not select the
                    separate Kling 3.0 path-version contract.
                  enum:
                    - kling-v2-6
                    - kling-v3
                  default: kling-v2-6
                image_url:
                  type: string
                  description: >-
                    Character image as a public URL or a raw Base64 string. Send
                    raw Base64 without a `data:image/...;base64,` prefix;
                    data-URI input is outside the compatible contract. Supported
                    formats are JPG, JPEG, and PNG. The image must be 10 MB or
                    smaller. Its width and height must each be from 300 through
                    65,536 pixels, and its aspect ratio must be between 1:2.5
                    and 2.5:1.
                video_url:
                  type: string
                  format: uri
                  description: >-
                    Public reference motion video URL. Use an MP4 or MOV file
                    that is 100 MB or smaller. The short edge must be at least
                    340 pixels, and the long edge must not exceed 3850 pixels.
                    The video must be at least 3 seconds long. The maximum
                    duration depends on `character_orientation`.
                prompt:
                  type: string
                  maxLength: 2500
                  description: >-
                    Optional text field in the compatible request structure.
                    Maximum 2500 characters.
                keep_original_sound:
                  type: string
                  description: >-
                    Compatible string enum. Accepted values are `yes` and `no`.
                    Omitted requests use `yes`.
                  enum:
                    - 'yes'
                    - 'no'
                  default: 'yes'
                character_orientation:
                  type: string
                  description: >-
                    Required compatible string enum. With `image`, the reference
                    video can be 3 to 10 seconds long. With `video`, the
                    reference video can be 3 to 30 seconds long.
                  enum:
                    - image
                    - video
                mode:
                  type: string
                  description: >-
                    Both compatible models accept `std` and `pro`. Omitted
                    requests use `std`.
                  enum:
                    - std
                    - pro
                  default: std
                callback_url:
                  description: >-
                    Optional callback field in the compatible structure. Provide
                    a URI, or omit the field or send an empty string when no
                    callback URI is configured.
                  oneOf:
                    - type: string
                      format: uri
                    - type: string
                      const: ''
                external_task_id:
                  type: string
                  description: >-
                    Optional ID for correlation in your application. The value
                    must be unique for your account. Store the returned
                    `task_id` for CometAPI status queries.
                element_list:
                  type: array
                  maxItems: 1
                  description: >-
                    Optional compatible Element structure. Provide at most one
                    object, and combine this field only with
                    `character_orientation: video`.
                  items:
                    type: object
                    required:
                      - element_id
                    properties:
                      element_id:
                        type: integer
                        format: int64
                        description: Kling Element ID in the compatible structure.
                    additionalProperties: false
                watermark_info:
                  type: object
                  description: Optional compatible watermark structure.
                  required:
                    - enabled
                  properties:
                    enabled:
                      type: boolean
                      description: Boolean flag in the compatible watermark structure.
                  additionalProperties: false
              example:
                model_name: kling-v3
                image_url: https://your-image-host.example.com/character.png
                video_url: https://your-video-host.example.com/reference-motion.mp4
                prompt: Studio scene.
                keep_original_sound: 'no'
                character_orientation: video
                mode: std
            examples:
              Image URL:
                summary: Use a public character image URL
                value:
                  model_name: kling-v3
                  image_url: https://your-image-host.example.com/character.png
                  video_url: https://your-video-host.example.com/reference-motion.mp4
                  prompt: Studio scene.
                  keep_original_sound: 'no'
                  character_orientation: video
                  mode: std
              Image base64:
                summary: Use a raw Base64 character image
                value:
                  model_name: kling-v3
                  image_url: <your-image-base64>
                  video_url: https://your-video-host.example.com/reference-motion.mp4
                  prompt: Studio scene.
                  keep_original_sound: 'no'
                  character_orientation: video
                  mode: pro
      responses:
        '200':
          description: Task accepted.
          content:
            application/json:
              schema:
                type: object
                required:
                  - code
                  - message
                  - data
                properties:
                  code:
                    type: integer
                    description: >-
                      Response code. A value of 0 indicates that the request was
                      accepted.
                  message:
                    type: string
                    description: Response message.
                  data:
                    type: object
                    required:
                      - task_id
                      - task_status
                      - task_info
                      - created_at
                      - updated_at
                    properties:
                      task_id:
                        type: string
                        description: System-generated task ID for status queries.
                      task_status:
                        type: string
                        description: Task state after submission.
                        const: submitted
                      task_status_msg:
                        type: string
                        description: Status detail when returned.
                      task_info:
                        type: object
                        description: Additional task metadata. The object can be empty.
                        additionalProperties: true
                      created_at:
                        type: integer
                        format: int64
                        description: Task creation timestamp in milliseconds.
                      updated_at:
                        type: integer
                        format: int64
                        description: Last task update timestamp in milliseconds.
                example:
                  code: 0
                  message: SUCCEED
                  data:
                    task_id: <task_id>
                    task_status: submitted
                    task_info: {}
                    created_at: 1785398400000
                    updated_at: 1785398400000
      x-codeSamples:
        - lang: Shell
          label: Image URL
          source: |
            curl https://api.cometapi.com/kling/v1/videos/motion-control \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model_name": "kling-v3",
                "image_url": "https://your-image-host.example.com/character.png",
                "video_url": "https://your-video-host.example.com/reference-motion.mp4",
                "prompt": "Studio scene.",
                "keep_original_sound": "no",
                "character_orientation": "video",
                "mode": "std"
              }'
        - lang: Python
          label: Image URL
          source: |
            import os
            import requests

            response = requests.post(
                "https://api.cometapi.com/kling/v1/videos/motion-control",
                headers={"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]},
                json={
                    "model_name": "kling-v3",
                    "image_url": "https://your-image-host.example.com/character.png",
                    "video_url": "https://your-video-host.example.com/reference-motion.mp4",
                    "prompt": "Studio scene.",
                    "keep_original_sound": "no",
                    "character_orientation": "video",
                    "mode": "std",
                },
            )

            result = response.json()
            print(result.get("code"), result.get("data", {}).get("task_id"))
        - lang: JavaScript
          label: Image URL
          source: |
            const response = await fetch(
              "https://api.cometapi.com/kling/v1/videos/motion-control",
              {
                method: "POST",
                headers: {
                  Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  model_name: "kling-v3",
                  image_url: "https://your-image-host.example.com/character.png",
                  video_url: "https://your-video-host.example.com/reference-motion.mp4",
                  prompt: "Studio scene.",
                  keep_original_sound: "no",
                  character_orientation: "video",
                  mode: "std",
                }),
              },
            );

            const result = await response.json();
            console.log(result.code, result.data?.task_id);
        - lang: Shell
          label: Image base64
          source: |
            curl https://api.cometapi.com/kling/v1/videos/motion-control \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              --data-binary @- <<'JSON'
            {
              "model_name": "kling-v3",
              "image_url": "<base64-encoded-png>",
              "video_url": "https://your-video-host.example.com/reference-motion.mp4",
              "prompt": "Studio scene.",
              "keep_original_sound": "no",
              "character_orientation": "video",
              "mode": "pro"
            }
            JSON
        - lang: Python
          label: Image base64
          source: |
            import base64
            import os
            import requests

            with open("character.png", "rb") as image_file:
                image_base64 = base64.b64encode(image_file.read()).decode("ascii")

            response = requests.post(
                "https://api.cometapi.com/kling/v1/videos/motion-control",
                headers={"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]},
                json={
                    "model_name": "kling-v3",
                    "image_url": image_base64,
                    "video_url": "https://your-video-host.example.com/reference-motion.mp4",
                    "prompt": "Studio scene.",
                    "keep_original_sound": "no",
                    "character_orientation": "video",
                    "mode": "pro",
                },
            )

            result = response.json()
            print(result.get("code"), result.get("data", {}).get("task_id"))
        - lang: JavaScript
          label: Image base64
          source: >
            import { readFile } from "node:fs/promises";


            const imageBase64 = (await
            readFile("character.png")).toString("base64");

            const response = await fetch(
              "https://api.cometapi.com/kling/v1/videos/motion-control",
              {
                method: "POST",
                headers: {
                  Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({
                  model_name: "kling-v3",
                  image_url: imageBase64,
                  video_url: "https://your-video-host.example.com/reference-motion.mp4",
                  prompt: "Studio scene.",
                  keep_original_sound: "no",
                  character_orientation: "video",
                  mode: "pro",
                }),
              },
            );


            const result = response.json();

            console.log(result.code, result.data?.task_id);
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Bearer authentication. Use your CometAPI API key.

````