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

# Grok Imagine 2.0 Ext 图像生成

>  - 异步文生图，返回 task_id 轮询结果
- 单次 1–12 张，按实际成功张数计费（$0.08/张）
- 仅支持 url 输出；不支持图生图 / 流式
- 图片链接有效期 72 小时 

> [!NOTE]
>
> **文生图 · 异步任务。** 提交 `POST /v1/images/generations` 后轮询 [获取任务状态](https://gccai.heqingsong.uk/cn/api-reference/tasks/status.md)。\
> 模型名固定 `grok-imagine-2.0-ext`；**不支持**参考图、`stream`、以及 `response_format` 除 `url` 以外的取值。
>
> 需要从已生成图片获取对象图层或编辑指定区域，请查看 [图层与选区编辑](https://gccai.heqingsong.uk/cn/api-reference/images/grok-imagine-2.0-ext/layer-region-edit.md)。

> [!WARNING]
>
> 不要把 API Key 写进浏览器包（`VITE_*` / `NEXT_PUBLIC_*`、LocalStorage 等）。推荐浏览器只调业务 BFF，由服务端持有 Key 调用本接口。

```bash cURL theme={null}
curl --request POST \
  --url https://gccai.heqingsong.uk/v1/images/generations \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --header 'Idempotency-Key: 8eacb46d-ef4e-4f4e-82de-830bd8bc67e2' \
  --header 'X-GccAi-Response-Version: 2026-07-27' \
  --data '{
    "model": "grok-imagine-2.0-ext",
    "prompt": "一只红苹果放在白色陶瓷盘上，干净的棚拍产品图",
    "n": 1,
    "size": "1:1",
    "resolution": "quality",
    "response_format": "url"
  }'
```

```python Python theme={null}
import requests
import uuid

url = "https://gccai.heqingsong.uk/v1/images/generations"

payload = {
    "model": "grok-imagine-2.0-ext",
    "prompt": "一只红苹果放在白色陶瓷盘上，干净的棚拍产品图",
    "n": 1,
    "size": "1:1",
    "resolution": "quality",
    "response_format": "url",
}

headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Idempotency-Key": str(uuid.uuid4()),
    "X-GccAi-Response-Version": "2026-07-27",
}

response = requests.post(url, json=payload, headers=headers)

print(response.status_code, response.json())
```

```javascript JavaScript theme={null}
const url = "https://gccai.heqingsong.uk/v1/images/generations";

const payload = {
  model: "grok-imagine-2.0-ext",
  prompt: "一只红苹果放在白色陶瓷盘上，干净的棚拍产品图",
  n: 1,
  size: "1:1",
  resolution: "quality",
  response_format: "url",
};

const headers = {
  Authorization: "Bearer <token>",
  "Content-Type": "application/json",
  Accept: "application/json",
  "Idempotency-Key": crypto.randomUUID(),
  "X-GccAi-Response-Version": "2026-07-27",
};

fetch(url, {
  method: "POST",
  headers: headers,
  body: JSON.stringify(payload),
})
  .then(async (response) => {
    console.log(response.status, await response.json());
  })
  .catch((error) => console.error("Error:", error));
```

```json 202 theme={null}
{
  "code": 202,
  "request_id": "2026081111342261665927mpb4IPDb",
  "data": {
    "id": "task_01KZQE5CM0Y3KZ6M1N1BK619MX",
    "object": "generation.task",
    "type": "image",
    "status": "pending",
    "progress": 0,
    "poll_url": "/v1/tasks/task_01KZQE5CM0Y3KZ6M1N1BK619MX"
  }
}
```

```json 400 theme={null}
{
  "request_id": "20260811...",
  "error": {
    "message": "`response_format` for grok-imagine-2.0-ext only supports `url` (got: b64_json)",
    "type": "invalid_response_format",
    "param": "",
    "code": "invalid_response_format"
  }
}
```

```json 401 theme={null}
{
  "error": {
    "code": 401,
    "message": "身份验证失败，请检查您的API密钥",
    "type": "authentication_error"
  }
}
```

```json 402 theme={null}
{
  "error": {
    "code": 402,
    "message": "账户余额不足，请充值后再试",
    "type": "payment_required"
  }
}
```

```json 429 theme={null}
{
  "error": {
    "code": 429,
    "message": "请求过于频繁，请稍后再试",
    "type": "rate_limit_error"
  }
}
```

## 能力与限制

| 维度 | 说明 |
| - | - |
| 模型名 | 固定 `grok-imagine-2.0-ext` |
| 能力 | **仅文生图** |
| 调用方式 | 异步任务 |
| 张数 `n` | `1`–`12`，默认 `1` |
| 比例 `size` | 7 种比例 + 5 种兼容像素写法（见下） |
| 输出 | 仅 `response_format=url`（默认亦为 `url`） |
| 质量 | 对外字段为 `resolution`；已验证值 `quality` |
| 不支持 | 图生图、`stream=true`、`quality` 字段、`style`、`b64_json` / `base64` |
| 计费 | 固定单价，按**实际成功交付张数**计费 |

## 认证与推荐 Header

**Authorization** `string` *required*

Bearer Token。访问 [API Key 管理页面](https://gccai.heqingsong.uk/keys) 获取。

```
Authorization: Bearer YOUR_API_KEY
```

| Header | 说明 |
| - | - |
| `Content-Type` | `application/json`（提交） |
| `Accept` | `application/json` |
| `Idempotency-Key` | 强烈建议。每次「用户确认的一次逻辑生成」用新 UUID；网络重试**必须复用**同一 key 与 body |
| `X-GccAi-Response-Version` | 推荐 `2026-07-27`，获得稳定的提交响应结构（`data.id`） |

## 请求参数

**model** `string` *required*

固定值：`grok-imagine-2.0-ext`

**nsfw\_check** `boolean` (default: false)

是否在提交图片任务前执行内容审核。

* `true`：使用 `omni-moderation-latest` 审核提示词和输入图片
* `false` 或不传：不发起审核请求，不增加审核成本与延迟（默认）

**prompt** `string` *required*

提示词。去空格后不能为空。提交前请 `trim`。

**n** `integer` (default: 1)

生成张数：`1`–`12`。显式传 `0` 会报错。未传按 `1`。

**size** `string`

画面比例。**推荐使用比例写法**（UI 建议只展示比例）：

| `size` | 方向 | 典型用途 |
| - | - | - |
| `1:1` | 正方形 | 商品图、头像 |
| `2:3` | 竖图 | 海报、人物全身 |
| `3:2` | 横图 | 摄影、横向场景 |
| `3:4` | 竖图 | 电商、人物图 |
| `4:3` | 横图 | 展示图 |
| `9:16` | 竖屏 | 短视频封面、Story |
| `16:9` | 宽屏 | Banner、视频封面 |

兼容像素写法：`1024x1024`（1:1）、`1024x1792`（2:3）、`1792x1024`（3:2）、`720x1280`（9:16）、`1280x720`（16:9）。

不在白名单内的值返回 `400 invalid_size`（如 `1:2`、`2:1`、`4:5`、`auto`）。

> [!NOTE]
>
> 同一比例下实际像素可能与兼容表不完全一致（例如 `1:1` 可能返回 1408×1408）。请以返回图片为准，不要反推改写 `size`。

**resolution** `string`

质量模式字段。当前已验证值：`quality`。

* 可省略（模型本身为质量模式）
* 或显式传 `resolution: "quality"`

**不要**把它理解成 `1K` / `2K` / `4K` 像素档；画面方向与比例由 `size` 控制。

> [!WARNING]
>
> 不要传公开字段 `quality`，会返回 `400 invalid_quality`。请使用 `resolution`。

**response\_format** `string` (default: url)

仅支持 `url`。可省略。传 `b64_json` / `base64` 会 `400 invalid_response_format`。

**webhook** `string`

可选。公网 HTTPS **base URL**；任务终态时平台会请求 `{webhook}/callback`。仅服务端集成使用，见 [Webhook](#webhook可选)。

### 明确不支持的参数

| 参数 | 行为 |
| - | - |
| `quality` | `400 invalid_quality` → 改传 `resolution` |
| `style` | `400 invalid_style` |
| `image_urls` / `image_with_roles` | `400 invalid_image_input` |
| `stream: true` | `400 invalid_stream` |
| `response_format: "b64_json"` / `"base64"` | `400 invalid_response_format` |

请用白名单组装请求，不要把其他图片模型的表单对象整体透传。

## 请求示例

### 最简

```json theme={null}
{
  "model": "grok-imagine-2.0-ext",
  "prompt": "一只红苹果放在白色陶瓷盘上，干净的棚拍产品图"
}
```

### 推荐

```json theme={null}
{
  "model": "grok-imagine-2.0-ext",
  "prompt": "一只红苹果放在白色陶瓷盘上，干净的棚拍产品图",
  "n": 1,
  "size": "1:1",
  "resolution": "quality",
  "response_format": "url"
}
```

## 提交响应

推荐携带 `X-GccAi-Response-Version: 2026-07-27`。成功时 HTTP **`202`**，任务 ID 在 **`data.id`**（不要依赖旧格式 `data[0].task_id`）。

请保存：

* `data.id`：任务 ID，用于轮询
* `request_id`：排查网关问题
* 本次 `Idempotency-Key`：结果不确定时安全重试
* 原始请求参数：展示与排查

## 幂等与安全重试

图片生成会计费，提交时**强烈建议**带 `Idempotency-Key`（1–191 个可见 ASCII 字符，UUID 最省心；记录保留 24 小时）。

| 场景 | 表现 | 处理 |
| - | - | - |
| 同 key、同请求已完成 | 重放原响应，Header `Idempotency-Replayed: true` | 使用同一任务 ID |
| 同 key 仍处理中 | `409 idempotency_in_progress` + `Retry-After` | 等待后用**同 key、同 body** 重试 |
| 同 key、不同参数 | `409 idempotency_key_reused` | 新逻辑请求应换新 key |
| 原结果不确定 | `409 idempotency_result_indeterminate` | 停止换 key，保留原 key 排查 |

POST 网络超时、无法判断是否已创建任务时，**不要立刻换新 key**；用相同 key / body / 响应版本重试。

## 查询任务

```http theme={null}
GET /v1/tasks/{task_id}?language=zh
Authorization: Bearer YOUR_API_KEY
Accept: application/json
```

`language` 可选：`zh` / `en` / `ko` / `ja`，仅影响失败文案本地化。详见 [获取任务状态](https://gccai.heqingsong.uk/cn/api-reference/tasks/status.md)。

### 状态

| `status` | 终态 | 处理 |
| - | :-: | - |
| `pending` / `processing` | 否 | 继续轮询（进行中可能没有 `result`，不要判失败） |
| `completed` | ✅ | 解析 `result.images` |
| `failed` | ✅ | 展示 `error.message`；`cost` 为 `0`（预扣退款） |
| `unknown` | 否 | 短暂重试；持续存在时带 task ID 联系支持 |

建议约每 **2 秒**查一次；最长约 **10 分钟**或 **120 次**。遇 `429` 遵循 `Retry-After`。任务默认保留约 3 天，轮询超时后仍应保存 task ID。

### 完成态示例

```json theme={null}
{
  "code": 200,
  "data": {
    "id": "task_01KZQE5CM0Y3KZ6M1N1BK619MX",
    "status": "completed",
    "progress": 100,
    "created": 1786419262,
    "completed": 1786419275,
    "actual_time": 13,
    "estimated_time": 100,
    "cost": 0.08,
    "credits_cost": 0.8,
    "result": {
      "images": [
        {
          "expires_at": 1786505675,
          "url": [
            "https://example.com/image/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.jpg"
          ],
          "image_ids": [
            "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
          ]
        }
      ]
    }
  }
}
```

### 解析 `url` 与 `image_ids`

```text theme={null}
result.images[]
  ├─ url[]          ← 展示/下载的权威字段（数组）
  ├─ image_ids[]    ← 可选，不透明 ID
  └─ expires_at     ← Unix 秒；前端倒计时需 ×1000
```

1. 取图用 `url[]`；`n>1` 时遍历全部，不要只取第一张
2. 仅当 `image_ids.length === url.length` 时按下标配对
3. `image_ids` 缺失不影响展示
4. 链接有效期 **72 小时**，请及时下载；同时以返回的 `expires_at` 为准

## 计费

基础价 **\$0.08 / 张**（按实际成功交付张数）：

| `n` | 预计基础金额 |
| -: | -: |
| 1 | \$0.08 |
| 4 | \$0.32 |
| 8 | \$0.64 |
| 12 | \$0.96 |

* 下单前展示「预计」；任务完成后的 **`data.cost`** 为最终美元金额
* **`data.credits_cost`** 为积分口径（当前约 = 美元 × 10）
* 提交按请求张数预扣；最终按成功张数对账，部分失败退差额
* 整单失败：`cost=0`，预扣退款
* 不要用 `resolution` 拼价格档；本模型统一按张价

## Webhook（可选）

```json theme={null}
{
  "webhook": "https://your-service.example.com/gccai"
}
```

* 填 **base URL**，平台请求 `{base}/callback`
* 须公网可访问并通过 SSRF 校验
* 若配置了 `webhook_secret`，签名为 `hex(HMAC-SHA256(secret, raw_body))`，须用原始请求字节验签
* 回调体与任务查询的 `data` 同源（不再包一层 `{code,data}`）
* 仍建议低频轮询兜底

## 常见错误

| HTTP | `error.code` | 原因 | 处理 |
| -: | - | - | - |
| 400 | `invalid_request` | prompt 为空或 JSON 非法 | 校验输入 |
| 400 | `invalid_n` | `n` 不在 1–12 | 限制张数 |
| 400 | `invalid_size` | size 不在白名单 | 使用固定下拉 |
| 400 | `invalid_response_format` | 非 `url` | 固定或省略 |
| 400 | `invalid_quality` | 误传 `quality` | 改 `resolution` |
| 400 | `invalid_style` | 传了 `style` | 移除 |
| 400 | `invalid_image_input` | 传了参考图 | 换支持图生图的模型 |
| 400 | `invalid_stream` | `stream=true` | 移除 |
| 400 | `invalid_idempotency_key` | key 非法 | 使用 UUID |
| 401 | 鉴权失败 | Key 无效 | 服务端检查凭据 |
| 402 | 余额不足 | 余额不足 | 引导充值 |
| 409 | `idempotency_*` | 幂等冲突 | 见上文幂等表 |
| 429 | 限流 | 过快 | 按 `Retry-After` 退避 |
| 5xx | 服务异常 | — | 保留 Idempotency-Key，勿盲目换 key |

错误提示优先用 `error.message`。不要把鉴权细节或内部信息直接展示给终端用户。

## 与 1.5 的差异（摘要）

| 项 | Grok Imagine 1.5 | 2.0 Ext |
| - | - | - |
| 模型名 | `grok-imagine-1.5-gccai` 等 | `grok-imagine-2.0-ext` |
| 图生图 | 支持参考图编辑 | **不支持** |
| 张数 | 视 1.5 文档 | **1–12** |
| 质量字段 | 见 1.5 文档 | 用 `resolution`（`quality`），勿传 `quality` |
| 输出 | 见 1.5 文档 | **仅 url** |
| 链接有效期 | 见 1.5 文档（常见 24h） | **72 小时** |
| 单价 | 见 1.5 文档 | **\$0.08 / 张** |


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