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

# 配合 Comfy Router 使用 Grok Imagine Image Quality

> 通过 Comfy Router 调用 xai/grok-imagine-image-quality：端点、请求结构与 Router 返回的响应。

`xai/grok-imagine-image-quality` 的 API 参考，由 Comfy Router 提供，来自 xAI。

## 快速开始

在[你的 Comfy 工作区](https://platform.comfy.org/profile/api-keys)中创建一个密钥，并将其导出为 `COMFY_API_KEY`。Python 和 TypeScript 代码片段使用 Comfy SDK（`pip install comfy-sdk`、`npm install @comfyorg/sdk`）；cURL 代码片段则是通过原始 HTTP 发起的同一调用。

**模型 ID：** `xai/grok-imagine-image-quality`

**端点：** `POST https://api.comfy.org/v2/models/xai/grok-imagine-image-quality`

<Tabs>
  <Tab title="Wait for the result">
    <CodeGroup>
      ```python Python theme={null}
      from comfy_sdk import Comfy

      # Reads COMFY_API_KEY from the environment.
      # The SDK automatically creates an idempotency key and reuses it for automatic retries.
      with Comfy() as client:
          result = client.models.run(
              "xai/grok-imagine-image-quality",
              {
                  "n": 1,
                  "prompt": "A single red maple leaf on a plain white background.",
              },
          )

      print(result)
      ```

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

      // Reads COMFY_API_KEY from the environment.
      // The SDK automatically creates an idempotency key and reuses it for automatic retries.
      const { data } = await comfy.models.run("xai/grok-imagine-image-quality", {
        n: 1,
        prompt: "A single red maple leaf on a plain white background.",
      });

      console.log(data);
      ```

      ```bash cURL theme={null}
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-quality \
        -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="Queue and collect later">
    <CodeGroup>
      ```python Python theme={null}
      from comfy_sdk import Comfy

      # Reads COMFY_API_KEY from the environment.
      # Each submit() call mints its own Idempotency-Key and reuses it for automatic retries.
      with Comfy() as client:
          handle = client.models.submit(
              "xai/grok-imagine-image-quality",
              {
                  "n": 1,
                  "prompt": "A single red maple leaf on a plain white background.",
              },
          )
          print("request_id:", handle.request_id)  # with the model ID, all another process needs

          # Poll until the request completes, waiting the Retry-After the server names.
          for update in handle.iter_events():
              print(update.status, update.queue_position)

          # The provider's own payload, the same value models.run() returns.
          # A request that failed or was cancelled raises the typed Router error here.
          result = handle.get()

      print(result)
      ```

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

      // Reads COMFY_API_KEY from the environment.
      // Each submit() call mints its own Idempotency-Key and reuses it for automatic retries.
      const handle = await comfy.models.submit("xai/grok-imagine-image-quality", {
        n: 1,
        prompt: "A single red maple leaf on a plain white background.",
      });
      console.log("requestId:", handle.requestId); // with the model ID, all another process needs

      // Poll until the request completes, waiting the Retry-After the server names.
      for await (const update of handle.events()) {
        console.log(update.status, update.queuePosition);
      }

      // The same result models.run() returns. A request that failed or was cancelled rejects here.
      const result = await handle.get();

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

      ```bash cURL theme={null}
      # 1. Submit. Router answers 201 with request_id, status_url, response_url and cancel_url.
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-quality/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. Poll until status is COMPLETED, waiting the Retry-After seconds each response names.
      REQUEST_ID="<request_id from the 201 body>"
      curl -i https://api.comfy.org/v2/models/xai/grok-imagine-image-quality/requests/$REQUEST_ID/status \
        -H "X-API-Key: $COMFY_API_KEY"

      # 3. Collect. 200 with the model's native output, 202 with the status body while it is still running.
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-quality/requests/$REQUEST_ID \
        -H "X-API-Key: $COMFY_API_KEY"
      ```
    </CodeGroup>
  </Tab>
</Tabs>

<h2 id="schema">
  Schema
</h2>

### 输入

<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。Comfy Router（`POST /v2/models/xai/{model}`）在向外发出的请求中会将其强制转换为 `url`，因为它无论哪种方式都以重新托管的 URL 返回图像结果；此 `/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-quality/openapi.json` 提供的 schema 生成，这是它在请求到达提供商之前用于校验调用的同一份文档。

### 输出

<ResponseField name="block_reason" type="string">
  如果请求被输入审核拦截，则包含拦截原因
</ResponseField>

<ResponseField name="data" type="object[]">
  已生成图像对象的列表
</ResponseField>

<ResponseField name="data[].b64_json" type="string">
  已生成图像的 base64 编码字符串表示，采用 jpeg 编码（如果 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 ticks 为单位（10,000,000,000 ticks = 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` 并在自动重试中复用它。手动重试时，请复用原始 key。Router 最长可保持连接 10 分钟。

请求失败时，Router 会发送 `X-Comfy-Error-Type` 响应头说明原因。`422` 表示 Router 在调用提供商之前就拒绝了输入。生成的资源请及时下载，因为[结果链接会过期](/zh/development/comfy-router/reference#结果资产)。

<CardGroup cols={3}>
  <Card title="请求头" icon="list" href="/zh/development/comfy-router/quickstart">
    身份验证、幂等性、请求 ID、错误分类、重试节奏、消费限额。
  </Card>

  <Card title="使用 Router API" icon="code" href="/zh/development/comfy-router/quickstart">
    模型发现、校验错误、重试与计费。
  </Card>

  <Card title="限制" icon="triangle-exclamation" href="/zh/development/comfy-router/limitations">
    Router 目前不支持的功能，以及替代方案。
  </Card>
</CardGroup>
