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

# Generación de video Kling v3 Omni

>  - Modo de procesamiento asíncrono, devuelve un ID de tarea para consultas posteriores
- Interfaz unificada text-to-video/image-to-video con sintaxis de referencia de imágenes
- Admite el modo estándar (720P), modo profesional (1080P) y modo 4K
- Referencia imágenes en los prompts usando la sintaxis image_N
- Admite la generación de videos con audio (mutuamente excluyente con video_list) 

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/videos/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "kling-v3-omni",
      "prompt": "Make the person in <<<image_1>>> wave at the camera",
      "image_urls": ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
      "mode": "std",
      "duration": 5,
      "aspect_ratio": "16:9"
    }'
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.apimart.ai/v1/videos/generations"

  payload = {
      "model": "kling-v3-omni",
      "prompt": "Make the person in <<<image_1>>> wave at the camera",
      "image_urls": ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
      "mode": "std",
      "duration": 5,
      "aspect_ratio": "16:9"
  }

  headers = {
      "Authorization": "Bearer <token>",
      "Content-Type": "application/json"
  }

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

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1/videos/generations";

  const payload = {
    model: "kling-v3-omni",
    prompt: "Make the person in <<<image_1>>> wave at the camera",
    image_urls: ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
    mode: "std",
    duration: 5,
    aspect_ratio: "16:9"
  };

  const headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
  };

  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload)
  })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io/ioutil"
      "net/http"
  )

  func main() {
      url := "https://api.apimart.ai/v1/videos/generations"

      payload := map[string]interface{}{
          "model":        "kling-v3-omni",
          "prompt":       "Make the person in <<<image_1>>> wave at the camera",
          "image_urls":   []string{"https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"},
          "mode":         "std",
          "duration":     5,
          "aspect_ratio": "16:9",
      }

      jsonData, _ := json.Marshal(payload)

      req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer <token>")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()

      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  public class Main {
      public static void main(String[] args) throws Exception {
          String url = "https://api.apimart.ai/v1/videos/generations";

          String payload = """
          {
            "model": "kling-v3-omni",
            "prompt": "Make the person in <<<image_1>>> wave at the camera",
            "image_urls": ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
            "mode": "std",
            "duration": 5,
            "aspect_ratio": "16:9"
          }
          """;

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <token>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(payload))
              .build();

          HttpResponse<String> response = client.send(request,
              HttpResponse.BodyHandlers.ofString());

          System.out.println(response.body());
      }
  }
  ```

  ```php PHP theme={null}
  <?php

  $url = "https://api.apimart.ai/v1/videos/generations";

  $payload = [
      "model" => "kling-v3-omni",
      "prompt" => "Make the person in <<<image_1>>> wave at the camera",
      "image_urls" => ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
      "mode" => "std",
      "duration" => 5,
      "aspect_ratio" => "16:9"
  ];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer <token>",
      "Content-Type: application/json"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

  url = URI("https://api.apimart.ai/v1/videos/generations")

  payload = {
    model: "kling-v3-omni",
    prompt: "Make the person in <<<image_1>>> wave at the camera",
    image_urls: ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
    mode: "std",
    duration: 5,
    aspect_ratio: "16:9"
  }

  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 = payload.to_json

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

  ```swift Swift theme={null}
  import Foundation

  let url = URL(string: "https://api.apimart.ai/v1/videos/generations")!

  let payload: [String: Any] = [
      "model": "kling-v3-omni",
      "prompt": "Make the person in <<<image_1>>> wave at the camera",
      "image_urls": ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
      "mode": "std",
      "duration": 5,
      "aspect_ratio": "16:9"
  ]

  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

  let task = URLSession.shared.dataTask(with: request) { data, response, error in
      if let error = error {
          print("Error: \(error)")
          return
      }

      if let data = data, let responseString = String(data: data, encoding: .utf8) {
          print(responseString)
      }
  }

  task.resume()
  ```

  ```csharp C# theme={null}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main(string[] args)
      {
          var url = "https://api.apimart.ai/v1/videos/generations";

          var payload = @"{
              ""model"": ""kling-v3-omni"",
              ""prompt"": ""Make the person in <<<image_1>>> wave at the camera"",
              ""image_urls"": [""https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp""],
              ""mode"": ""std"",
              ""duration"": 5,
              ""aspect_ratio"": ""16:9""
          }";

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

          var content = new StringContent(payload, Encoding.UTF8, "application/json");
          var response = await client.PostAsync(url, content);
          var result = await response.Content.ReadAsStringAsync();

          Console.WriteLine(result);
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "code": 200,
    "data": [
      {
        "status": "submitted",
        "task_id": "task_xxxxxxxxxx"
      }
    ]
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "Invalid request parameters",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "Invalid authentication credentials",
      "type": "authentication_error"
    }
  }
  ```

  ```json 402 theme={null}
  {
    "error": {
      "code": 402,
      "message": "Insufficient balance. Please top up your account",
      "type": "payment_required"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "Rate limit exceeded. Please try again later",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "Internal server error. Please try again later",
      "type": "server_error"
    }
  }
  ```
</ResponseExample>

## Autorización

<ParamField header="Authorization" type="string" required>
  Todos los endpoints de la API requieren autenticación mediante Bearer Token

  Obtenga su API Key:

  Visite la [página de gestión de API Keys](https://apimart.ai/keys) para obtener su API Key

  Añádala al encabezado de la solicitud:

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Parámetros de la solicitud

<ParamField body="model" type="string" required>
  Nombre del modelo de generación de video

  Modelos compatibles:

  * `kling-v3-omni` - Kling v3 Omni (interfaz unificada)
</ParamField>

<ParamField body="prompt" type="string" required>
  Prompt de texto positivo

  Admite referenciar imágenes de `image_urls` usando la sintaxis `<<<image_N>>>`, donde `N` comienza en 1.

  Ejemplo: `"Make the person in <<<image_1>>> wave at the camera"`

  <Note>
    Si se proporcionan imágenes pero el prompt no contiene ninguna referencia `<<<image_N>>>`, el sistema añadirá automáticamente `<<<image_1>>>` al principio del prompt.
  </Note>
</ParamField>

<ParamField body="negative_prompt" type="string">
  Prompt negativo utilizado para excluir contenido no deseado. La longitud máxima es de 2500 caracteres.
</ParamField>

<ParamField body="mode" type="string" default="std">
  Modo de generación

  Opciones:

  * `std` - Modo estándar (720P)
  * `pro` - Modo profesional (1080P)
  * `4k` - Modo 4K ultra HD

  Predeterminado: `std`
</ParamField>

<ParamField body="duration" type="integer" default="5">
  Predeterminado: `5`
  Duración del video (segundos)

  Rango: 3-15 (mínimo 3 segundos, máximo 15 segundos)

  **⚠️ Nota:** Debe ser un número simple (por ejemplo, `6`), sin comillas, de lo contrario se producirá un error
</ParamField>

<ParamField body="aspect_ratio" type="string" default="16:9">
  Relación de aspecto del video

  Opciones:

  * `16:9` - Horizontal
  * `9:16` - Vertical
  * `1:1` - Cuadrado

  Predeterminado: `16:9`
</ParamField>

<ParamField body="image_urls" type="array<url>">
  Array de URLs de imágenes para la referencia de imágenes

  Referencie las imágenes correspondientes en el prompt usando la sintaxis `<<<image_N>>>` (N comienza en 1)

  Ejemplo: `["https://example.com/photo.jpg"]`

  <Warning>
    * Las URLs de imágenes deben ser de acceso público, sin protección contra hotlinking
    * En el modo image-to-video, `aspect_ratio` puede ser sobrescrito por la relación real de la imagen
  </Warning>
</ParamField>

<ParamField body="image_with_roles" type="array<object>">
  Array de imágenes basadas en roles, recomendado para image-to-video.

  Formato de cada elemento: `{ "url": "...", "role": "..." }`

  * `first_frame`: primer frame
  * `last_frame`: último frame
  * `reference`: imagen de referencia

  <Warning>
    `image_urls` e `image_with_roles` son mutuamente excluyentes. Use solo uno.
  </Warning>
</ParamField>

<ParamField body="video_list" type="array" optional>
  Lista de videos de referencia (basada en URL), hasta 1 video.

  Use `refer_type` para distinguir los tipos:

  * `base`: video a editar (predeterminado)
  * `feature`: video de referencia de características

  Use `keep_original_sound` para controlar el audio original:

  * `no`: no conservar (predeterminado)
  * `yes`: conservar el sonido original

  Formato de la solicitud:

  ```json theme={null}
  "video_list":[
    { "video_url": "video_url", "refer_type": "base", "keep_original_sound": "no" }
  ]
  ```

  <Warning>
    * `video_url` no puede estar vacío y la URL del video debe ser accesible
    * Cuando `refer_type=base`:
      * No se pueden definir los frames inicial/final
      * El video de referencia debe durar entre 3 y 10 segundos
      * La duración del video generado sigue al video subido
    * Cuando `refer_type=feature` y `video_url` no está vacío:
      * `image_urls` solo puede incluir una imagen del primer frame
    * Requisitos del video: solo MP4/MOV; duración mínima de 3 segundos; resolución 720px-2160px; velocidad de fotogramas 24-60fps (la salida es 24fps); tamaño no superior a 200MB
  </Warning>
</ParamField>

<ParamField body="multi_shot" type="boolean" default="false">
  Define si se activa el modo multi-shot.
</ParamField>

<ParamField body="shot_type" type="string">
  Método de división de planos: `customize` / `intelligence`.

  Obligatorio cuando `multi_shot=true`.
</ParamField>

<ParamField body="multi_prompt" type="array<object>">
  Lista multi-shot, cada elemento es `{ index, prompt, duration }`.

  * Mínimo 1 plano, máximo 6 planos
  * El `duration` de cada plano debe ser un entero y >= 1
  * La suma de las duraciones de todos los planos debe ser igual al `duration` de nivel superior
  * `index` debe comenzar en 1 y aumentar de forma continua
  * Obligatorio cuando `multi_shot=true` y `shot_type=customize`

  Ejemplo:

  ```json theme={null}
  [
    { "index": 1, "prompt": "a happy dog in running@element_cat", "duration": 3 },
    { "index": 2, "prompt": "a happy dog play with a cat@element_dog", "duration": 3 }
  ]
  ```
</ParamField>

<ParamField body="element_list" type="array<object>">
  Lista de sujetos de referencia, hasta 3 sujetos. Admite:

  * Crear sujetos al instante con `name`, `description`, `element_input_urls`

  Formato común:

  ```json theme={null}
  [
    {
      "name": "element_dog",
      "description": "a golden retriever, fluffy fur, friendly expression",
      "element_input_urls": [
        "https://example.com/image1.png",
        "https://example.com/image2.png"
      ]
    },
    {
      "name": "element_cat",
      "description": "an orange tabby cat, round face, bright eyes",
      "element_input_urls": [
        "https://example.com/image1.png",
        "https://example.com/image2.png"
      ]
    }
  ]
  ```

  Notas:

  * Para la creación al instante, `name`, `description`, `element_input_urls` son obligatorios
  * `element_input_urls`: de 2 a 4 imágenes por sujeto (la primera como imagen frontal, las demás como referencias)
  * Use `@name` en `prompt`, por ejemplo, `"@element_dog and @element_cat are playing on the grass"`
</ParamField>

<ParamField body="watermark" type="boolean">
  Define si se añade una marca de agua
</ParamField>

<ParamField body="audio" type="boolean" default="false">
  Define si se genera el video con audio

  <Warning>
    Este parámetro es mutuamente excluyente con `video_list`.

    Cuando `video_list` tiene un valor, el parámetro `audio` no es necesario.
  </Warning>
</ParamField>

### Restricciones y límites de parámetros

* `image_urls` e `image_with_roles` son mutuamente excluyentes
* `mode=4k` está disponible para `kling-v3-omni`
* La entrada solo del último frame (`last_frame` sin primer frame) no es válida
* Los frames inicial/final y la edición de video son mutuamente excluyentes: cuando `video_list.refer_type=base` (u omitido), no se permiten los frames inicial/final
* Cuando `video_list` está presente, se ignora `audio`
* `video_list` admite como máximo 1 video
* `multi_prompt` admite hasta 6 planos, con `index` comenzando en 1 y aumentando de forma continua

## Sintaxis de referencia de imágenes

El modelo Omni utiliza la sintaxis `<<<image_N>>>` para referenciar imágenes en los prompts, ofreciendo una experiencia unificada text-to-video/image-to-video:

| Sintaxis        | Descripción                                    |
| --------------- | ---------------------------------------------- |
| `<<<image_1>>>` | Referencia la 1ª imagen del array `image_urls` |
| `<<<image_2>>>` | Referencia la 2ª imagen del array `image_urls` |

<Note>
  **Referencia automática**: Si se proporciona `image_urls` pero el prompt no contiene ninguna referencia `<<<image_N>>>`, el sistema añadirá automáticamente `<<<image_1>>>` al principio del prompt.
</Note>

## Respuesta

<ResponseField name="code" type="integer">
  Código de estado de la respuesta, 200 en caso de éxito
</ResponseField>

<ResponseField name="data" type="array">
  Array de datos de la respuesta

  <Expandable title="Elementos del array">
    <ResponseField name="status" type="string">
      Estado de la tarea, `submitted` en la solicitud inicial
    </ResponseField>

    <ResponseField name="task_id" type="string">
      Identificador único de la tarea para consultar el estado y los resultados
    </ResponseField>
  </Expandable>
</ResponseField>

## Casos de uso

### Caso 1: Texto a video (Modo estándar)

```json theme={null}
{
  "model": "kling-v3-omni",
  "prompt": "A golden retriever running on the beach, sunset, cinematic",
  "mode": "std",
  "duration": 5,
  "aspect_ratio": "16:9"
}
```

### Caso 2: Referencia de imagen (Imagen única)

```json theme={null}
{
  "model": "kling-v3-omni",
  "prompt": "Make the person in <<<image_1>>> wave at the camera",
  "image_urls": ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
  "mode": "pro",
  "duration": 5
}
```

### Caso 3: Múltiples referencias de imagen

```json theme={null}
{
  "model": "kling-v3-omni",
  "prompt": "The character in <<<image_1>>> walks toward the scene in <<<image_2>>>",
  "image_urls": [
    "https://example.com/character.jpg",
    "https://example.com/scene.jpg"
  ],
  "mode": "pro",
  "duration": 5
}
```

### Caso 4: Imagen proporcionada sin referencia explícita (añadida automáticamente)

```json theme={null}
{
  "model": "kling-v3-omni",
  "prompt": "The person slowly turns and smiles",
  "image_urls": ["https://upload.apimart.ai/f/models/9998230426123070-e9d6af04-cb5e-4731-8ae7-abf144cb0d29-9998230586368386-29641169-f698-4ab9-9b6d-380899e6521e-9998230593110693-c1741a3a-.webp"],
  "mode": "std",
  "duration": 5
}
```

> El sistema añadirá automáticamente `<<<image_1>>>` al principio del prompt, equivalente a `"<<<image_1>>>The person slowly turns and smiles"`.

### Caso 5: Generar video con audio

```json theme={null}
{
  "model": "kling-v3-omni",
  "prompt": "A yellow canary singing on a branch",
  "audio": true,
  "mode": "std",
  "duration": 5
}
```

> **Nota**: `audio` es mutuamente excluyente con `video_list`. Cuando `video_list` tiene un valor, el parámetro `audio` no es necesario.

<Note>
  **Consultar los resultados de la tarea**

  La generación de video es una tarea asíncrona que devuelve un `task_id` al enviarse. Use el endpoint [Obtener estado de la tarea](/es/api-reference/tasks/status) para consultar el progreso y los resultados de la generación.
</Note>
