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

# OpenAI-compatible 이미지 생성 API: GPT Image 2 가이드

> GPT Image 2와 BetterToken의 OpenAI-compatible API로 text에서 이미지를 생성하세요. API Key, Base URL, parameters, Python, JavaScript 및 errors를 안내합니다.

`POST /v1/images/generations`

text-to-image endpoint는 `application/json` request body를 사용합니다. prompt를 제출하고 HTTP request를 열어 둔 뒤 같은 response의 `data[0].b64_json`에서 생성된 이미지를 읽으세요.

<Note>
  `https://www.bettertoken.ai/v1`을 `Base URL`로 사용하세요. `Authorization: Bearer YOUR_API_KEY`를 통해 BetterToken API Key를 전달하세요.
</Note>

<Tip>
  페이지 오른쪽의 Playground에서 `Authorization` 및 request body를 입력한 다음 `https://www.bettertoken.ai/v1/images/generations`로 request를 직접 보낼 수 있습니다.
</Tip>

<Warning>
  API keys를 frontend browser code, Git repositories, tickets, screenshots 또는 logs에 넣지 마세요. server-side proxy calls에서는 API keys를 server environment variables 또는 secret manager에만 저장하세요.
</Warning>

## curl 빠른 시작

`https://www.bettertoken.ai/v1`을 Base URL로 사용하고 `https://www.bettertoken.ai/v1/images/generations`로 request를 보내세요.

```bash theme={null}
curl -X POST "https://www.bettertoken.ai/v1/images/generations" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A product photo of a green ceramic mug on a studio table",
    "size": "1024x1024",
    "n": 1,
    "response_format": "b64_json",
    "output_format": "png"
  }'
```

## 권장 값

모든 request에서 다음 fields를 명시적으로 보내세요.

```json theme={null}
{
  "model": "gpt-image-2",
  "n": 1,
  "response_format": "b64_json",
  "output_format": "png"
}
```

| Parameter         | 보낼 값             | 목적                                                                             |
| ----------------- | ---------------- | ------------------------------------------------------------------------------ |
| `model`           | `gpt-image-2`    | image model을 선택합니다.                                                            |
| `prompt`          | text description | 필수 image description입니다. subject, style, composition 및 중요한 constraints를 포함하세요. |
| `size`            | 예: `1024x1024`   | output size와 aspect ratio를 선택합니다.                                              |
| `n`               | `1`              | 하나의 request에 대한 image count입니다. 여러 images에는 별도의 requests를 보내세요.                |
| `response_format` | `b64_json`       | `data[0].b64_json`에 base64 image content를 반환합니다.                               |
| `output_format`   | `png`            | result를 PNG로 저장할 수 있게 합니다.                                                     |

여러 independent requests를 보내 여러 images를 생성하세요. `n > 1`인 단일 request에 의존하지 마세요.

## 권장 sizes

| `size`      | 비율     | 사용 사례                                          |
| ----------- | ------ | ---------------------------------------------- |
| `auto`      | 자동     | 자동 size 선택                                     |
| `1024x1024` | `1:1`  | 정사각형 images, avatars, covers, assets           |
| `1536x1024` | `3:2`  | 가로 posters, banners, scenes                    |
| `1024x1536` | `2:3`  | 세로 mobile covers 및 posters                     |
| `1536x1152` | `4:3`  | 표준 가로 images, product images, content graphics |
| `1152x1536` | `3:4`  | 표준 세로 images, mobile covers, vertical posters  |
| `2048x2048` | `1:1`  | 고해상도 정사각형 images                               |
| `2048x1152` | `16:9` | 고해상도 가로 images                                 |
| `3840x2160` | `16:9` | 4K 가로 images                                   |
| `2160x3840` | `9:16` | 4K 세로 images                                   |

`size`는 예상 aspect ratio와 size tier를 나타냅니다. 실제 반환 pixels는 server에 의해 mapping 또는 adjusted될 수 있습니다. output을 요청한 값으로 강제로 crop하지 말고 decoded image dimensions를 사용하세요.

## 이미지 저장

성공한 response는 다음 OpenAI-compatible image response shape를 따릅니다.

```json theme={null}
{
  "created": 1710000000,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUgAA...(truncated)"
    }
  ]
}
```

`data[0].b64_json`을 읽어 base64 image content로 저장하세요. response에는 `revised_prompt` 등의 extra fields가 포함될 수 있으므로 client에서 이 fields를 허용하세요.

항상 `output_format: "png"`를 설정하세요. 그런 다음 file headers를 검사하지 않고 decoded image를 `.png`로 저장하세요.

```python theme={null}
import base64
import json
from pathlib import Path

response = json.loads(Path("response.json").read_text(encoding="utf-8"))
b64_json = response["data"][0]["b64_json"]

if "," in b64_json and "base64" in b64_json.split(",", 1)[0]:
    b64_json = b64_json.split(",", 1)[1]

image_bytes = base64.b64decode(b64_json)
Path("output.png").write_bytes(image_bytes)
```

### JavaScript 예시(Node.js)

```js theme={null}
import { writeFile } from "node:fs/promises";

const response = await fetch("https://www.bettertoken.ai/v1/images/generations", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-image-2",
    prompt: "A green ceramic mug on a studio table",
    size: "1024x1024",
    n: 1,
    response_format: "b64_json",
    output_format: "png",
  }),
});

if (!response.ok) {
  throw new Error(await response.text());
}

const { data } = await response.json();
const b64Json = data[0].b64_json.replace(/^data:.*;base64,/, "");
await writeFile("output.png", Buffer.from(b64Json, "base64"));
```

<Warning>
  JPEG 또는 WebP files를 직접 받기 위해 `output_format: "jpeg"` 또는 `output_format: "webp"`에 의존하지 마세요. 현재 endpoint는 여전히 PNG image content를 반환할 수 있습니다. product에 JPEG 또는 WebP가 필요하면 먼저 PNG를 받은 후 자체 code에서 변환하세요.
</Warning>

## Response flow

이 endpoint는 synchronous입니다. `POST /images/generations`를 보낸 후 server가 response할 때까지 현재 HTTP request를 열어 두세요. generation에 성공하면 image content가 `data[0].b64_json`으로 반환됩니다.

endpoint는 `task_id`를 반환하지 않으며 별도의 status query 또는 result download endpoint가 없습니다.

## Timeouts 및 retries

* HTTP client timeouts를 몇 분으로 설정하세요.
* transport errors, `408`, `409`, `425`, `429` 및 `5xx`는 retry하세요.
* `400`, `401`, missing parameters 또는 malformed requests는 자동 retry하지 마세요.
* `3s`, `8s`, `15s` 등의 exponential backoff를 사용하세요.
* duplicate images를 허용할 수 없다면 retry하기 전에 자체 request ID를 기록하세요.

## Error handling

errors는 일반적으로 JSON을 반환합니다. error를 표시할 때는 `error.message`를 먼저 읽고 `message`, HTTP status text 순서로 읽으세요.

| HTTP status | 의미                                                    | 수행할 작업                                                       |
| ----------- | ----------------------------------------------------- | ------------------------------------------------------------ |
| `400`       | malformed JSON, missing parameter 또는 unsupported size | request body를 확인하세요. 자동 retry하지 마세요.                         |
| `401`       | API Key가 없거나 invalid함                                 | `Authorization: Bearer YOUR_API_KEY` header를 확인하세요.          |
| `402`       | balance 또는 quota 부족                                   | balance를 충전하거나 available key를 사용하세요.                         |
| `429`       | rate limit, concurrency limit 또는 busy upstream        | 기다린 후 exponential backoff로 retry하세요.                         |
| `5xx`       | gateway 또는 upstream failure                           | request를 retry하세요. 계속 실패하면 request ID와 error message를 기록하세요. |

## Integration checklist

* Base URL은 `https://www.bettertoken.ai/v1`입니다.
* header에는 `Authorization: Bearer YOUR_API_KEY`가 포함됩니다.
* request는 `application/json`과 `POST /images/generations`를 사용합니다.
* `model`은 `gpt-image-2`, `response_format`은 `b64_json`, `output_format`은 `png`, `n`은 `1`입니다.
* `size`는 `1024x1024` 등의 권장 값 중 하나입니다.
* HTTP client가 generation에 몇 분을 허용합니다.

## 관련 문서

* [이미지 변환](/ko/api-reference/images-edits)
* [GPT Image 2 출시](/ko/model-updates/gpt-image-2)


## OpenAPI

````yaml api-reference/openapi.json POST /v1/images/generations
openapi: 3.1.0
info:
  title: BetterToken GPT Image 2 API
  description: >-
    OpenAI-compatible image generation and image editing endpoints for
    BetterToken.
  version: 1.0.0
servers:
  - url: https://www.bettertoken.ai
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      tags:
        - GPT Image 2
      summary: 文生图（图片生成）
      description: >-
        使用 GPT Image 2 根据文本提示词生成图片。请求使用 application/json，成功响应中的图片内容位于
        data[0].b64_json。
      operationId: createImageGeneration
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TextToImageRequest'
            example:
              model: YOUR_MODEL_ID
              prompt: 一张未来感 AI 产品海报，浅色背景，玻璃质感，干净构图，高级科技感
              'n': 1
              size: 1024x1024
              response_format: b64_json
              output_format: png
      responses:
        '200':
          $ref: '#/components/responses/ImageResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/ServerError'
      x-codeSamples:
        - lang: cURL
          label: cURL
          source: |-
            curl 'https://www.bettertoken.ai/v1/images/generations' \
              -H 'Authorization: Bearer YOUR_API_KEY' \
              -H 'Content-Type: application/json' \
              --data '{
                "model": "YOUR_MODEL_ID",
                "prompt": "一张未来感 AI 产品海报，浅色背景，玻璃质感，干净构图，高级科技感",
                "n": 1,
                "size": "1024x1024",
                "response_format": "b64_json",
                "output_format": "png"
              }'
components:
  schemas:
    TextToImageRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: 固定使用 YOUR_MODEL_ID。
          enum:
            - YOUR_MODEL_ID
          default: YOUR_MODEL_ID
          example: YOUR_MODEL_ID
        prompt:
          type: string
          description: 图片生成提示词。
          example: 一张未来感 AI 产品海报，浅色背景，玻璃质感，干净构图，高级科技感
        'n':
          type: integer
          description: 推荐固定为 1。多张图片建议发起多次独立请求。
          minimum: 1
          maximum: 1
          default: 1
          example: 1
        size:
          $ref: '#/components/schemas/ImageSize'
        response_format:
          type: string
          description: 推荐固定为 b64_json，便于稳定保存图片。
          enum:
            - b64_json
          default: b64_json
          example: b64_json
        output_format:
          type: string
          description: 推荐固定为 png。不要依赖 jpeg 或 webp 直接返回对应格式。
          enum:
            - png
          default: png
          example: png
      additionalProperties: false
    ImageSize:
      type: string
      description: >-
        图片尺寸和比例档位。auto 为自动；1024x1024 和 2048x2048 为 1:1；1536x1024 为 3:2；1024x1536
        为 2:3；1536x1152 为 4:3；1152x1536 为 3:4；2048x1152 和 3840x2160 为
        16:9；2160x3840 为 9:16。实际返回像素可能由服务端映射或调整，客户端应以解码后的真实图片尺寸为准。
      enum:
        - auto
        - 1024x1024
        - 1536x1024
        - 1024x1536
        - 1536x1152
        - 1152x1536
        - 2048x2048
        - 2048x1152
        - 3840x2160
        - 2160x3840
      default: 1024x1024
      example: 1024x1024
    ImageResponse:
      type: object
      description: >-
        OpenAI-compatible image response. Clients should read data[0].b64_json
        and allow additional fields such as revised_prompt.
      properties:
        created:
          type: integer
          example: 1710000000
        data:
          type: array
          items:
            type: object
            properties:
              b64_json:
                type: string
                description: Base64-encoded image content.
                example: iVBORw0KGgoAAAANSUhEUgAA...(truncated)
              revised_prompt:
                type: string
                description: Optional revised prompt.
            additionalProperties: true
      additionalProperties: true
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            message:
              type: string
              example: invalid request
            type:
              type: string
              example: invalid_request_error
            code:
              type: string
              example: invalid_request
          additionalProperties: true
        message:
          type: string
          example: insufficient quota
      additionalProperties: true
  responses:
    ImageResponse:
      description: Image generation result.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ImageResponse'
          example:
            created: 1710000000
            data:
              - b64_json: iVBORw0KGgoAAAANSUhEUgAA...(truncated)
    BadRequest:
      description: 请求格式错误、缺少参数、JSON 或 multipart 解析失败、尺寸格式错误。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: API Key 缺失或无效。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    PaymentRequired:
      description: 额度或余额不足。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimited:
      description: 触发限速、并发限制或上游繁忙。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ServerError:
      description: 网关或上游服务异常。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: BetterToken API Key
      description: >-
        Use your BetterToken API Key as a bearer token. Do not expose API keys
        in frontend browser code, screenshots, logs, tickets, or Git
        repositories.

````