> ## Documentation Index
> Fetch the complete documentation index at: https://comfyuiwiki.com/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?onboarding=router)中创建一个密钥，并将其导出为 `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 defaultTabIndex={1}>
  <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-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";

      // 从环境变量中读取 COMFY_API_KEY。
      // SDK 会自动创建幂等键，并在自动重试时复用它。
      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="加入队列并稍后收集">
    同一个请求体，发送到 `POST https://api.comfy.org/v2/models/xai/grok-imagine-image-quality/requests`。只要运行被接纳，Router 就会返回 `201` 以及一个 `request_id`，结果准备就绪后再进行收集，可由当前进程或另一个进程完成。[队列化交付](/zh/development/comfy-router/queue) 详解了状态、取消和收集的流程。

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

      # 从环境变量中读取 COMFY_API_KEY。
      # 每次 submit() 调用都会生成自己的 Idempotency-Key，并在自动重试时复用它。
      async def main():
          async with AsyncComfy() as client:
              handle = await 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)  # 再加上模型 ID，就是另一个进程所需的全部信息

              # 轮询直到请求完成，按服务器指定的 Retry-After 等待。
              async for update in handle.iter_events():
                  print(update.status, update.queue_position)

              # 提供商自身的载荷，与 models.run() 返回的值相同。
              # 失败或已取消的请求会在此处抛出带类型的 Router 错误。
              result = await handle.get()

          print(result)

      asyncio.run(main())
      ```

      ```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-quality", {
        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);
      ```

      ```bash cURL theme={null}
      # 1. 提交。Router 返回 201 以及 request_id、status_url、response_url 和 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. 轮询直到状态为 COMPLETED，按每次响应指定的 Retry-After 秒数等待。
      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. 收集。返回 200 及模型的原始输出，仍在运行时返回 202 及状态响应体。
      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>

## Schema

### 输入

<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 在向外发出的请求中会将其强制转换为 `url`：无论是 Comfy Router 的调度（`POST /v2/models/xai/{model}`），还是此 `/proxy/` 路由，都是如此，因为图像结果无论如何都以重新托管的 URL 形式提供。该字段会被接受并忽略，而不会被拒绝；发送它或省略它，得到的答复都一样。

  可选值：`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 在调用提供商之前就拒绝了输入，`413` 表示请求体超出了 Router 可接受的大小。已生成的资源请及时下载，因为[结果 URL 会过期](/zh/development/comfy-router/reference#结果资产)。

上文任何字段描述中提到的尺寸限制，都是提供商对该字段自身的限定，引自提供商的规范。Router 会对整个请求体另行设置上限，base64 编码的媒体内容也计入其中：参见[请求体大小](/zh/development/comfy-router/limitations)。

本页记录的是通过 Comfy Router 调用的某一个合作伙伴模型。同一个 `comfy-sdk` / `@comfyorg/sdk` 包还提供第二个客户端，用于在 Comfy Cloud 上运行完整的 ComfyUI 工作流图：`Comfy(api_key=...)` / `new Comfy({ apiKey })`，并带有 `client.workflows`、`client.assets` 和 `client.jobs`。请参阅 [Comfy SDKs](/zh/development/api-development/sdks)。

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

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

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