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

# Grok Imagine Image 2.0 官方图像生成与编辑

>  - grok-imagine-image-2.0 官方异步图片接口
- 支持文生图、单图编辑与最多 3 张图片的多图参考
- 支持 1–10 张输出、1K / 2K 分辨率、14 种宽高比
- 提交后返回任务 ID，通过任务状态接口获取最终图片
- 推荐固定响应版本 2026-07-27，并使用 Idempotency-Key 防止重复扣费 

<Info>
  **异步图片接口。** 提交成功后返回任务 ID，请通过[获取任务状态](/cn/api-reference/tasks/status)接口轮询最终结果。
  不传 `image_urls` 即文生图；传入 `image_urls` 即图片编辑或多图参考。
</Info>

<Warning>
  不要把长期有效的 APIMart API Key 写入浏览器代码、`VITE_*` / `NEXT_PUBLIC_*`、LocalStorage、URL 或前端日志。生产环境应由业务后端或 BFF 持有 API Key 并调用本接口。
</Warning>

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/images/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --header 'Accept: application/json' \
    --header 'Idempotency-Key: 1c0a9cf6-6724-44d2-b64e-4db7373bc391' \
    --header 'X-APIMart-Response-Version: 2026-07-27' \
    --data '{
      "model": "grok-imagine-image-2.0",
      "prompt": "雨夜中霓虹灯照亮的电影感城市街道",
      "n": 1,
      "aspect_ratio": "16:9",
      "resolution": "2k",
      "quality": "medium"
    }'
  ```

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

  url = "https://api.apimart.ai/v1/images/generations"

  payload = {
      "model": "grok-imagine-image-2.0",
      "prompt": "雨夜中霓虹灯照亮的电影感城市街道",
      "n": 1,
      "aspect_ratio": "16:9",
      "resolution": "2k",
      "quality": "medium",
  }

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

  response = requests.post(url, json=payload, headers=headers)
  response.raise_for_status()
  print(response.json()["data"]["id"])
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1/images/generations";

  const payload = {
    model: "grok-imagine-image-2.0",
    prompt: "雨夜中霓虹灯照亮的电影感城市街道",
    n: 1,
    aspect_ratio: "16:9",
    resolution: "2k",
    quality: "medium",
  };

  const response = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: "Bearer <token>",
      "Content-Type": "application/json",
      Accept: "application/json",
      "Idempotency-Key": crypto.randomUUID(),
      "X-APIMart-Response-Version": "2026-07-27",
    },
    body: JSON.stringify(payload),
  });

  const body = await response.json();
  if (!response.ok) throw new Error(body.error?.message ?? "图片生成失败");
  console.log(body.data.id);
  ```
</RequestExample>

<ResponseExample>
  ```json 202 theme={null}
  {
    "code": 202,
    "request_id": "2026081415330012345678abcdef",
    "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": "req_xxx",
    "error": {
      "message": "参数不合法",
      "type": "invalid_request_error",
      "param": "aspect_ratio",
      "code": "invalid_request_error"
    }
  }
  ```

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

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

  ```json 409 theme={null}
  {
    "request_id": "req_xxx",
    "error": {
      "message": "原请求仍在处理中，请稍后使用相同参数重试",
      "type": "idempotency_error",
      "param": "",
      "code": "idempotency_in_progress"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "request_id": "req_xxx",
    "error": {
      "message": "请求过于频繁，请稍后重试",
      "type": "rate_limit_error",
      "param": "",
      "code": "rate_limit_error"
    }
  }
  ```
</ResponseExample>

## 接入概览

<CardGroup cols={3}>
  <Card title="异步任务" icon="clock">
    提交后返回任务 ID，通过任务状态接口获取最终结果。
  </Card>

  <Card title="生成与编辑" icon="wand-magic-sparkles">
    一个接口同时支持文生图、单图编辑和多图参考。
  </Card>

  <Card title="统一轮询" icon="arrows-rotate">
    使用返回的 `data.id` 请求任务状态接口，直到任务完成或失败。
  </Card>
</CardGroup>

| 场景   | `image_urls` | 处理方式           |
| ---- | -----------: | -------------- |
| 文生图  |          不发送 | 根据提示词生成图片      |
| 单图编辑 |          1 张 | 根据提示词编辑参考图     |
| 多图参考 |        2–3 张 | 按数组顺序融合或参考多张图片 |

<Note>
  提交成功时 HTTP 状态为 `202`，任务 ID 位于 `data.id`。使用 `data.poll_url` 或 `GET /v1/tasks/{task_id}` 轮询任务状态。
</Note>

## 模型能力

| 模型                       | 分辨率       | `quality`             |   输入图 |   输出张数 |
| ------------------------ | --------- | --------------------- | ----: | -----: |
| `grok-imagine-image-2.0` | `1k`、`2k` | 仅文生图支持 `low`、`medium` | 0–3 张 | 1–10 张 |

`quality` 的发送规则：

* 可选 `low`、`medium`，默认 `medium`；
* 请求含参考图时不要发送 `quality`；
* 添加参考图时，应清除表单中遗留的 `quality`。

## Authorizations

<ParamField header="Authorization" type="string" required>
  所有接口均使用 Bearer Token 认证。

  访问 [API Key 管理页面](https://apimart.ai/keys) 获取 API Key，并在请求头中添加：

  ```http theme={null}
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## 推荐请求头

| Header                       | 要求   | 说明                         |
| ---------------------------- | ---- | -------------------------- |
| `Authorization`              | 必须   | `Bearer <APIMart API Key>` |
| `Content-Type`               | 必须   | 固定 `application/json`      |
| `Accept`                     | 推荐   | 固定 `application/json`      |
| `Idempotency-Key`            | 强烈推荐 | 每次逻辑生成使用唯一 UUID；网络重试复用原值   |
| `X-APIMart-Response-Version` | 强烈推荐 | 固定为 `2026-07-27`，确保响应结构稳定  |

## Body

<ParamField body="model" type="string" default="grok-imagine-image-2.0" required>
  固定值：`grok-imagine-image-2.0`
</ParamField>

<ParamField body="prompt" type="string" required>
  图片生成或编辑的文本描述。去除首尾空格后不能为空，最多 8000 个字符。

  多图参考时，可以按数组顺序在提示词中使用 `<IMAGE_0>`、`<IMAGE_1>`、`<IMAGE_2>` 引用图片。
</ParamField>

<ParamField body="n" type="integer" default="1">
  输出图片张数，取值为 `1`–`10`。
</ParamField>

<ParamField body="aspect_ratio" type="string" default="auto">
  图片宽高比。支持：

  | 值                                  | 方向  | 常见用途         |
  | ---------------------------------- | --- | ------------ |
  | `auto`                             | 自动  | 根据提示词或参考图选择  |
  | `1:1`                              | 正方形 | 商品图、头像       |
  | `3:4` / `2:3`                      | 竖图  | 人像、海报        |
  | `4:3` / `3:2`                      | 横图  | 摄影、展示图       |
  | `9:16` / `9:19.5` / `9:20` / `1:2` | 竖屏  | Story、手机壁纸   |
  | `16:9` / `19.5:9` / `20:9` / `2:1` | 横屏  | 封面、Banner、壁纸 |

  允许值完整列表：`1:1`、`3:4`、`4:3`、`9:16`、`16:9`、`2:3`、`3:2`、`9:19.5`、`19.5:9`、`9:20`、`20:9`、`1:2`、`2:1`、`auto`。

  <Note>
    新接入不要发送像素尺寸字符串。画面比例由 `aspect_ratio` 控制，清晰度档位由 `resolution` 控制。
  </Note>
</ParamField>

<ParamField body="resolution" type="string" default="1k">
  图片清晰度档位：

  * `1k`（默认）
  * `2k`
</ParamField>

<ParamField body="quality" type="string">
  仅 `grok-imagine-image-2.0` **文生图**支持：

  * `low`
  * `medium`（2.0 文生图默认）

  <Warning>
    请求包含 `image_urls` 时不要发送本字段。
  </Warning>
</ParamField>

<ParamField body="image_urls" type="array">
  参考图片数组，允许 `1`–`3` 张。省略本字段即文生图。

  数组元素支持：

  1. 公网可访问的绝对 `http://` 或 `https://` URL；
  2. JPEG、PNG、WebP 的 Base64 Data URL。

  Data URL 示例：

  ```text theme={null}
  data:image/png;base64,iVBORw0KGgoAAA...
  ```

  * 不接受相对 URL、裸 Base64 或其它格式的 Data URL；
  * Data URL 解码后单张不超过 10 MiB；
  * 数组顺序会保留；
  * 重复图片按多张输入处理并按张计费；
  * 没有参考图时应省略本字段，不要发送空数组。
</ParamField>

## 使用示例

### 2.0 文生图

```json theme={null}
{
  "model": "grok-imagine-image-2.0",
  "prompt": "高级产品摄影，柔和棚拍光线，干净背景",
  "n": 1,
  "aspect_ratio": "1:1",
  "resolution": "2k",
  "quality": "medium"
}
```

### 单图编辑

```json theme={null}
{
  "model": "grok-imagine-image-2.0",
  "prompt": "将白天的天空替换成戏剧性的璀璨星空",
  "n": 1,
  "aspect_ratio": "auto",
  "resolution": "1k",
  "image_urls": [
    "https://cdn.example.com/source.png"
  ]
}
```

有参考图时不要发送 `quality`。

### 多图参考

```json theme={null}
{
  "model": "grok-imagine-image-2.0",
  "prompt": "使用 <IMAGE_0> 作为产品，使用 <IMAGE_1> 作为海报风格",
  "n": 1,
  "aspect_ratio": "4:3",
  "resolution": "2k",
  "image_urls": [
    "https://cdn.example.com/product.png",
    "https://cdn.example.com/style.webp"
  ]
}
```

## Response

<ResponseField name="code" type="integer">
  HTTP 业务状态码，提交成功时为 `202`。
</ResponseField>

<ResponseField name="request_id" type="string">
  本次请求的排查 ID。联系支持或记录错误时请保留。
</ResponseField>

<ResponseField name="data.id" type="string">
  任务 ID，用于查询任务状态。
</ResponseField>

<ResponseField name="data.object" type="string">
  异步任务固定为 `generation.task`。
</ResponseField>

<ResponseField name="data.status" type="string">
  提交成功时为 `pending`。
</ResponseField>

<ResponseField name="data.progress" type="integer">
  提交时通常为 `0`。
</ResponseField>

<ResponseField name="data.poll_url" type="string">
  任务查询路径。也可使用 `GET /v1/tasks/{task_id}` 查询。
</ResponseField>

<Note>
  轮询直到任务进入 `completed` 或 `failed`。完整字段请参阅[获取任务状态](/cn/api-reference/tasks/status)。
</Note>

## 上传本地参考图

如果用户选择本地文件，可先上传到平台，再把返回的 `url` 放入生成请求的 `image_urls`。

```http theme={null}
POST https://api.apimart.ai/v1/uploads/images
Authorization: Bearer <APIMart_API_KEY>
Content-Type: multipart/form-data
```

表单字段固定为 `file`：

```bash theme={null}
curl --request POST \
  --url https://api.apimart.ai/v1/uploads/images \
  --header 'Authorization: Bearer <token>' \
  --form 'file=@reference.png'
```

成功响应：

```json theme={null}
{
  "url": "https://cdn.example.com/image/reference.png",
  "filename": "reference.png",
  "content_type": "image/png",
  "bytes": 123456,
  "created_at": 1786690805
}
```

* 支持 JPEG、PNG、WebP；
* 单张图片不超过 10 MiB；
* 使用 `FormData` 时不要手动设置 `Content-Type`，客户端会自动添加 multipart boundary。

## 获取预估价格

价格应以报价接口返回的 `final_usd` 为准，不要在客户端硬编码价格或自行计算最终金额。

```http theme={null}
GET https://api.apimart.ai/api/pricing/image/quote
```

### 报价参数

| 参数             |  必填 | 说明                                |
| -------------- | :-: | --------------------------------- |
| `model`        |  是  | 与生成请求一致                           |
| `n`            |  否  | 与生成请求一致，默认 `1`                    |
| `aspect_ratio` |  否  | 与生成请求一致                           |
| `resolution`   |  否  | 与生成请求一致                           |
| `quality`      |  否  | 仅 2.0 文生图传入                       |
| `input_images` |  否  | 等于 `image_urls.length`，无参考图时为 `0` |

示例：

```http theme={null}
GET https://api.apimart.ai/api/pricing/image/quote?model=grok-imagine-image-2.0&resolution=2k&quality=medium&aspect_ratio=16:9&n=2&input_images=3
```

```json theme={null}
{
  "success": true,
  "data": {
    "model_name": "grok-imagine-image-2.0",
    "resolution": "2k",
    "aspect_ratio": "16:9",
    "quality": "medium",
    "image_count": 2,
    "unit_price_usd": 0.08,
    "input_images": 3,
    "input_surcharge_usd": 0.03,
    "final_usd": 0.19
  }
}
```

| 字段                                    | 用途               |
| ------------------------------------- | ---------------- |
| `final_usd`                           | 本次唯一应展示的预估总价     |
| `unit_price_usd`                      | 单张输出基础价，仅用于明细    |
| `input_surcharge_usd`                 | 全部参考图的基础加价，仅用于明细 |
| `image_count`                         | 服务端采用的输出数量       |
| `input_images`                        | 服务端采用的参考图数量      |
| `resolution`、`quality`、`aspect_ratio` | 服务端规范化后的参数       |

<Warning>
  不要用 `unit_price_usd × image_count + input_surcharge_usd` 替代 `final_usd`。用户折扣、分组价格和整单取整可能使自行计算的结果不同。
</Warning>

输入图片从第 1 张开始计费，费用按输入张数计算，不再乘输出数量 `n`。前端只需把 `image_urls.length` 作为 `input_images`，并展示报价返回的 `final_usd`。

需要读取当前 Web 登录用户的个性化报价时，请携带 Session Cookie：

```ts theme={null}
fetch(url, { credentials: "include" });
```

模型、`n`、`aspect_ratio`、`resolution`、`quality` 或参考图数量变化后，应重新报价。建议使用 `200–300ms` 防抖，并取消上一笔未完成的请求，防止旧响应覆盖新价格。

## 幂等与重试

图片生成会产生费用。每次用户确认的一次逻辑生成都应创建一个 `Idempotency-Key`。

1. 首次请求创建一个 UUID；
2. 同一次请求的网络重试复用原 UUID 和完全相同的请求 Body；
3. 修改模型、提示词、图片或其它参数后创建新 UUID；
4. 不要在每次自动重试时创建新 UUID；
5. 同一 Key 重试时，`X-APIMart-Response-Version` 也必须保持一致。

| 场景            | 响应                                     | 处理方式                                  |
| ------------- | -------------------------------------- | ------------------------------------- |
| 原请求已完成        | 重放原响应                                  | 使用原任务 ID 查询结果                         |
| 原请求仍在处理       | `409 idempotency_in_progress`          | 按 `Retry-After` 等待，使用原 Key 和原 Body 重试 |
| 同一 Key 对应不同参数 | `409 idempotency_key_reused`           | 客户端逻辑错误，修复 Key 生命周期                   |
| 请求结果无法确认      | `409 idempotency_result_indeterminate` | 停止自动重试，不要换 Key，记录 `request_id` 排查     |
| 幂等服务暂不可用      | `503 idempotency_unavailable`          | 当前请求未执行，稍后重试                          |

<Note>
  浏览器取消请求只表示客户端不再等待响应，不代表服务端生成已经取消，也不代表一定不会计费。
</Note>

## 错误处理

统一错误结构：

```json theme={null}
{
  "request_id": "req_xxx",
  "error": {
    "message": "具体错误信息",
    "type": "invalid_request_error",
    "param": "",
    "code": "invalid_request_error"
  }
}
```

| HTTP 状态 | 说明         | 建议处理                       |
| ------: | ---------- | -------------------------- |
|   `400` | 参数错误       | 展示服务端 `message`，不要自动重试     |
|   `401` | API Key 无效 | 检查认证信息                     |
|   `402` | 余额或额度不足    | 引导充值或联系管理员                 |
|   `403` | 权限不足       | 检查令牌和模型权限                  |
|   `409` | 幂等冲突       | 按上一节的幂等规则处理                |
|   `429` | 请求过快       | 按 `Retry-After` 退避，复用原 Key |
|   `5xx` | 服务异常       | 保留原 Key 和原 Body，按策略重试      |

建议记录 `request_id`、`Idempotency-Key`、模型名、HTTP 状态和错误 `code`。不要记录 API Key、完整 Data URL、用户隐私图片或包含敏感信息的完整提示词。

## TypeScript 服务端封装

以下代码应运行在业务后端或 BFF，不要放入包含长期 API Key 的浏览器产物。

```ts theme={null}
type GrokImageModel = "grok-imagine-image-2.0";

type GrokAspectRatio =
  | "1:1" | "3:4" | "4:3" | "9:16" | "16:9"
  | "2:3" | "3:2" | "9:19.5" | "19.5:9"
  | "9:20" | "20:9" | "1:2" | "2:1" | "auto";

interface GrokImageRequest {
  model: GrokImageModel;
  prompt: string;
  n?: number;
  aspect_ratio?: GrokAspectRatio;
  resolution?: "1k" | "2k";
  quality?: "low" | "medium";
  image_urls?: string[];
}

function buildBody(input: GrokImageRequest): GrokImageRequest {
  const prompt = input.prompt.trim();
  if (!prompt) throw new Error("prompt 不能为空");
  if (prompt.length > 8000) throw new Error("prompt 不能超过 8000 个字符");

  const n = input.n ?? 1;
  if (!Number.isInteger(n) || n < 1 || n > 10) {
    throw new Error("n 必须是 1–10 的整数");
  }

  if (input.image_urls && (input.image_urls.length < 1 || input.image_urls.length > 3)) {
    throw new Error("参考图片必须为 1–3 张");
  }

  const body: GrokImageRequest = {
    model: input.model,
    prompt,
    n,
    aspect_ratio: input.aspect_ratio ?? "auto",
    resolution: input.resolution ?? "1k",
  };

  if (!input.image_urls?.length) {
    body.quality = input.quality ?? "medium";
  }

  if (input.image_urls?.length) body.image_urls = input.image_urls;
  return body;
}

export async function submitGrokImageTask(params: {
  apiKey: string;
  request: GrokImageRequest;
  idempotencyKey: string;
  signal?: AbortSignal;
}) {
  const response = await fetch("https://api.apimart.ai/v1/images/generations", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${params.apiKey}`,
      "Content-Type": "application/json",
      Accept: "application/json",
      "Idempotency-Key": params.idempotencyKey,
      "X-APIMart-Response-Version": "2026-07-27",
    },
    body: JSON.stringify(buildBody(params.request)),
    signal: params.signal,
  });

  const body = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(body.error?.message ?? `图片请求失败（HTTP ${response.status}）`);
  }

  if (body.data?.object !== "generation.task" || !body.data?.id) {
    throw new Error("图片接口未返回有效任务 ID");
  }

  return {
    taskId: body.data.id as string,
    pollUrl: body.data.poll_url as string | undefined,
  };
}
```

提交成功后，使用返回的 `taskId` 调用[获取任务状态](/cn/api-reference/tasks/status)，直到任务状态变为 `completed` 或 `failed`。

## 前端联动规则

| 当前状态      | UI 与请求行为                  |
| --------- | ------------------------- |
| 无参考图      | 显示 Low / Medium，默认 Medium |
| 添加参考图     | 隐藏质量控件，提交时删除 `quality`    |
| 参考图达到 3 张 | 禁止继续添加                    |
| 任务提交成功    | 保存任务 ID 并开始轮询             |
| 任务完成      | 从任务结果中读取并显示图片 URL         |
| 任一计价参数变化  | 防抖刷新报价                    |

最小上线要求：

1. 固定调用 `POST /v1/images/generations`；
2. 固定发送 `X-APIMart-Response-Version: 2026-07-27`；
3. 每次逻辑生成创建一个幂等 Key，重试时复用；
4. 参考图统一通过 `image_urls` 传入，最多 3 张；
5. 尺寸统一使用 `aspect_ratio + resolution`；
6. 从提交响应中读取任务 ID；
7. 使用报价接口的 `final_usd` 展示预估价格；
8. 通过任务状态接口轮询至 `completed` 或 `failed`。
