> ## 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 một hình ảnh

> Sử dụng CometAPI POST /v1/images/generations để tạo hình ảnh với các model hình ảnh tương thích OpenAI và các tùy chọn điều khiển theo từng model.

Sử dụng route này để tạo hình ảnh từ văn bản với định dạng request tương thích OpenAI trên CometAPI.

## Tài liệu tham khảo chính thức

* Đọc [hướng dẫn tạo hình ảnh của OpenAI](https://developers.openai.com/api/docs/guides/image-generation) trước khi bạn sử dụng các tùy chọn điều khiển theo từng model như `background`, `output_compression`, streaming, hoặc các tùy chọn hình ảnh GPT trong tương lai.
* Sử dụng [tài liệu tham khảo OpenAI Create image](https://developers.openai.com/api/reference/resources/images/methods/generate) để xem danh sách tham số hiện tại.

## Chọn model trước

* Sử dụng model hình ảnh GPT như `gpt-image-2` cho các request text-to-image với các tùy chọn điều khiển như `output_format`, `quality`, hoặc `background`
* Sử dụng `qwen-image` khi bạn cần đúng nhà cung cấp đó, nhưng giữ `n` ở mức 1
* Chọn một model ID hình ảnh hiện có từ [trang Models](/vi/overview/models)

## Request đầu tiên an toàn

* Bắt đầu với `gpt-image-2`
* Giữ `size` ở `1024x1024`
* Model hình ảnh GPT trả về dữ liệu hình ảnh mã hóa base64 trong `b64_json`; hãy giải mã dữ liệu đó để lưu tệp hình ảnh
* Chỉ thêm `output_format` khi bạn cần một kiểu hình ảnh được mã hóa cụ thể như `jpeg`
* Kiểm tra hướng dẫn tạo hình ảnh của OpenAI trước khi thêm `background`, `output_compression`, hoặc streaming
* Sử dụng một prompt và một hình ảnh đầu ra trước khi thêm batch generation hoặc tinh chỉnh phong cách

## Chạy một tác vụ hình ảnh async

Sử dụng `async: true` cho các tác vụ hình ảnh chạy lâu khi client của bạn ưu tiên luồng gửi rồi polling thay vì giữ một kết nối HTTP mở.

Request tạo sẽ trả về `data.task_id`.

Polling [Truy xuất một tác vụ tạo hình ảnh](/api/image/openai/image-generation-task) cho đến khi `data.status` là `success` hoặc `failure`.

Trường `async` là một phần mở rộng của CometAPI cho route này, không phải là tham số OpenAI. OpenAI ghi nhận `stream` và `partial_images` cho các model hình ảnh GPT. Chế độ tác vụ bất đồng bộ của CometAPI trả về metadata tác vụ ở dạng JSON và sử dụng polling.

Sử dụng chế độ tác vụ async với các model ID đã được ghi nhận sau: `gpt-image-2` và `doubao-seedream-4-0-250828`. Với các model hình ảnh khác, hãy dùng tạo đồng bộ hoặc streaming trừ khi hỗ trợ tác vụ async được ghi nhận cho model đó.

Khi một request bao gồm cả `async: true` và `stream: true`, chế độ tác vụ async sẽ được ưu tiên. Request tạo sẽ trả về metadata tác vụ JSON thay vì một luồng SSE.

## Hành vi request theo từng model

* `response_format` chỉ áp dụng cho các model DALL·E; các model hình ảnh GPT trả về dữ liệu base64 và bỏ qua tham số này
* Các model hình ảnh GPT sử dụng các tùy chọn điều khiển chỉ dành cho GPT như `output_format`, `quality`, `background`, và `output_compression`
* Làm theo hướng dẫn tạo hình ảnh của OpenAI để biết các tùy chọn theo từng model mới nhất
* `qwen-image` không hỗ trợ `n > 1`

<Warning>
  Hình ảnh được tạo phải tuân thủ chính sách sử dụng của nhà cung cấp. Không gửi các prompt bất hợp pháp, bạo lực, khiêu dâm hoặc vi phạm bản quyền.
</Warning>


## OpenAPI

````yaml api/openapi/image/openai/post-images.openapi.json POST /v1/images/generations
openapi: 3.1.0
info:
  title: Images API
  version: 1.0.0
  description: >-
    Create images through the OpenAI-compatible CometAPI image generation route.
    Request parameters vary by model. For the latest model-specific controls,
    refer to the OpenAI image generation guide:
    https://developers.openai.com/api/docs/guides/image-generation
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      summary: Create images
      description: >-
        Generate images from a text prompt using OpenAI-compatible request
        shapes on CometAPI. For the latest model-specific output controls and
        parameter support, refer to the OpenAI image generation guide:
        https://developers.openai.com/api/docs/guides/image-generation
      operationId: images
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - prompt
              properties:
                model:
                  type: string
                  description: >-
                    The image generation model to use. Choose a current model
                    from the [Models page](/overview/models).
                  default: gpt-image-2
                prompt:
                  type: string
                  description: Text description of the image you want to generate.
                  example: A paper boat floating on calm water at sunrise.
                'n':
                  type: integer
                  description: >-
                    Number of images to generate. Keep this at 1 for the
                    broadest compatibility.
                  default: 1
                quality:
                  type: string
                  description: >-
                    Quality setting for models that support it. See the OpenAI
                    image generation guide for the latest model-specific values.
                size:
                  type: string
                  description: >-
                    Requested output size. Supported values depend on the
                    selected model. See the OpenAI image generation guide for
                    the latest model-specific ranges.
                  example: 1024x1024
                response_format:
                  type: string
                  description: >-
                    The response container for `dall-e-2` and `dall-e-3`. This
                    parameter is not supported for GPT image models, which
                    return base64-encoded image data.
                  enum:
                    - url
                    - b64_json
                output_format:
                  type: string
                  description: >-
                    The encoded image type for GPT image model results, such as
                    `png`, `jpeg`, or `webp`. See the OpenAI image generation
                    guide for current GPT image output controls.
                  example: jpeg
                stream:
                  type: boolean
                  description: >-
                    Set this to `true` to receive server-sent image generation
                    events instead of waiting for the completed JSON response.
                    Streaming responses use `text/event-stream` and can include
                    final events such as `image_generation.completed`. When
                    `stream` and `async` are both `true`, async task mode takes
                    precedence and the create request returns JSON instead of a
                    streaming image response.
                  default: false
                async:
                  type: boolean
                  description: >-
                    CometAPI asynchronous task mode. Set this to `true` to
                    return immediately with `data.task_id`, then poll `GET
                    /v1/images/generations/{task_id}` for the final image data.
                    Documented model IDs for this mode: `gpt-image-2` and
                    `doubao-seedream-4-0-250828`. This is a CometAPI extension,
                    not an OpenAI parameter. When `async` and `stream` are both
                    `true`, async takes precedence and returns JSON task
                    metadata instead of an SSE stream.
                  default: false
              default:
                model: gpt-image-2
                prompt: A paper boat floating on calm water at sunrise.
                'n': 1
                size: 1024x1024
                output_format: jpeg
            examples:
              gpt_image:
                summary: GPT image generation (gpt-image-2)
                value:
                  model: gpt-image-2
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
                  output_format: jpeg
              streaming_image:
                summary: Streaming image generation
                value:
                  model: gpt-image-2
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
                  output_format: jpeg
                  stream: true
              async_image:
                summary: Async image generation
                value:
                  model: gpt-image-2
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
                  output_format: jpeg
                  async: true
              gpt_image_1:
                summary: GPT image generation (gpt-image-1)
                value:
                  model: gpt-image-1
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
      responses:
        '200':
          description: >-
            Image generation result. Synchronous requests return completed image
            data. Async requests return a task response with `data.task_id`.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    title: Completed image response
                    required:
                      - created
                      - data
                    properties:
                      created:
                        type: integer
                        description: Unix timestamp for the completed generation.
                      background:
                        type: string
                        description: Background mode returned by models that expose it.
                      output_format:
                        type: string
                        description: Encoded image type returned by GPT image models.
                      quality:
                        type: string
                        description: Quality level returned by models that expose it.
                      size:
                        type: string
                        description: Output size returned by models that expose it.
                      usage:
                        type: object
                        description: >-
                          Token usage details when returned by the selected
                          model.
                        properties:
                          input_tokens:
                            type: integer
                          output_tokens:
                            type: integer
                          total_tokens:
                            type: integer
                          input_tokens_details:
                            type: object
                            properties:
                              image_tokens:
                                type: integer
                              text_tokens:
                                type: integer
                          output_tokens_details:
                            type: object
                            properties:
                              image_tokens:
                                type: integer
                              text_tokens:
                                type: integer
                      data:
                        type: array
                        items:
                          type: object
                          properties:
                            url:
                              type: string
                              description: >-
                                Temporary image URL when the selected model
                                supports URL output.
                            b64_json:
                              type: string
                              description: >-
                                Base64-encoded image payload for models that
                                return inline content.
                            revised_prompt:
                              type: string
                              description: Provider-rewritten prompt, when available.
                  - type: object
                    title: Async task response
                    required:
                      - code
                      - data
                    properties:
                      code:
                        type: string
                        description: >-
                          Request status code. A successful async submit returns
                          `success`.
                        example: success
                      message:
                        type: string
                        description: Optional status message.
                      data:
                        type: object
                        required:
                          - task_id
                          - status
                          - data
                        properties:
                          task_id:
                            type: string
                            description: >-
                              Task ID to pass to `GET
                              /v1/images/generations/{task_id}`.
                          status:
                            type: string
                            description: Task state for the submitted image generation job.
                            enum:
                              - pending
                              - success
                              - failure
                          data:
                            type: array
                            description: >-
                              Empty at submit time. Poll the task endpoint to
                              receive final image data.
                            items:
                              type: object
                    example:
                      code: success
                      message: ''
                      data:
                        task_id: <task_id>
                        status: pending
                        data: []
              example:
                created: 1781075000
                background: opaque
                output_format: jpeg
                quality: low
                size: 1024x1024
                usage:
                  input_tokens: 13
                  input_tokens_details:
                    image_tokens: 0
                    text_tokens: 13
                  output_tokens: 196
                  output_tokens_details:
                    image_tokens: 196
                    text_tokens: 0
                  total_tokens: 209
                data:
                  - b64_json: /9j/4AAQSkZJRgABAQAAAQABAAD...
            text/event-stream:
              schema:
                type: string
                description: >-
                  Server-sent events returned when `stream` is `true`. Events
                  can include image generation progress and final image data.
              example: >+
                event: image_generation.completed

                data:
                {"created_at":1783305600,"type":"image_generation.completed","b64_json":"<base64-image-data>"}

      x-codeSamples:
        - lang: Shell
          label: Default
          source: |
            curl https://api.cometapi.com/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg"
              }'
        - lang: Python
          label: Default
          source: |
            import base64
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            result = client.images.generate(
                model="gpt-image-2",
                prompt="A paper boat floating on calm water at sunrise.",
                quality="low",
                size="1024x1024",
                output_format="jpeg",
            )

            image_bytes = base64.b64decode(result.data[0].b64_json)
            with open("boat.jpg", "wb") as f:
                f.write(image_bytes)
        - lang: JavaScript
          label: Default
          source: >
            import fs from "node:fs";

            import OpenAI from "openai";


            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });


            const result = await client.images.generate({
                model: "gpt-image-2",
                prompt: "A paper boat floating on calm water at sunrise.",
                quality: "low",
                size: "1024x1024",
                output_format: "jpeg",
            });


            fs.writeFileSync("boat.jpg", Buffer.from(result.data[0].b64_json,
            "base64"));
        - lang: Shell
          label: Streaming request
          source: |
            curl -N https://api.cometapi.com/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg",
                "stream": true
              }'
        - lang: Python
          label: Streaming request
          source: |
            import json
            import os
            import urllib.request

            payload = {
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg",
                "stream": True,
            }

            request = urllib.request.Request(
                "https://api.cometapi.com/v1/images/generations",
                data=json.dumps(payload).encode("utf-8"),
                headers={
                    "Authorization": "Bearer " + os.environ["COMETAPI_KEY"],
                    "Content-Type": "application/json",
                },
                method="POST",
            )

            with urllib.request.urlopen(request) as response:
                for raw_line in response:
                    line = raw_line.decode("utf-8").strip()
                    if line:
                        print(line)
        - lang: JavaScript
          label: Streaming request
          source: >
            const response = await
            fetch("https://api.cometapi.com/v1/images/generations", {
              method: "POST",
              headers: {
                Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                model: "gpt-image-2",
                prompt: "A paper boat floating on calm water at sunrise.",
                quality: "low",
                size: "1024x1024",
                output_format: "jpeg",
                stream: true,
              }),
            });


            const decoder = new TextDecoder();

            for await (const chunk of response.body) {
              process.stdout.write(decoder.decode(chunk));
            }
        - lang: Shell
          label: Async request
          source: |
            curl https://api.cometapi.com/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg",
                "async": true
              }'
        - lang: Python
          label: Async request
          source: |
            import os
            import requests

            response = requests.post(
                "https://api.cometapi.com/v1/images/generations",
                headers={
                    "Authorization": "Bearer " + os.environ["COMETAPI_KEY"],
                    "Content-Type": "application/json",
                },
                json={
                    "model": "gpt-image-2",
                    "prompt": "A paper boat floating on calm water at sunrise.",
                    "quality": "low",
                    "size": "1024x1024",
                    "output_format": "jpeg",
                    "async": True,
                },
            )

            result = response.json()
            print(result["data"]["task_id"])
        - lang: JavaScript
          label: Async request
          source: >
            const response = await
            fetch("https://api.cometapi.com/v1/images/generations", {
              method: "POST",
              headers: {
                Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                model: "gpt-image-2",
                prompt: "A paper boat floating on calm water at sunrise.",
                quality: "low",
                size: "1024x1024",
                output_format: "jpeg",
                async: true,
              }),
            });


            const result = await response.json();

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

````