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

# 이미지 생성

> CometAPI POST /v1/images/generations를 사용해 OpenAI 호환 이미지 모델과 모델별 제어 옵션으로 이미지를 생성합니다.

CometAPI에서 OpenAI 호환 요청 형식으로 텍스트로부터 이미지를 생성하려면 이 경로를 사용하세요.

## 공식 레퍼런스

* `background`, `output_compression`, 스트리밍(Streaming), 또는 향후 GPT 이미지 옵션과 같은 모델별 제어 기능을 사용하기 전에 [OpenAI image generation guide](https://developers.openai.com/api/docs/guides/image-generation)를 읽어보세요.
* 현재 파라미터 목록은 [OpenAI Create image reference](https://developers.openai.com/api/reference/resources/images/methods/generate)를 사용하세요.

## 먼저 모델 선택하기

* `output_format`, `quality`, `background` 같은 제어 옵션이 있는 텍스트-투-이미지 요청에는 `gpt-image-2`와 같은 GPT 이미지 모델을 사용하세요
* 해당 provider가 특별히 필요하다면 `qwen-image`를 사용하되, `n`은 1로 유지하세요
* [Models page](/ko/overview/models)에서 현재 이미지 model ID를 선택하세요

## 안전한 첫 요청

* `gpt-image-2`로 시작하세요
* `size`는 `1024x1024`로 유지하세요
* GPT 이미지 모델은 `b64_json`에 base64로 인코딩된 이미지 데이터를 반환하므로, 이미지 파일로 저장하려면 이를 디코딩해야 합니다
* `jpeg`와 같은 특정 인코딩 이미지 형식이 필요할 때만 `output_format`을 추가하세요
* `background`, `output_compression`, 또는 스트리밍(Streaming)을 추가하기 전에 OpenAI 이미지 생성 가이드를 확인하세요
* 배치 생성이나 스타일 조정을 추가하기 전에 프롬프트(Prompt) 1개와 출력 이미지 1개로 먼저 사용해 보세요

## 비동기 이미지 작업 실행

클라이언트가 하나의 HTTP 연결을 계속 열어두는 대신 제출 후 폴링하는 흐름을 선호한다면, 오래 걸리는 이미지 작업에 `async: true`를 사용하세요. 생성 요청은 `data.task_id`를 반환합니다.

`data.status`가 `success` 또는 `failure`가 될 때까지 [Retrieve an image generation task](/api/image/openai/image-generation-task)를 폴링하세요.

`async` 필드는 이 경로에 대한 CometAPI 확장이며, OpenAI 파라미터가 아닙니다. OpenAI는 GPT 이미지 모델에 대해 `stream` 및 `partial_images`를 문서화합니다. CometAPI 비동기 작업 모드는 JSON 작업 메타데이터를 반환하고 폴링을 사용합니다.

문서화된 다음 model ID에서 async 작업 모드를 사용하세요: `gpt-image-2` 및 `doubao-seedream-4-0-250828`. 다른 이미지 모델의 경우, 해당 모델에 async 작업 지원이 문서화되어 있지 않다면 동기 생성 또는 스트리밍(Streaming)을 사용하세요.

요청에 `async: true`와 `stream: true`가 모두 포함되면 async 작업 모드가 우선 적용됩니다. 생성 요청은 SSE 스트림 대신 JSON 작업 메타데이터를 반환합니다.

## 모델별 요청 동작

* `response_format`은 DALL·E 모델에만 적용되며, GPT 이미지 모델은 base64 데이터를 반환하고 이를 무시합니다
* GPT 이미지 모델은 `output_format`, `quality`, `background`, `output_compression` 같은 GPT 전용 제어 옵션을 사용합니다
* 최신 모델별 옵션은 OpenAI 이미지 생성 가이드를 따르세요
* `qwen-image`는 `n > 1`을 지원하지 않습니다

<Warning>
  생성된 이미지는 provider 사용 정책을 준수해야 합니다. 불법적이거나 폭력적이거나 음란하거나 저작권을 침해하는 프롬프트(Prompt)를 보내지 마세요.
</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.

````