> ## Documentation Index
> Fetch the complete documentation index at: https://dripart-chore-mintlify-theme-mint.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Comfy Router で Grok Imagine Image 2.0 を使用する

> Comfy Router 経由で xai/grok-imagine-image-2.0 を呼び出します: endpoint、リクエスト形状、Router が返すレスポンスについて説明します。

`xai/grok-imagine-image-2.0` の API リファレンスです。このモデルは xAI から Comfy Router を通じて提供されます。

## クイックスタート

[Comfy ワークスペース](https://platform.comfy.org/profile/api-keys?onboarding=router)でキーを作成し、`COMFY_API_KEY` としてエクスポートします。Python、TypeScript、Swift のスニペットは Comfy SDK（`pip install comfy-sdk`、`npm install @comfyorg/sdk`、および [`ComfySwiftSDK`](https://github.com/Comfy-Org/comfy-swift-sdk) Swift パッケージ）を使用します。cURL スニペットは、同じ呼び出しを生の HTTP で実行するものです。

**モデル ID:** `xai/grok-imagine-image-2.0`

**エンドポイント:** `POST https://api.comfy.org/v2/models/xai/grok-imagine-image-2.0`

<Tabs>
  <Tab title="結果を待つ">
    <CodeGroup>
      ```python Python theme={null}
      from comfy_sdk import Comfy

      # 環境変数から COMFY_API_KEY を読み取ります。
      # SDK は自動的に冪等性キーを作成し、自動リトライのために再利用します。
      with Comfy() as client:
          result = client.models.run(
              "xai/grok-imagine-image-2.0",
              {
                  "n": 1,
                  "prompt": "A single red maple leaf on a plain white background.",
              },
          )

      print(result)
      ```

      ```typescript TypeScript theme={null}
      import { comfy } from "@comfyorg/sdk";

      // 環境変数から COMFY_API_KEY を読み取ります。
      // SDK は自動的に冪等性キーを作成し、自動リトライのために再利用します。
      const { data } = await comfy.models.run("xai/grok-imagine-image-2.0", {
        n: 1,
        prompt: "A single red maple leaf on a plain white background.",
      });

      console.log(data);
      ```

      ```swift Swift theme={null}
      import Foundation
      import ComfySwiftSDK

      // 環境変数から COMFY_API_KEY を読み取ります。
      // SDK は呼び出しごとに冪等性キーを発行し、自動リトライのために再利用します。
      let client = ComfyCloudClient(apiKey: ProcessInfo.processInfo.environment["COMFY_API_KEY"]!)
      let result = try await client.models.run(
          "xai/grok-imagine-image-2.0",
          input: [
              "n": 1,
              "prompt": "A single red maple leaf on a plain white background.",
          ]
      )

      print(result.output)
      ```

      ```bash cURL theme={null}
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-2.0 \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $(uuidgen)" \
        -H "Content-Type: application/json" \
        -d "{\"n\": 1, \"prompt\": \"A single red maple leaf on a plain white background.\"}"
      ```
    </CodeGroup>
  </Tab>

  <Tab title="キューに送信して後で収集">
    同じボディを `POST https://api.comfy.org/v2/models/xai/grok-imagine-image-2.0/requests` に送信します。Router は実行が受け付けられ次第、`request_id` とともに `201` を返し、結果は準備ができたら、このプロセスからでも別のプロセスからでも収集できます。[キューによる配信](/ja/development/comfy-router/queue)では、ステータス、キャンセル、収集について説明します。

    <CodeGroup>
      ```python Python theme={null}
      from comfy_sdk import Comfy

      # 環境変数から COMFY_API_KEY を読み取ります。
      # 各 submit() 呼び出しは独自の Idempotency-Key を発行し、自動リトライのために再利用します。
      with Comfy() as client:
          handle = client.models.submit(
              "xai/grok-imagine-image-2.0",
              {
                  "n": 1,
                  "prompt": "A single red maple leaf on a plain white background.",
              },
          )
          print("request_id:", handle.request_id)  # モデル ID と合わせれば、別のプロセスに必要なものはこれだけです

          # リクエストが完了するまでポーリングし、サーバーが指定する Retry-After の時間だけ待機します。
          for update in handle.iter_events():
              print(update.status, update.queue_position)

          # プロバイダー自身のペイロードで、models.run() が返す値と同じです。
          # 失敗またはキャンセルされたリクエストは、ここで型付きの Router エラーを発生させます。
          result = handle.get()

      print(result)
      ```

      ```typescript TypeScript theme={null}
      import { comfy } from "@comfyorg/sdk";

      // 環境変数から COMFY_API_KEY を読み取ります。
      // 各 submit() 呼び出しは独自の Idempotency-Key を発行し、自動リトライのために再利用します。
      const handle = await comfy.models.submit("xai/grok-imagine-image-2.0", {
        n: 1,
        prompt: "A single red maple leaf on a plain white background.",
      });
      console.log("requestId:", handle.requestId); // モデル ID と合わせれば、別のプロセスに必要なものはこれだけです

      // リクエストが完了するまでポーリングし、サーバーが指定する Retry-After の時間だけ待機します。
      for await (const update of handle.events()) {
        console.log(update.status, update.queuePosition);
      }

      // models.run() が返すのと同じ結果です。失敗またはキャンセルされたリクエストはここで reject されます。
      const result = await handle.get();

      console.log(result.data);
      ```

      ```swift Swift theme={null}
      import Foundation
      import ComfySwiftSDK

      // 環境変数から COMFY_API_KEY を読み取ります。
      // 各 submit() 呼び出しは独自の Idempotency-Key を発行し、自動リトライのために再利用します。
      let client = ComfyCloudClient(apiKey: ProcessInfo.processInfo.environment["COMFY_API_KEY"]!)
      let handle = try await client.models.submit(
          "xai/grok-imagine-image-2.0",
          input: [
              "n": 1,
              "prompt": "A single red maple leaf on a plain white background.",
          ]
      )
      print("requestId:", handle.requestId)  // モデル ID と合わせれば、別のプロセスに必要なものはこれだけです

      // リクエストが完了するまでポーリングし、サーバーが指定する Retry-After の時間だけ待機します。
      for try await update in handle.events() {
          print(update.state.rawValue, update.queuePosition.map(String.init) ?? "unknown")
      }

      // プロバイダー自身のペイロードで、models.run() が返す値と同じです。
      // 失敗またはキャンセルされたリクエストは、ここで型付きの Router エラーをスローします。
      let result = try await handle.result()

      print(result.output)
      ```

      ```bash cURL theme={null}
      # 1. 送信。Router は request_id、status_url、response_url、cancel_url とともに 201 を返します。
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-2.0/requests \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $(uuidgen)" \
        -H "Content-Type: application/json" \
        -d "{\"n\": 1, \"prompt\": \"A single red maple leaf on a plain white background.\"}"

      # 2. ステータスが COMPLETED になるまでポーリングし、各レスポンスが指定する Retry-After の秒数だけ待機します。
      REQUEST_ID="<request_id from the 201 body>"
      curl -i https://api.comfy.org/v2/models/xai/grok-imagine-image-2.0/requests/$REQUEST_ID/status \
        -H "X-API-Key: $COMFY_API_KEY"

      # 3. 収集。モデルのネイティブ出力とともに 200、まだ実行中であればステータスボディとともに 202 を返します。
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-2.0/requests/$REQUEST_ID \
        -H "X-API-Key: $COMFY_API_KEY"
      ```
    </CodeGroup>
  </Tab>
</Tabs>

## スキーマ

### 入力

<ParamField body="aspect_ratio" type="string" default="&#x22;auto&#x22;">
  生成される画像のアスペクト比。デフォルトは auto で、プロンプトに最適な比率が自動的に選択されます。

  指定可能な値: `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`
</ParamField>

<ParamField body="model" type="string" default="&#x22;grok-imagine-image&#x22;">
  使用するモデル。対応: grok-imagine-image（デフォルト）、grok-imagine-image-pro、grok-imagine-image-quality、grok-imagine-image-2.0。非推奨の -beta ID は GA モデルへのエイリアスです。
</ParamField>

<ParamField body="n" type="integer" default="1">
  生成する画像の数

  範囲: `1` から `10`
</ParamField>

<ParamField body="prompt" type="string" required>
  画像生成のためのプロンプト
</ParamField>

<ParamField body="quality" type="string">
  出力画像の品質。grok-imagine-image-2.0 では価格ティアを選択します（low/medium。デフォルトは medium）。その他のモデルは現在これを無視します。

  指定可能な値: `low`, `medium`, `high`
</ParamField>

<ParamField body="resolution" type="string" default="&#x22;1k&#x22;">
  生成される画像の解像度。デフォルトは 1k。

  指定可能な値: `1k`, `2k`
</ParamField>

<ParamField body="response_format" type="string" default="&#x22;url&#x22;">
  画像を返す際のレスポンス形式。url または b64\_json を指定できます。いずれの場合も画像結果は再ホストされた URL として提供されるため、Comfy は送信リクエストでこれを `url` に強制変換します。Comfy Router のディスパッチ（`POST /v2/models/xai/{model}`）でも、この `/proxy/` ルートでも同様です。このフィールドは拒否されるのではなく、受け入れられたうえで無視されます。送信しても省略しても、結果は同じです。

  指定可能な値: `url`, `b64_json`
</ParamField>

<ParamField body="size" type="string">
  画像のサイズ（未対応）
</ParamField>

<ParamField body="style" type="string">
  画像のスタイル（未対応）
</ParamField>

<ParamField body="user" type="string">
  エンドユーザーを表す一意の識別子。xAI が不正利用の監視と検出に役立てることができます
</ParamField>

Router が `GET /v2/models/xai/grok-imagine-image-2.0/openapi.json` で提供するスキーマから生成されています。これは、リクエストがプロバイダーに到達する前に Router が呼び出しの検証に使用するのと同じドキュメントです。

### 出力

<ResponseField name="block_reason" type="string">
  リクエストが入力モデレーションによってブロックされた場合、ブロック理由が含まれます
</ResponseField>

<ResponseField name="data" type="object[]">
  生成された画像オブジェクトのリスト
</ResponseField>

<ResponseField name="data[].b64_json" type="string">
  生成された画像を jpeg エンコーディングで表した base64 エンコード文字列（response\_format が b64\_json の場合）
</ResponseField>

<ResponseField name="data[].mime_type" type="string">
  生成された画像の MIME タイプ（例: image/png、image/jpeg、image/webp）。
</ResponseField>

<ResponseField name="data[].url" type="string">
  生成された画像への URL（response\_format が url の場合）
</ResponseField>

<ResponseField name="usage" type="object">
  画像生成リクエストの使用状況情報
</ResponseField>

<ResponseField name="usage.cost_in_usd_ticks" type="integer">
  このリクエストの正確なコスト（USD ティック単位。10,000,000,000 ティック = 1 USD）
</ResponseField>

## 例

### 入力

```json theme={null}
{
  "n": 1,
  "prompt": "A single red maple leaf on a plain white background."
}
```

### 出力

```json theme={null}
{
  "data": [
    {
      "mime_type": "image/jpeg",
      "url": "https://example.invalid/xai/grok-imagine-image/generated.jpg"
    },
    {
      "mime_type": "image/jpeg",
      "url": "https://example.invalid/xai/grok-imagine-image/generated-2.jpg"
    }
  ],
  "usage": {
    "cost_in_usd_ticks": 200000000
  }
}
```

## 出荷前の確認

SDK は `Idempotency-Key` を生成し、自動リトライで再利用します。手動リトライでは元のキーを再利用してください。Router は最大 10 分間接続を保持できます。

リクエストが失敗すると、Router は理由を説明する `X-Comfy-Error-Type` レスポンスヘッダーを送信します。`422` は、プロバイダーを呼び出す前に Router が入力を拒否したことを意味し、`413` はリクエスト本文が Router の受け入れ可能なサイズを超えていたことを意味します。生成されたアセットは [結果 URL の有効期限](/ja/development/comfy-router/reference#結果アセット) があるため、早めにダウンロードしてください。

上記のフィールド説明に記載されているサイズ制限は、プロバイダーの仕様から引用した、そのフィールドに対するプロバイダー自身の上限です。Router はリクエスト本文全体に対して別の上限を適用し、base64 エンコードされたメディアもこれにカウントされます。[リクエスト本文のサイズ](/ja/development/comfy-router/limitations) を参照してください。

このページは、Comfy Router 経由で呼び出す 1 つのパートナーモデルについて説明しています。同じ `comfy-sdk` / `@comfyorg/sdk` パッケージには、Comfy Cloud 上で ComfyUI のワークフローグラフ全体を実行するための 2 つ目のクライアントも含まれています: `Comfy(api_key=...)` / `new Comfy({ apiKey })`、および `client.workflows`、`client.assets`、`client.jobs`。[Comfy SDKs](/ja/development/api-development/sdks) を参照してください。

<CardGroup cols={3}>
  <Card title="ヘッダー" icon="list" href="/ja/development/comfy-router/headers">
    認証、冪等性、リクエスト ID、エラー分類、リトライ間隔、支出上限。
  </Card>

  <Card title="Router API の利用" icon="code" href="/ja/development/comfy-router/api">
    モデルの検出、バリデーションエラー、リトライ、課金。
  </Card>

  <Card title="制限事項" icon="triangle-exclamation" href="/ja/development/comfy-router/limitations">
    Router が現在対応していないことと、代替手段。
  </Card>
</CardGroup>
