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

# Buat gambar

> Gunakan CometAPI POST /v1/images/generations untuk membuat gambar dengan model gambar yang kompatibel dengan OpenAI dan kontrol khusus model.

Gunakan rute ini untuk membuat gambar dari teks dengan bentuk request yang kompatibel dengan OpenAI di CometAPI.

## Referensi resmi

* Baca [panduan pembuatan gambar OpenAI](https://developers.openai.com/api/docs/guides/image-generation) sebelum Anda menggunakan kontrol khusus model seperti `background`, `output_compression`, streaming, atau opsi GPT image di masa mendatang.
* Gunakan [referensi OpenAI Create image](https://developers.openai.com/api/reference/resources/images/methods/generate) untuk daftar parameter saat ini.

## Pilih model terlebih dahulu

* Gunakan model GPT image seperti `gpt-image-2` untuk request text-to-image dengan kontrol seperti `output_format`, `quality`, atau `background`
* Gunakan `qwen-image` ketika Anda secara khusus membutuhkan provider tersebut, tetapi pertahankan `n` di 1
* Pilih model ID gambar saat ini dari [halaman Models](/id/overview/models)

## Request pertama yang aman

* Mulai dengan `gpt-image-2`
* Pertahankan `size` di `1024x1024`
* Model GPT image mengembalikan data gambar yang dienkode base64 dalam `b64_json`; decode data tersebut untuk menyimpan file gambar
* Tambahkan `output_format` hanya saat Anda membutuhkan tipe gambar terenkode tertentu seperti `jpeg`
* Periksa panduan pembuatan gambar OpenAI sebelum Anda menambahkan `background`, `output_compression`, atau streaming
* Gunakan satu prompt dan satu gambar output sebelum Anda menambahkan pembuatan batch atau penyesuaian gaya

## Jalankan task gambar async

Gunakan `async: true` untuk job gambar yang berjalan lama ketika client Anda lebih memilih alur kirim-dan-poll dibandingkan menahan satu koneksi HTTP tetap terbuka. Request create mengembalikan `data.task_id`.

Lakukan poll ke [Retrieve an image generation task](/api/image/openai/image-generation-task) sampai `data.status` bernilai `success` atau `failure`.

Field `async` adalah ekstensi CometAPI untuk rute ini, bukan parameter OpenAI. OpenAI mendokumentasikan `stream` dan `partial_images` untuk model GPT image. Mode task asynchronous CometAPI mengembalikan metadata task JSON dan menggunakan polling.

Gunakan mode task async dengan model ID yang terdokumentasi berikut: `gpt-image-2` dan `doubao-seedream-4-0-250828`. Untuk model gambar lainnya, gunakan pembuatan sinkron atau streaming kecuali dukungan task async didokumentasikan untuk model tersebut.

Ketika sebuah request menyertakan `async: true` dan `stream: true`, mode task async akan diprioritaskan. Request create mengembalikan metadata task JSON alih-alih stream SSE.

## Perilaku request khusus model

* `response_format` hanya berlaku untuk model DALL·E; model GPT image mengembalikan data base64 dan mengabaikannya
* Model GPT image menggunakan kontrol khusus GPT seperti `output_format`, `quality`, `background`, dan `output_compression`
* Ikuti panduan pembuatan gambar OpenAI untuk opsi khusus model terbaru
* `qwen-image` tidak mendukung `n > 1`

<Warning>
  Gambar yang dihasilkan harus mematuhi kebijakan penggunaan provider. Jangan kirim prompt yang ilegal, mengandung kekerasan, pornografi, atau melanggar hak cipta.
</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.

````