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

# Текст в изображение (генерация изображений)

> Генерируйте изображения из текстовых prompt через GPT Image2 и OpenAI-совместимый API BetterToken.

`POST /v1/images/generations`

Endpoint text-to-image использует тело запроса `application/json`. Передайте prompt, держите HTTP-запрос открытым и прочитайте готовое изображение из `data[0].b64_json` в том же ответе.

<Note>
  Используйте `https://www.bettertoken.ai/v1` как `Base URL`. API Key BetterToken передается через `Authorization: Bearer YOUR_API_KEY`.
</Note>

<Tip>
  В Playground справа можно заполнить `Authorization` и тело запроса, а затем отправить запрос напрямую на `https://www.bettertoken.ai/v1/images/generations`.
</Tip>

<Warning>
  Не помещайте API keys во frontend-код браузера, Git-репозитории, тикеты, скриншоты или логи. Для server-side proxy calls храните ключи только в переменных окружения сервера или secret manager.
</Warning>

## Рекомендуемые значения

Передавайте эти поля явно в каждом запросе:

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

Чтобы сгенерировать несколько изображений, отправляйте несколько независимых запросов. Не рассчитывайте на один запрос с `n > 1`.

## Рекомендуемые размеры

| `size`      | Соотношение | Сценарий                                                            |
| ----------- | ----------- | ------------------------------------------------------------------- |
| `auto`      | Auto        | Автоматический выбор размера                                        |
| `1024x1024` | `1:1`       | Квадратные изображения, аватары, обложки, assets                    |
| `1536x1024` | `3:2`       | Landscape-постеры, баннеры, сцены                                   |
| `1024x1536` | `2:3`       | Portrait-обложки для мобильных и постеры                            |
| `1536x1152` | `4:3`       | Стандартные landscape-изображения, product images, content graphics |
| `1152x1536` | `3:4`       | Стандартные portrait-изображения, mobile covers, vertical posters   |
| `2048x2048` | `1:1`       | High-resolution квадратные изображения                              |
| `2048x1152` | `16:9`      | High-resolution landscape-изображения                               |
| `3840x2160` | `16:9`      | 4K landscape-изображения                                            |
| `2160x3840` | `9:16`      | 4K portrait-изображения                                             |

`size` задает ожидаемое соотношение сторон и уровень размера. Фактические пиксели в ответе могут быть сопоставлены или скорректированы сервером. Используйте размеры декодированного изображения, а не принудительную обрезку до запрошенного значения.

## Сохранение изображения

Успешный ответ следует OpenAI-совместимой форме image response:

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

Прочитайте `data[0].b64_json` и сохраните его как base64 image content. Ответ может содержать дополнительные поля, например `revised_prompt`; клиент должен разрешать такие поля.

Всегда задавайте `output_format: "png"`. Затем сохраняйте декодированное изображение как `.png` без проверки file headers.

```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)
```

<Warning>
  Не рассчитывайте, что `output_format: "jpeg"` или `output_format: "webp"` сразу вернет JPEG или WebP-файл. Текущий endpoint может по-прежнему вернуть PNG. Если продукту нужен JPEG или WebP, сначала получите PNG и конвертируйте его в своем коде.
</Warning>

## Поток ответа

Endpoint синхронный. После отправки `POST /images/generations` держите текущий HTTP-запрос открытым до ответа сервера. При успешной генерации содержимое изображения возвращается в `data[0].b64_json`.

Endpoint не возвращает `task_id`; отдельного status query или endpoint для скачивания результата нет.

## Timeout и повторные попытки

* Задавайте timeout HTTP-клиента в несколько минут.
* Повторяйте transport errors, `408`, `409`, `425`, `429` и `5xx`.
* Не повторяйте автоматически `400`, `401`, отсутствующие параметры и некорректные запросы.
* Используйте exponential backoff, например `3s`, `8s`, `15s`.
* Если дубли изображений недопустимы, записывайте собственный request ID перед retry.

## Смежные документы

* [Image to image](/ru/api-reference/images-edits)
* [GPT Image 2 доступен](/ru/model-updates/gpt-image-2)


## OpenAPI

````yaml POST /v1/images/generations
openapi: 3.1.0
info:
  title: BetterToken GPT Image2 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 Image2
      summary: 文生图（图片生成）
      description: >-
        使用 GPT Image2 根据文本提示词生成图片。请求使用 application/json，成功响应中的图片内容位于
        data[0].b64_json。
      operationId: createImageGeneration
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TextToImageRequest'
            example:
              model: gpt-image-2
              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 sk-***REDACTED***' \
              -H 'Content-Type: application/json' \
              --data '{
                "model": "gpt-image-2",
                "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: 固定使用 gpt-image-2。
          enum:
            - gpt-image-2
          default: gpt-image-2
          example: gpt-image-2
        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.

````