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

# Справочник по официальному API генерации изображений по тексту Grok Imagine

> Справочник и интерактивное тестирование официального API генерации изображений по тексту Grok Imagine — три модели, уровни разрешения 1k / 1.5k / 2k, качество low / medium в 2.0, тарификация по уровням аналогично xAI

> [!WARNING]
>
> **🔒 Требуется группа `GrokOfficial`, доступ предоставляется по заявке**: Grok Imagine Official не входит в группу `Default`; перед вызовом необходимо запросить доступ (включая Playground на этой странице). Без доступа или с pay-per-request Token каждый вызов возвращает `503`. См. [Обзор Grok Imagine Official — Настройка группы](/ru/api-capabilities/grok-imagine-image-official/overview#group-setup).

> [!NOTE]
>
> Интерактивный Playground справа позволяет протестировать эндпоинт напрямую. Введите свой API Key в **Authorization** (формат: `Bearer sk-xxx`), заполните `prompt`, выберите модель, `resolution` и `aspect_ratio` (а также `quality` для 2.0) и выполните отправку.

> [!TIP]
>
> **Когда использовать эту страницу**: генерация изображений по тексту, одно изображение за вызов. Этот канал пока не поддерживает редактирование изображений — для редактирования на основе референсов или создания нескольких изображений за вызов используйте [Grok Imagine Reverse](/ru/api-capabilities/grok-imagine-image/overview).

> [!WARNING]
>
> **⚠️ Три самые распространенные ошибки**
>
> 1. **Используйте `resolution`, а не `size`**: `size` не привязан к уровню разрешения, поэтому изображение генерируется и тарифицируется по умолчанию как `1k`.
> 2. **Ошибки возвращают код ошибки**: выход `resolution` / `aspect_ratio` за пределы диапазона возвращает 422, а `quality: "high"` возвращает 400 — в отличие от незаметного отката к значениям по умолчанию в reverse-канале.
> 3. **Всегда передавайте `n` = 1**: для получения нескольких изображений отправляйте несколько параллельных запросов.

> [!NOTE]
>
> Все API генерации изображений являются **синхронными**: идентификатор асинхронной задачи отсутствует, поэтому при отключении клиента результат будет потерян, но запрос все равно тарифицируется. Генерация `grok-imagine-image-2.0` при `medium` и 2K занимает около 60–80 секунд, поэтому **установите таймаут клиента на 360 секунд**. См. [Примечания и рекомендации по Image API](/ru/api-capabilities/image-api-best-practices).

## Примеры кода

### Python (OpenAI SDK)

```python theme={null}
from openai import OpenAI
import urllib.request

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.apiyi.com/v1",
    timeout=360.0  # the image API is synchronous; give it a generous timeout
)

resp = client.images.generate(
    model="grok-imagine-image-2.0",
    prompt="A photorealistic red wooden boat moored on a glassy alpine lake at dawn, "
           "mist over the water, snow-capped peaks behind, cinematic photography",
    n=1,
    # resolution / aspect_ratio / quality are not standard OpenAI SDK fields; put them in extra_body
    extra_body={
        "resolution": "1.5k",
        "aspect_ratio": "16:9",
        "quality": "medium"
    }
)

# The default response is an image link; download and store it right away
urllib.request.urlretrieve(resp.data[0].url, "out.png")
```

### Python (requests)

```python theme={null}
import requests
import base64

API_KEY = "sk-your-api-key"

response = requests.post(
    "https://api.apiyi.com/v1/images/generations",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "model": "grok-imagine-image-quality",
        "prompt": "Rainy cyberpunk city at night, close-up of neon signs, cinematic lighting",
        "n": 1,
        "resolution": "2k",
        "aspect_ratio": "9:16",
        "response_format": "b64_json"
    },
    timeout=360
).json()

# b64_json is plain base64 (no data: prefix); decode and write it
with open("out.png", "wb") as f:
    f.write(base64.b64decode(response["data"][0]["b64_json"]))
```

### cURL

```bash theme={null}
curl -X POST "https://api.apiyi.com/v1/images/generations" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-image",
    "prompt": "An orange cat in sunglasses sitting at a beach bar, photorealistic, warm sunset",
    "n": 1,
    "resolution": "1k",
    "aspect_ratio": "3:2"
  }'
```

### Node.js (fetch)

```javascript theme={null}
import fs from 'node:fs';

// Need 3 images: send 3 requests concurrently, each with n=1
const prompts = Array(3).fill('A serene Japanese garden with cherry blossoms, koi pond, golden hour');

const results = await Promise.all(prompts.map(prompt =>
    fetch('https://api.apiyi.com/v1/images/generations', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer sk-your-api-key'
        },
        body: JSON.stringify({
            model: 'grok-imagine-image-2.0',
            prompt,
            n: 1,
            resolution: '1k',
            aspect_ratio: '4:3',
            quality: 'low'
        }),
        signal: AbortSignal.timeout(360000)
    }).then(r => r.json())
));

for (const [i, data] of results.entries()) {
    const img = await fetch(data.data[0].url);
    fs.writeFileSync(`out-${i}.img`, Buffer.from(await img.arrayBuffer()));
}
```

## Краткий справочник по параметрам

| Параметр | Тип | Обязательный | По умолчанию | Примечания |
| - | - | - | - | - |
| `model` | string | ✅ | — | `grok-imagine-image` / `grok-imagine-image-quality` / `grok-imagine-image-2.0` |
| `prompt` | string | ✅ | — | Prompt на любом языке. Опишите объект, сцену, стиль и освещение |
| `n` | integer | ❌ | `1` | **Всегда 1** на этом канале; отправляйте параллельные запросы для большего количества |
| `resolution` | string | ❌ | `1k` | `1k` / `1.5k` / `2k` (в нижнем регистре), задает ценовой уровень; значения вне допустимого диапазона возвращают 422 |
| `aspect_ratio` | string | ❌ | `1:1` | Стандартные: `1:1` / `16:9` / `9:16` / `4:3` / `3:4` / `3:2` / `2:3`; значения вне допустимого диапазона возвращают 422 |
| `quality` | string | ❌ | `low` | Только для `grok-imagine-image-2.0`: `low` или `medium`; `high` возвращает 400 |
| `response_format` | string | ❌ | `url` | `url` возвращает ссылку на изображение; `b64_json` возвращает чистый base64 (без префикса `data:`) |

**Цена за изображение** (как у xAI):

| Модель | `1k` | `1.5k` | `2k` |
| - | - | - | - |
| `grok-imagine-image` | \$0.02 | \$0.02 | \$0.02 |
| `grok-imagine-image-quality` | \$0.05 | \$0.06 | \$0.07 |
| `grok-imagine-image-2.0` (`low`) | \$0.04 | \$0.05 | \$0.06 |
| `grok-imagine-image-2.0` (`medium`) | \$0.06 | \$0.07 | \$0.08 |

> [!NOTE]
>
> Цены на модели синхронизированы с официальными сайтами и могут изменяться вслед за ними; таблица выше приведена исключительно для справки, а вкладка **Тарифы на модели** в верхней навигации имеет приоритет: [Тарифы на модели](/en/models/index).

## Формат ответа

```json theme={null}
{
  "created": 0,
  "data": [
    { "url": "https://.../sync_xxxxxxxx_0.png" }
  ],
  "usage": {
    "prompt_tokens": 1000,
    "total_tokens": 1000
  }
}
```

> [!NOTE]
>
> * Каждый элемент в `data[]` содержит **либо** `url`, либо `b64_json`, в зависимости от `response_format`.
> * Скачивайте изображения по полученным ссылкам сразу же; не используйте эти ссылки для постоянного обращения.
> * `usage` является плейсхолдером (`prompt_tokens` всегда `1000 × image count`) и **не может использоваться для сверки** — определяющими являются записи тарификации в консоли.
> * `created` всегда равен 0; не используйте его для измерения времени.

## Связанная документация

* [Grok Imagine: официальный обзор](/ru/api-capabilities/grok-imagine-image-official/overview) — цены, применение группы, официальный релей против reverse
* [Grok Imagine: видео](/ru/api-capabilities/grok-imagine-video/overview) — та же группа, посекундная тарификация
* [Grok Imagine: reverse](/ru/api-capabilities/grok-imagine-image/overview) — редактирование изображений и несколько изображений за вызов


## OpenAPI

````yaml api-reference/grok-imagine-image-official-generate-openapi-en.yaml POST /v1/images/generations
openapi: 3.1.0
info:
  title: Grok Imagine Official Text-to-Image API
  description: >
    xAI Grok Imagine official channel — text-to-image endpoint, priced the same
    as xAI and billed by resolution and quality tier.


    - Three models: `grok-imagine-image` (\$0.02 per image at every tier),
    `grok-imagine-image-quality` (\$0.05 / \$0.06 / \$0.07),
    `grok-imagine-image-2.0` (`low` \$0.04–0.06, `medium` \$0.06–0.08)

    - Resolutions `1k` / `1.5k` / `2k`, set with `resolution` — **do not send
    `size`** (it is not mapped and the image is generated and billed at the
    default 1k)

    - Strict validation: out-of-range `resolution` / `aspect_ratio` returns 422,
    `quality: high` returns 400

    - `n` is fixed at 1 on this channel; call concurrently for more images.
    Image editing is not offered yet


    **Authentication**: add `Authorization: Bearer YOUR_API_KEY` to the request
    headers


    **API Key setup**: the Token group must include **`GrokOfficial`** (granted
    on application) with billing mode **Pay-as-you-go Priority** or
    **Pay-as-you-go**; without access, or with a pay-per-request Token, calls
    return 503


    **Get an API Key**: create a Token in the [APIYI
    console](https://api.apiyi.com/token)
  version: 1.0.0
servers:
  - url: https://api.apiyi.com
    description: Primary endpoint
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      tags:
        - Text-to-Image
      summary: 'Text-to-image: generate an image from a prompt (official channel)'
      description: >
        Generate one image from a text prompt on the Grok Imagine official
        channel.


        - Required: `model`, `prompt`

        - Optional: `resolution`, `aspect_ratio`, `quality` (2.0 only),
        `response_format`

        - Synchronous; 2.0 at `medium` and 2K takes about 60–80 seconds, so use
        a client timeout of at least 360 seconds

        - No reference images: an `image` field is ignored and the image is
        generated from the prompt alone
      operationId: generateGrokImagineOfficialTextToImage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GrokImagineOfficialGenerateRequest'
      responses:
        '200':
          description: Image generated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageResponse'
        '400':
          description: >-
            Invalid `quality` (such as `high`); the message lists the allowed
            values
        '401':
          description: Unauthorized - invalid API Key
        '422':
          description: '`resolution` / `aspect_ratio` outside the allowed set (not billed)'
        '429':
          description: Rate limit hit or insufficient balance
        '503':
          description: >-
            Token lacks the `GrokOfficial` group, or uses pay-per-request
            billing
      security:
        - bearerAuth: []
components:
  schemas:
    GrokImagineOfficialGenerateRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: >
            Model ID:

            - `grok-imagine-image` — standard, \$0.02 per image at every
            resolution

            - `grok-imagine-image-quality` — high quality, \$0.05 / \$0.06 /
            \$0.07 at 1k / 1.5k / 2k

            - `grok-imagine-image-2.0` — newer model, `low` \$0.04 / \$0.05 /
            \$0.06, `medium` \$0.06 / \$0.07 / \$0.08
          enum:
            - grok-imagine-image
            - grok-imagine-image-quality
            - grok-imagine-image-2.0
          default: grok-imagine-image
        prompt:
          type: string
          description: >-
            Prompt in any language. Describe the subject, scene, style, and
            lighting in detail
          example: >-
            A photorealistic red wooden boat moored on a glassy alpine lake at
            dawn, mist over the water, snow-capped peaks behind, cinematic
            photography
        'n':
          type: integer
          description: >-
            Image count. Fixed at 1 on this channel; call concurrently for more
            images
          enum:
            - 1
          default: 1
        resolution:
          type: string
          description: >
            Resolution tier (lowercase), which also sets the price: `1k`
            (default) / `1.5k` / `2k`.


            Out-of-range values (such as `4k` or `1K`) return 422. **Do not use
            `size` instead** — it is not mapped to a resolution tier.
          enum:
            - 1k
            - 1.5k
            - 2k
          default: 1k
        aspect_ratio:
          type: string
          description: >
            Output aspect ratio, default `1:1`. Measured examples:
            `grok-imagine-image` at `1k` + `3:2` outputs 1248×832; `-quality` at
            `2k` + `9:16` outputs 1584×2816.


            Out-of-range values (such as `5:7`) return 422.
          enum:
            - '1:1'
            - '16:9'
            - '9:16'
            - '4:3'
            - '3:4'
            - '3:2'
            - '2:3'
          default: '1:1'
        quality:
          type: string
          description: >
            Quality tier, **only for `grok-imagine-image-2.0`**: `low` (default)
            or `medium` (\$0.02 more per image, slower).


            `high` returns 400. The other two models take no `quality`.
          enum:
            - low
            - medium
        response_format:
          type: string
          description: >-
            Response format: `url` (default; download and store the image right
            away) or `b64_json` (plain base64, no `data:` prefix)
          enum:
            - url
            - b64_json
          default: url
    ImageResponse:
      type: object
      properties:
        created:
          type: integer
          description: Always 0; do not use it for timing
          example: 0
        data:
          type: array
          description: Image results (one item on this channel)
          items:
            type: object
            properties:
              url:
                type: string
                description: Image link, returned when `response_format=url`
              b64_json:
                type: string
                description: >-
                  Plain base64 image data, returned when
                  `response_format=b64_json`
        usage:
          type: object
          description: >-
            **Placeholder — do not reconcile with it.** `prompt_tokens` is
            always `1000 × image count`; the console billing records are
            authoritative
          properties:
            prompt_tokens:
              type: integer
              example: 1000
            total_tokens:
              type: integer
              example: 1000
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: API Key from the APIYI console (Token group must include GrokOfficial)

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.