> ## 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 Image Generation API: GPT Image 2 गाइड

> GPT Image 2 और BetterToken के OpenAI-compatible API से text से इमेज बनाएं: API Key, Base URL, parameter, Python, JavaScript और त्रुटियां।

`POST /v1/images/generations`

text-to-image endpoint `application/json` request body उपयोग करता है। prompt भेजें, HTTP request खुला रखें और उसी response में `data[0].b64_json` से generated इमेज पढ़ें।

<Note>
  `https://www.bettertoken.ai/v1` को `Base URL` के रूप में उपयोग करें। BetterToken API Key को `Authorization: Bearer YOUR_API_KEY` से भेजें।
</Note>

<Tip>
  पेज के दाईं ओर Playground में `Authorization` और request body भरें, फिर अनुरोध सीधे `https://www.bettertoken.ai/v1/images/generations` पर भेजें।
</Tip>

<Warning>
  API key को frontend browser code, Git repository, ticket, screenshot या log में न रखें। server-side proxy call के लिए API key केवल server environment variable या secret manager में रखें।
</Warning>

## curl के साथ त्वरित शुरुआत

`https://www.bettertoken.ai/v1` को Base URL के रूप में उपयोग करें और `https://www.bettertoken.ai/v1/images/generations` पर अनुरोध भेजें:

```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"
  }'
```

## अनुशंसित मान

हर अनुरोध में इन फ़ील्ड को स्पष्ट रूप से भेजें:

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

| parameter         | क्या भेजें                | उद्देश्य                                                                           |
| ----------------- | ------------------------- | ---------------------------------------------------------------------------------- |
| `model`           | `gpt-image-2`             | इमेज मॉडल चुनता है।                                                                |
| `prompt`          | text description          | जरूरी इमेज वर्णन। subject, style, composition और महत्वपूर्ण constraint शामिल करें। |
| `size`            | उदाहरण के लिए `1024x1024` | output size और aspect ratio चुनता है।                                              |
| `n`               | `1`                       | एक अनुरोध की इमेज संख्या। कई इमेज के लिए अलग अनुरोध भेजें।                         |
| `response_format` | `b64_json`                | `data[0].b64_json` में base64 के रूप में इमेज content लौटाता है।                   |
| `output_format`   | `png`                     | परिणाम को PNG के रूप में सहेजने देता है।                                           |

कई स्वतंत्र अनुरोध भेजकर कई इमेज बनाएं। `n > 1` वाले एक अनुरोध पर निर्भर न रहें।

## अनुशंसित आकार

| `size`      | अनुपात | उपयोग                                               |
| ----------- | ------ | --------------------------------------------------- |
| `auto`      | Auto   | अपने-आप आकार चयन                                    |
| `1024x1024` | `1:1`  | वर्गाकार इमेज, avatar, cover, asset                 |
| `1536x1024` | `3:2`  | landscape poster, banner, scene                     |
| `1024x1536` | `2:3`  | portrait mobile cover और poster                     |
| `1536x1152` | `4:3`  | मानक landscape इमेज, product image, content graphic |
| `1152x1536` | `3:4`  | मानक portrait इमेज, mobile cover, vertical poster   |
| `2048x2048` | `1:1`  | high-resolution वर्गाकार इमेज                       |
| `2048x1152` | `16:9` | high-resolution landscape इमेज                      |
| `3840x2160` | `16:9` | 4K landscape इमेज                                   |
| `2160x3840` | `9:16` | 4K portrait इमेज                                    |

`size` अपेक्षित aspect ratio और size tier दर्शाता है। वास्तविक लौटे pixel server द्वारा map या adjust किए जा सकते हैं। output को मांगे गए मान पर जबरन crop करने के बजाय decoded इमेज dimension उपयोग करें।

## इमेज सहेजें

सफल response OpenAI-compatible इमेज response स्वरूप का पालन करता है:

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

`data[0].b64_json` पढ़ें और इसे base64 image content के रूप में सहेजें। response में `revised_prompt` जैसे अतिरिक्त field हो सकते हैं; इन्हें client में स्वीकार करें।

`output_format: "png"` हमेशा सेट करें। फिर file header जांचे बिना decoded इमेज को `.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 फ़ाइल सीधे पाने के लिए `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 नहीं है।

## timeout और retry

* HTTP client timeout को कई मिनट पर सेट करें।
* transport error, `408`, `409`, `425`, `429` और `5xx` पर retry करें।
* `400`, `401`, missing parameter या malformed request को अपने-आप retry न करें।
* `3s`, `8s` और `15s` जैसे exponential backoff उपयोग करें।
* duplicate image स्वीकार्य न हों तो retry से पहले अपनी request ID रिकॉर्ड करें।

## त्रुटि प्रबंधन

त्रुटियां सामान्यतः JSON लौटाती हैं। त्रुटि दिखाते समय पहले `error.message`, फिर `message`, फिर HTTP status text पढ़ें।

| HTTP status | अर्थ                                               | क्या करें                                                                     |
| ----------- | -------------------------------------------------- | ----------------------------------------------------------------------------- |
| `400`       | malformed JSON, missing parameter या असमर्थित size | request body जांचें। अपने-आप retry न करें।                                    |
| `401`       | API Key अनुपस्थित या अमान्य है                     | `Authorization: Bearer YOUR_API_KEY` header जांचें।                           |
| `402`       | अपर्याप्त balance या quota                         | balance जोड़ें या उपलब्ध key उपयोग करें।                                      |
| `429`       | rate limit, concurrency limit या व्यस्त upstream   | प्रतीक्षा करें और exponential backoff से retry करें।                          |
| `5xx`       | gateway या upstream विफलता                         | अनुरोध retry करें। फिर भी विफल हो तो request ID और त्रुटि संदेश रिकॉर्ड करें। |

## एकीकरण जांचसूची

* Base URL `https://www.bettertoken.ai/v1` है।
* header में `Authorization: Bearer YOUR_API_KEY` है।
* अनुरोध `application/json` और `POST /images/generations` उपयोग करता है।
* `model` `gpt-image-2`, `response_format` `b64_json`, `output_format` `png` और `n` `1` है।
* `size` अनुशंसित मानों में से है, जैसे `1024x1024`।
* HTTP client generation के लिए कई मिनट की अनुमति देता है।

## संबंधित दस्तावेज

* [Image to image](/hi/api-reference/images-edits)
* [GPT Image 2 अब उपलब्ध है](/hi/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.

````