> ## 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 Pro

> 通过 Comfy Router 调用 xai/grok-imagine-image-pro:端点、请求形状以及 Router 返回的响应。

由 Comfy Router 从 xAI 提供的 `xai/grok-imagine-image-pro` API 参考。

## 快速开始

在[你的 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-pro`

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

<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-pro",
              {
                  "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-pro", {
        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-pro",
          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-pro \
        -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-pro/requests`。Router 在运行被接受后立即返回 `201` 和 `request_id`，结果就绪后即可收集，无论来自当前进程还是其他进程。[队列投递](/zh/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-pro",
              {
                  "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-pro", {
        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() 返回的结果相同。失败或已取消的请求会在此处被拒绝。
      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-pro",
          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 返回 201，以及 request_id、status_url、response_url 和 cancel_url。
      curl https://api.comfy.org/v2/models/xai/grok-imagine-image-pro/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-pro/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-pro/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-pro/openapi.json` 提供的 schema 生成，这也是请求到达提供商之前 Router 用于校验调用的同一份文档。

### 输出

<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>
