> ## 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.

# Tạo hình ảnh với Kling

> Tạo hình ảnh với Kling qua CometAPI: POST /kling/v1/images/generations hỗ trợ tạo hình ảnh từ prompt và tạo hình ảnh bằng ảnh tham chiếu.

## Tạo hình ảnh

<Note>Để xem tài liệu tham khảo tham số đầy đủ, hãy xem [tài liệu Kling chính thức](https://kling.ai/document-api/api/image/3-0-omni/image-generation).</Note>

Sử dụng endpoint này để tạo hình ảnh tĩnh thông qua API tạo hình ảnh của Kling. Endpoint này hỗ trợ cả yêu cầu chỉ dùng văn bản và yêu cầu dùng ảnh tham chiếu thông qua cùng một luồng tác vụ bất đồng bộ.

## Yêu cầu đầu tiên

Bắt đầu với `model_name: kling-v3`, `prompt`, `n` và `aspect_ratio`. Chỉ thêm ảnh tham chiếu, các thiết lập độ trung thực hoặc các trường nâng cao sau khi yêu cầu đầu tiên trả về một tác vụ có thể sử dụng được. Nếu bỏ qua `model_name`, hệ thống sẽ dùng một giá trị mặc định tương thích cũ, vì vậy hãy gửi rõ ràng `kling-v3` cho các tích hợp mới.

## Đọc phản hồi

Lưu `task_id` được trả về, sau đó poll route truy vấn hình ảnh Kling tương ứng cho đến khi `task_status` đạt trạng thái kết thúc. Nếu quy trình của bạn cần lưu trữ bền vững, hãy sao chép asset cuối cùng vào lớp lưu trữ của riêng bạn sau khi quá trình tạo hoàn tất.


## OpenAPI

````yaml api/openapi/image/kling/post-image-generation.openapi.json POST /kling/v1/images/generations
openapi: 3.1.0
info:
  title: Kling Image Generation API
  version: 1.0.0
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /kling/v1/images/generations:
    post:
      summary: Generate images with Kling
      operationId: kling_image_generation
      parameters:
        - name: Content-Type
          in: header
          required: false
          description: Must be `application/json`.
          schema:
            type: string
            default: application/json
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - prompt
              properties:
                model_name:
                  type: string
                  description: >-
                    Kling image model variant. Use `kling-v3` for new requests.
                    Omitting `model_name` uses the legacy CometAPI route
                    default.
                  enum:
                    - kling-v1
                    - kling-v1-5
                    - kling-v2
                    - kling-v2-1
                    - kling-v3
                  default: kling-v1
                prompt:
                  type: string
                  description: >-
                    Text prompt describing the image to generate. Maximum 2500
                    characters.
                negative_prompt:
                  type: string
                  description: >-
                    Elements to exclude from the image. Maximum 2500 characters.
                    Not supported when `image` is provided.
                image:
                  type: string
                  description: >-
                    Reference image as a raw Base64 string without a `data:`
                    prefix, or a public URL. Accepted formats: JPG, JPEG, PNG.
                    Maximum 10 MB, minimum 300x300 px, aspect ratio between
                    1:2.5 and 2.5:1.
                image_reference:
                  type: string
                  description: >-
                    Reference mode for legacy image-to-image requests when
                    `image` is provided.
                  enum:
                    - subject
                    - face
                image_fidelity:
                  type: number
                  description: >-
                    How closely the output follows the reference image. Range:
                    0-1. Used by legacy image-reference models.
                  default: 0.5
                  minimum: 0
                  maximum: 1
                human_fidelity:
                  type: number
                  description: >-
                    Human-subject fidelity control. Range: 0-1. Used only by
                    legacy subject-reference requests.
                  default: 0.45
                  minimum: 0
                  maximum: 1
                element_list:
                  type: array
                  description: >-
                    Optional Kling element references. The total count of
                    element references and input images must not exceed 10.
                  items:
                    type: object
                    required:
                      - element_id
                    properties:
                      element_id:
                        type: integer
                        description: Kling element ID.
                resolution:
                  type: string
                  description: Output resolution. Defaults to `1k`.
                  enum:
                    - 1k
                    - 2k
                  default: 1k
                'n':
                  type: integer
                  description: 'Number of images to generate. Range: 1-9.'
                  minimum: 1
                  maximum: 9
                  default: 1
                aspect_ratio:
                  type: string
                  description: Output aspect ratio (width:height).
                  enum:
                    - '16:9'
                    - '9:16'
                    - '1:1'
                    - '4:3'
                    - '3:4'
                    - '3:2'
                    - '2:3'
                    - '21:9'
                  default: '16:9'
                watermark_info:
                  type: object
                  description: Watermark options.
                  properties:
                    enabled:
                      type: boolean
                      description: Whether to add the official watermark.
                callback_url:
                  type: string
                  description: >-
                    Webhook URL to receive task status updates when the task
                    completes.
                external_task_id:
                  type: string
                  description: >-
                    Optional user-defined task ID for your own tracking. Must be
                    unique per account.
              default:
                model_name: kling-v3
                prompt: A paper boat floating on calm water at sunrise
                'n': 1
                aspect_ratio: '1:1'
            examples:
              Default:
                summary: Text-to-image request
                value:
                  model_name: kling-v3
                  prompt: A paper boat floating on calm water at sunrise
                  'n': 1
                  aspect_ratio: '1:1'
      responses:
        '200':
          description: Task request accepted or an error response returned by the API.
          content:
            application/json:
              schema:
                type: object
                required:
                  - code
                  - message
                  - data
                properties:
                  code:
                    oneOf:
                      - type: integer
                      - type: string
                    description: Response code. `0` means the task request was accepted.
                  message:
                    type: string
                    description: Response message.
                  request_id:
                    type: string
                    description: Request identifier returned when present.
                  data:
                    type: object
                    required:
                      - task_id
                      - task_status
                      - created_at
                      - updated_at
                    properties:
                      task_id:
                        type: string
                        description: System-generated task ID.
                      task_status:
                        type: string
                        description: Task status.
                        enum:
                          - submitted
                          - processing
                          - succeed
                          - failed
                      task_status_msg:
                        oneOf:
                          - type: string
                          - type: 'null'
                        description: Task status detail when present.
                      task_info:
                        type: object
                        properties:
                          external_task_id:
                            oneOf:
                              - type: string
                              - type: 'null'
                            description: Caller-provided external task ID when supplied.
                        additionalProperties: true
                      task_result:
                        oneOf:
                          - type: object
                            additionalProperties: true
                          - type: 'null'
                        description: Task result payload after the task completes.
                      created_at:
                        type: integer
                        description: >-
                          Task creation time as a Unix timestamp in
                          milliseconds.
                      updated_at:
                        type: integer
                        description: Task update time as a Unix timestamp in milliseconds.
                    additionalProperties: true
                additionalProperties: true
      x-codeSamples:
        - lang: Shell
          label: Default
          source: |
            curl https://api.cometapi.com/kling/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
              "model_name": "kling-v3",
              "prompt": "A paper boat floating on calm water at sunrise",
              "n": 1,
              "aspect_ratio": "1:1"
            }'
        - lang: Python
          label: Default
          source: |
            import os
            import requests

            response = requests.post(
                "https://api.cometapi.com/kling/v1/images/generations",
                headers={"Authorization": "Bearer " + os.environ["COMETAPI_KEY"]},
                json={
                "model_name": "kling-v3",
                "prompt": "A paper boat floating on calm water at sunrise",
                "n": 1,
                "aspect_ratio": "1:1"
            },
            )

            result = response.json()
            print(result["code"], result.get("data", {}).get("task_id"))
        - lang: JavaScript
          label: Default
          source: >
            const response = await
            fetch("https://api.cometapi.com/kling/v1/images/generations", {
              method: "POST",
              headers: {
                Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                "model_name": "kling-v3",
                "prompt": "A paper boat floating on calm water at sunrise",
                "n": 1,
                "aspect_ratio": "1:1"
            }),

            });


            const result = await response.json();

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

````