> ## 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 2.0 Ext 画像生成

>  - 非同期テキストから画像生成。task_id でポーリング
- 1 リクエストあたり 1–12 枚。正常に配信された画像ごとに課金（$0.08 / 枚）
- URL 出力のみ。画像から画像生成 / ストリーミング非対応
- 画像 URL の有効期限は 72 時間 

<Info>
  **テキストから画像 · 非同期ジョブ。** `POST /v1/images/generations` を送信し、[タスク状態の取得](/ja/api-reference/tasks/status) でポーリングしてください。\
  モデル名は固定で `grok-imagine-2.0-ext`。**非対応**: 参照画像、`stream`、および `url` 以外の `response_format`。
</Info>

<Warning>
  API キーをブラウザバンドル（`VITE_*` / `NEXT_PUBLIC_*`、LocalStorage など）に埋め込まないでください。ブラウザからは自前の BFF を呼び、APIMart キーはサーバー側で保持してください。
</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: 8eacb46d-ef4e-4f4e-82de-830bd8bc67e2' \
    --header 'X-APIMart-Response-Version: 2026-07-27' \
    --data '{
      "model": "grok-imagine-2.0-ext",
      "prompt": "A red apple on a white ceramic plate, clean studio product photo",
      "n": 1,
      "size": "1:1",
      "resolution": "quality",
      "response_format": "url"
    }'
  ```

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

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

  payload = {
      "model": "grok-imagine-2.0-ext",
      "prompt": "A red apple on a white ceramic plate, clean studio product photo",
      "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-APIMart-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://api.apimart.ai/v1/images/generations";

  const payload = {
    model: "grok-imagine-2.0-ext",
    prompt: "A red apple on a white ceramic plate, clean studio product photo",
    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-APIMart-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));
  ```
</RequestExample>

<ResponseExample>
  ```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"
    }
  }
  ```
</ResponseExample>

## 機能と制限

| 項目     | 契約内容                                                            |
| ------ | --------------------------------------------------------------- |
| モデル    | 固定 `grok-imagine-2.0-ext`                                       |
| 機能     | **テキストから画像のみ**                                                  |
| モード    | 非同期タスク                                                          |
| 枚数 `n` | `1`–`12`、デフォルト `1`                                              |
| `size` | 7 種のアスペクト比 + 5 種のピクセルエイリアス（下記）                                  |
| 出力     | `response_format=url` のみ（デフォルトも同じ）                              |
| 品質     | 公開フィールドは `resolution`；検証済みの値は `quality`                         |
| 非対応    | 画像から画像、`stream=true`、公開 `quality`、`style`、`b64_json` / `base64` |
| 課金     | 固定単価；**正常に配信された**画像分を課金                                         |

## 認証と推奨ヘッダー

<ParamField header="Authorization" type="string" required>
  Bearer トークン。[API Key ページ](https://apimart.ai/keys) からキーを取得してください。

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

| Header                       | 説明                                                                     |
| ---------------------------- | ---------------------------------------------------------------------- |
| `Content-Type`               | `application/json`（送信時）                                                |
| `Accept`                     | `application/json`                                                     |
| `Idempotency-Key`            | 強く推奨。ユーザーが確定した 1 回の生成ごとに新しい UUID。ネットワーク再試行時は**同じ key と body を再利用**すること |
| `X-APIMart-Response-Version` | 安定した送信レスポンス形状（`data.id`）のため `2026-07-27` を推奨                           |

## リクエストパラメータ

<ParamField body="model" type="string" required>
  固定値: `grok-imagine-2.0-ext`
</ParamField>

<ParamField body="prompt" type="string" required>
  プロンプト。trim 後に空であってはなりません。送信前に trim してください。
</ParamField>

<ParamField body="n" type="integer" default="1">
  画像枚数: `1`–`12`。明示的に `0` を渡すとエラー。省略時は `1`。
</ParamField>

<ParamField body="size" type="string">
  アスペクト比。**比率文字列を推奨**（UI では比率のみ表示すること）:

  | `size` | 向き  | 典型的な用途            |
  | ------ | --- | ----------------- |
  | `1:1`  | 正方形 | 商品、アバター           |
  | `2:3`  | 縦長  | ポスター、全身           |
  | `3:2`  | 横長  | 写真、広いシーン          |
  | `3:4`  | 縦長  | EC、人物             |
  | `4:3`  | 横長  | ディスプレイアート         |
  | `9:16` | 縦型  | Story / ショート動画カバー |
  | `16:9` | ワイド | バナー、動画カバー         |

  ピクセルエイリアス: `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` を書き換えないでください。
  </Note>
</ParamField>

<ParamField body="resolution" type="string">
  品質モード用フィールド。検証済みの値: `quality`。

  * 省略可（モデルはデフォルトで品質モード）、または
  * 明示的に `resolution: "quality"` を渡す

  **`1K` / `2K` / `4K` のピクセル段階ではありません**。構図は `size` で制御します。

  <Warning>
    公開フィールド `quality` を送らないでください — `400 invalid_quality` になります。`resolution` を使用してください。
  </Warning>
</ParamField>

<ParamField body="response_format" type="string" default="url">
  `url` のみ許可。省略可。`b64_json` / `base64` → `400 invalid_response_format`。
</ParamField>

<ParamField body="webhook" type="string">
  任意の公開 HTTPS **ベース URL**。終端ステータス時にプラットフォームが `{webhook}/callback` へ POST します。サーバー側のみ — [Webhook](#webhook任意) を参照。
</ParamField>

### 非対応パラメータ

| パラメータ                                      | 挙動                                       |
| ------------------------------------------ | ---------------------------------------- |
| `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": "A red apple on a white ceramic plate, clean studio product photo"
}
```

### 推奨

```json theme={null}
{
  "model": "grok-imagine-2.0-ext",
  "prompt": "A red apple on a white ceramic plate, clean studio product photo",
  "n": 1,
  "size": "1:1",
  "resolution": "quality",
  "response_format": "url"
}
```

## 送信レスポンス

`X-APIMart-Response-Version: 2026-07-27` を推奨。成功時は HTTP **`202`**。タスク ID は **`data.id`**（レガシーの `data[0].task_id` に依存しないこと）。

保存すべきもの:

* ポーリング用の `data.id`
* ゲートウェイ調査用の `request_id`
* 結果不明時の安全な再試行用 `Idempotency-Key`
* UI / サポート用の元リクエストパラメータ

## 冪等性と安全な再試行

画像生成は課金対象です — **強く推奨** `Idempotency-Key`（1–191 の印刷可能 ASCII 文字。UUID が最も簡単。約 24 時間保持）。

| シナリオ                   | 挙動                                            | 対応                         |
| ---------------------- | --------------------------------------------- | -------------------------- |
| 同じ key + 同じ body が完了済み | リプレイ。ヘッダー `Idempotency-Replayed: true`        | 同じタスク ID を使用               |
| 同じ key が処理中            | `409 idempotency_in_progress` + `Retry-After` | 待機し、**同じ key と body** で再試行 |
| 同じ key、異なる body        | `409 idempotency_key_reused`                  | 新しい論理ジョブには新しい key が必要      |
| 結果が不定                  | `409 idempotency_result_indeterminate`        | 新しい key を発行せず、旧 key で調査    |

POST のネットワークタイムアウトでサーバーが受け付けたか不明な場合、**すぐ新しい key を作らない** — 同じ key / body / レスポンスバージョンで再試行してください。

## タスクのポーリング

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

任意の `language`: `zh` / `en` / `ko` / `ja`（失敗メッセージのローカライズのみ）。[タスク状態の取得](/ja/api-reference/tasks/status) を参照。

### ステータス

| `status`                 |  終端 | 扱い                                        |
| ------------------------ | :-: | ----------------------------------------- |
| `pending` / `processing` | いいえ | ポーリング継続（`result` がなくても失敗ではない）             |
| `completed`              |  はい | `result.images` を解析                       |
| `failed`                 |  はい | `error.message` を表示。`cost` は `0`（事前課金は返金） |
| `unknown`                | いいえ | 短時間再試行。続く場合はタスク ID を添えてサポートへ              |

約 **2 秒**ごとにポーリング。上限は約 **10 分**または **120** 回。`429` では `Retry-After` に従う。タスクはデフォルトで約 3 日保持 — クライアントがタイムアウトしてもタスク 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 秒。JS Date では 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 |

* 送信前 UI は「見積もり」と表示。最終 USD は **`data.cost`**
* **`data.credits_cost`** はクレジット表示（現在は約 USD × 10）
* リクエスト枚数で事前課金。成功枚数で精算（部分失敗時は差額返金）
* 全失敗: `cost=0`、事前課金は返金
* `resolution` から価格キーを組み立てないこと。本モデルは枚数固定単価

## Webhook（任意）

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

* **ベース 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 を保持。安易にローテートしない |

UI では `error.message` を優先。生の認証内部情報をエンドユーザーに見せないでください。

## 1.5 との違い（要約）

| 項目       | Grok Imagine 1.5              | 2.0 Ext                                  |
| -------- | ----------------------------- | ---------------------------------------- |
| モデル      | `grok-imagine-1.5-apimart` など | `grok-imagine-2.0-ext`                   |
| 画像から画像   | 対応（1.5 ドキュメント参照）              | **非対応**                                  |
| 枚数       | 1.5 ドキュメント参照                  | **1–12**                                 |
| 品質フィールド  | 1.5 ドキュメント参照                  | `resolution`（`quality`）。公開 `quality` は不可 |
| 出力       | 1.5 ドキュメント参照                  | **URL のみ**                               |
| URL 有効期限 | 1.5 ドキュメント参照（多くは 24h）         | **72 時間**                                |
| 単価       | 1.5 ドキュメント参照                  | **\$0.08 / 枚**                           |
