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

# Grok Imagine 官转文生图 API 参考

> Grok Imagine 官转文生图 API 参考与在线调试 — 三款模型、1k / 1.5k / 2k 三档分辨率、2.0 支持 low / medium 画质，与官网同价按档计费

> [!WARNING]
>
> **🔒 需申请开通 `GrokOfficial` 分组**：Grok Imagine 官转不在 `Default` 默认分组，需申请开通后才能调用（含本页 Playground）。未开通、或令牌计费模式为「按次计费」时，调用固定返回 `503`。申请流程见 [Grok Imagine 官转概览 · 分组介绍](/api-capabilities/grok-imagine-image-official/overview#分组介绍)。

> [!NOTE]
>
> 右侧的交互式 Playground 支持直接在线调试。请在 **Authorization** 中填入你的 API Key（格式：`Bearer sk-xxx`），输入 `prompt`，选择模型、`resolution`、`aspect_ratio`（2.0 再选 `quality`）后一键发送即可。

> [!TIP]
>
> **场景说明**：本页用于「文本生成图片」，每次 1 张。本通道暂不开放图片编辑，需要基于参考图改图或单次多张，请使用 [Grok Imagine 官逆](/api-capabilities/grok-imagine-image/overview)。

> [!WARNING]
>
> **⚠️ 三个最容易踩的坑**
>
> 1. **用 `resolution`，不要用 `size`**：`size` 不会被换算成分辨率档，传了会按默认 `1k` 出图和计费。
> 2. **参数写错会报错**：`resolution` / `aspect_ratio` 不在枚举内返回 422，`quality: "high"` 返回 400——这与官逆通道「静默回退」的行为相反。
> 3. **`n` 固定传 1**：需要多张请并发发起多次请求。

> [!NOTE]
>
> 图片 API 全部为**同步调用**：没有异步任务 ID，客户端断开连接结果即丢失、但请求仍会计费。`grok-imagine-image-2.0` 的 `medium` 档 2K 约 60–80 秒，**建议客户端超时设到 360 秒**，详见 [图片 API 调用须知与最佳实践](/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  # 图片 API 是同步调用，超时要给足
)

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 不是 OpenAI SDK 的标准字段，要放进 extra_body
    extra_body={
        "resolution": "1.5k",
        "aspect_ratio": "16:9",
        "quality": "medium"
    }
)

# 默认返回图片链接，请立即下载转存
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": "赛博朋克城市雨夜，霓虹招牌特写，电影感打光",
        "n": 1,
        "resolution": "2k",
        "aspect_ratio": "9:16",
        "response_format": "b64_json"
    },
    timeout=360
).json()

# b64_json 是纯 base64（不带 data: 前缀），直接 decode 写文件
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": "一只戴墨镜的橘猫坐在海边吧台，写实摄影，暖色调夕阳",
    "n": 1,
    "resolution": "1k",
    "aspect_ratio": "3:2"
  }'
```

### Node.js（原生 fetch）

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

// 需要 3 张图：并发 3 次请求，每次 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 | ✅ | — | 提示词，支持中英文。建议描述主体、场景、风格、光线 |
| `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]
>
> 模型价格与官网对齐，且可能随官网调整；上表仅供参考，具体以顶部导航「模型价格」栏目为准：[模型价格](/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 × 张数`），**不能用来核账**，以控制台账单为准。
> * `created` 恒为 0，不要拿来计时。

## 相关文档

* [Grok Imagine 官转概览](/api-capabilities/grok-imagine-image-official/overview) - 定价、分组申请、官转与官逆对比
* [Grok Imagine 视频生成](/api-capabilities/grok-imagine-video/overview) - 同一分组，按秒计费
* [Grok Imagine 官逆](/api-capabilities/grok-imagine-image/overview) - 支持图片编辑与单次多张


## OpenAPI

````yaml api-reference/grok-imagine-image-official-generate-openapi.yaml POST /v1/images/generations
openapi: 3.1.0
info:
  title: Grok Imagine 官转文生图 API
  description: >
    xAI Grok Imagine 官方通道（官转）— 文生图接口，与 xAI 官网同价，按分辨率与画质档计费。


    - 三个模型：`grok-imagine-image`（各档 \$0.02/张）、`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）

    - 分辨率 `1k` / `1.5k` / `2k`；用 `resolution` 控制，**不要传 `size`**（不会被换算，按默认 1k
    出图计费）

    - 参数校验严格：枚举外的 `resolution` / `aspect_ratio` 返回 422，`quality: high` 返回 400

    - 本通道 `n` 固定为 1，多张请并发调用；暂不开放图片编辑


    **认证方式**：在请求头中添加 `Authorization: Bearer YOUR_API_KEY`


    **API Key 配置**：令牌分组需包含 **`GrokOfficial`**（需申请开通），计费模式选 **按量优先** 或
    **按量计费**；未开通或按次计费令牌会返回 503


    **获取 API Key**：访问 [API易控制台](https://api.apiyi.com/token) 创建令牌
  version: 1.0.0
servers:
  - url: https://api.apiyi.com
    description: 主要端点
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      tags:
        - 文生图
      summary: 文生图：根据文本提示词生成图片（官转）
      description: |
        使用 Grok Imagine 官转通道根据文本提示词生成 1 张图片。

        - 必填：`model`、`prompt`
        - 可选：`resolution`、`aspect_ratio`、`quality`（仅 2.0）、`response_format`
        - 同步调用，2.0 `medium` 档 2K 约 60–80 秒，客户端超时建议 ≥ 360 秒
        - 不接受参考图：传入 `image` 会被忽略，只按提示词出图
      operationId: generateGrokImagineOfficialTextToImage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GrokImagineOfficialGenerateRequest'
      responses:
        '200':
          description: 成功生成图片
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageResponse'
        '400':
          description: '`quality` 取值非法（如 `high`），错误信息会列出合法值'
        '401':
          description: 未授权 - API Key 无效
        '422':
          description: '`resolution` / `aspect_ratio` 不在支持的枚举内（不计费）'
        '429':
          description: 请求频率超限或额度不足
        '503':
          description: 令牌未开通 `GrokOfficial` 分组，或令牌计费模式为按次计费
      security:
        - bearerAuth: []
components:
  schemas:
    GrokImagineOfficialGenerateRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: >
            模型 ID：

            - `grok-imagine-image` —— 标准版，各分辨率均 \$0.02/张

            - `grok-imagine-image-quality` —— 高质量版，1k / 1.5k / 2k 为 \$0.05 /
            \$0.06 / \$0.07

            - `grok-imagine-image-2.0` —— 新一代，`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: 提示词，支持中英文。建议详细描述主体、场景、风格、光线
          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: 出图数量。本通道固定为 1，需要多张请并发调用
          enum:
            - 1
          default: 1
        resolution:
          type: string
          description: |
            分辨率档位（小写），决定计费档：`1k`（默认）/ `1.5k` / `2k`。

            枚举外的值（如 `4k`、`1K`）返回 422。**不要用 `size` 代替**，`size` 不会被换算成分辨率档。
          enum:
            - 1k
            - 1.5k
            - 2k
          default: 1k
        aspect_ratio:
          type: string
          description: >
            输出宽高比，默认 `1:1`。实测示例：`grok-imagine-image` 的 `1k` + `3:2` 输出
            1248×832；`-quality` 的 `2k` + `9:16` 输出 1584×2816。


            枚举外的值（如 `5:7`）返回 422。
          enum:
            - '1:1'
            - '16:9'
            - '9:16'
            - '4:3'
            - '3:4'
            - '3:2'
            - '2:3'
          default: '1:1'
        quality:
          type: string
          description: >
            画质档，**仅 `grok-imagine-image-2.0` 有效**：`low`（默认）或 `medium`（单价高
            \$0.02，更慢）。


            传 `high` 返回 400。另外两个模型不需要传。
          enum:
            - low
            - medium
        response_format:
          type: string
          description: 返回格式：`url`（默认，图片链接，请立即下载转存）或 `b64_json`（纯 base64，不带 `data:` 前缀）
          enum:
            - url
            - b64_json
          default: url
    ImageResponse:
      type: object
      properties:
        created:
          type: integer
          description: 恒为 0，不可用于计时
          example: 0
        data:
          type: array
          description: 图片结果数组（本通道 1 项）
          items:
            type: object
            properties:
              url:
                type: string
                description: 图片链接，`response_format=url` 时返回
              b64_json:
                type: string
                description: 纯 base64 图片数据，`response_format=b64_json` 时返回
        usage:
          type: object
          description: '**占位值，不能用于核账。** `prompt_tokens` 恒为 `1000 × 张数`，真实扣费以控制台账单为准'
          properties:
            prompt_tokens:
              type: integer
              example: 1000
            total_tokens:
              type: integer
              example: 1000
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 在 API易控制台获取的 API Key（令牌分组需包含 GrokOfficial）

````

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