> ## 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 使用 Recraft V2

> 通过 Comfy Router 调用 recraft/recraftv2：端点、请求结构以及 Router 返回的响应。

`recraft/recraftv2` 的 API 参考，由 Comfy Router 提供，来源于 Recraft。

## 快速开始

在[你的 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：** `recraft/recraftv2`

**端点：** `POST https://api.comfy.org/v2/models/recraft/recraftv2`

<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(
              "recraft/recraftv2",
              {
                  "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("recraft/recraftv2", {
        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(
          "recraft/recraftv2",
          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/recraft/recraftv2 \
        -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/recraft/recraftv2/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(
              "recraft/recraftv2",
              {
                  "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("recraft/recraftv2", {
        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(
          "recraft/recraftv2",
          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/recraft/recraftv2/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/recraft/recraftv2/requests/$REQUEST_ID/status \
        -H "X-API-Key: $COMFY_API_KEY"

      # 3. 收集。仍在运行时返回 202 和状态响应体，完成后返回 200 和模型的原始输出。
      curl https://api.comfy.org/v2/models/recraft/recraftv2/requests/$REQUEST_ID \
        -H "X-API-Key: $COMFY_API_KEY"
      ```
    </CodeGroup>
  </Tab>
</Tabs>

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

### 输入

<ParamField body="controls" type="object">
  已生成图像的控制参数
</ParamField>

<ParamField body="controls.artistic_level" type="integer">
  定义图像的艺术基调。在 simple 级别，人物以静态、干净的风格直视相机。dynamic 和 eccentric 级别则引入动感与创意。

  范围：`0` 到 `5`
</ParamField>

<ParamField body="controls.background_color" type="object">
  RGB 颜色值
</ParamField>

<ParamField body="controls.background_color.rgb" type="integer[]" required />

<ParamField body="controls.colors" type="object[]">
  偏好颜色的数组
</ParamField>

<ParamField body="controls.colors[].rgb" type="integer[]" required />

<ParamField body="controls.no_text" type="boolean">
  不嵌入文字版式
</ParamField>

<ParamField body="model" type="string">
  用于生成的模型（例如 "recraftv3"）。该字段不受 enum 约束：代理会原样转发调用方发送的内容。Comfy 提供的拼写，也就是 Comfy Router 以 `recraft/<model>` 形式寻址的那一组，包括 recraftv2、recraftv3、recraftv4、recraftv4\_pro、recraftv4\_1、recraftv4\_1\_utility、recraftv4\_1\_pro、recraftv4\_1\_utility\_pro、recraftv4\_styles、recraftv4\_styles\_pro、recraftv4\_1\_vector、recraftv4\_1\_utility\_vector、recraftv4\_1\_pro\_vector、recraftv4\_1\_utility\_pro\_vector、recraftv4\_styles\_vector 和 recraftv4\_styles\_pro\_vector。这里将它们逐一写出，而不是通过引用点名，是因为声明它们的 RecraftGenerationModel 组件没有被任何地方 `$ref` 引用，因此会从 GET /openapi 所提供的规范中剪除，若指向它就会在所提供的文档中形成悬空指针。四种 `recraftv4_styles*` 拼写还额外要求 `style_id`，参见该字段。
</ParamField>

<ParamField body="n" type="integer">
  要生成的图像数量。Recraft 接受 1-6。

  范围：`1` 到 `6`
</ParamField>

<ParamField body="prompt" type="string" required>
  描述要生成图像的文本提示词
</ParamField>

<ParamField body="response_format" type="string">
  可能的值：`url`、`b64_json`
</ParamField>

<ParamField body="size" type="string">
  已生成图像的尺寸（例如 "1024x1024"）
</ParamField>

<ParamField body="style" type="string">
  应用于已生成图像的风格（例如 "digital\_illustration"）
</ParamField>

<ParamField body="style_id" type="string">
  应用于已生成图像的风格 ID（例如 "123e4567-e89b-12d3-a456-426614174000"）。如果提供了 style\_id，则不应提供 style。四种 `recraftv4_styles*` 模型要求此字段必填：Recraft 会拒绝没有 style\_id 或风格引用的请求。可通过 `POST /proxy/recraft/styles` 生成一个，该端点由同一代理在相同凭据下提供。此路由上没有任何机制强制这一配对关系：请求体会原样转发给 Recraft，因此不带 style\_id 的 `recraftv4_styles*` 调用会到达合作伙伴并返回 4xx。
</ParamField>

本文档依据 Router 在 `GET /v2/models/recraft/recraftv2/openapi.json` 提供的 schema 生成，Router 在请求到达提供商之前也会用同一份文档校验调用。

### 输出

<ResponseField name="created" type="integer" required>
  生成创建时的 Unix 时间戳
</ResponseField>

<ResponseField name="credits" type="integer" required>
  本次生成所使用的积分数量
</ResponseField>

<ResponseField name="data" type="object[]" required>
  已生成图像信息的数组
</ResponseField>

<ResponseField name="data[].b64_json" type="string">
  Base64 编码的图像数据（当请求设置 `response_format: b64_json` 时出现，用于替代 `url`）
</ResponseField>

<ResponseField name="data[].image_id" type="string">
  已生成图像的唯一标识符
</ResponseField>

<ResponseField name="data[].url" type="string">
  访问已生成图像的 URL（当 `response_format` 为 `url`（默认值）时出现）
</ResponseField>

<ResponseField name="style_id" type="string">
  解析后的风格 ID，由 Recraft 在使用风格引用时返回（尤其是必填输入模型 recraftv4\_styles\*）；可在后续请求中作为 `style_id` 重复使用。
</ResponseField>

## 示例

### 输入

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

### 输出

```json theme={null}
{
  "created": 1767225600,
  "credits": 1,
  "data": [
    {
      "image_id": "3f7a1b28-5c0d-4e91-8a6f-1b2c3d4e5f60",
      "url": "https://example.invalid/recraft/recraftv3/generated.png"
    }
  ]
}
```

## 发布前须知

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>
