> ## 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 官轉概覽 · 分組介紹](/zh-Hant/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 官逆](/zh-Hant/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 呼叫須知與最佳實踐](/zh-Hant/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]
>
> 模型價格與官網對齊，且可能隨官網調整；上表僅供參考，具體以頂部導航「模型價格」欄目為準：[模型價格](/zh-Hant/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 官轉概覽](/zh-Hant/api-capabilities/grok-imagine-image-official/overview) - 定價、分組申請、官轉與官逆對比
* [Grok Imagine 影片生成](/zh-Hant/api-capabilities/grok-imagine-video/overview) - 同一分組，按秒計費
* [Grok Imagine 官逆](/zh-Hant/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.