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

# 使用 Comfy Router 调用 Image Edit Replace Background

> 通过 Comfy Router 调用 bria/image-edit-replace-background：端点、请求结构以及 Router 返回的响应。

`bria/image-edit-replace-background` 的 API 参考，由 Comfy Router 从 Bria 提供。

## 快速开始

在[你的 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 package）；cURL 代码片段则是通过原始 HTTP 发起的同一调用。

**模型 ID：** `bria/image-edit-replace-background`

**端点：** `POST https://api.comfy.org/v2/models/bria/image-edit-replace-background`

<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(
              "bria/image-edit-replace-background",
              {
                  "image": "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
                  "prompt": "A sunny beach with palm trees and a clear blue sky",
              },
          )

      print(result)
      ```

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

      // 从环境变量中读取 COMFY_API_KEY。
      // SDK 会自动创建幂等键，并在自动重试时复用它。
      const { data } = await comfy.models.run("bria/image-edit-replace-background", {
        image: "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
        prompt: "A sunny beach with palm trees and a clear blue sky",
      });

      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(
          "bria/image-edit-replace-background",
          input: [
              "image": "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
              "prompt": "A sunny beach with palm trees and a clear blue sky",
          ]
      )

      print(result.output)
      ```

      ```bash cURL theme={null}
      curl https://api.comfy.org/v2/models/bria/image-edit-replace-background \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $(uuidgen)" \
        -H "Content-Type: application/json" \
        -d "{\"image\": \"https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80\", \"prompt\": \"A sunny beach with palm trees and a clear blue sky\"}"
      ```
    </CodeGroup>
  </Tab>

  <Tab title="排队并稍后收集">
    同样的请求体，发送到 `POST https://api.comfy.org/v2/models/bria/image-edit-replace-background/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(
              "bria/image-edit-replace-background",
              {
                  "image": "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
                  "prompt": "A sunny beach with palm trees and a clear blue sky",
              },
          )
          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("bria/image-edit-replace-background", {
        image: "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
        prompt: "A sunny beach with palm trees and a clear blue sky",
      });
      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(
          "bria/image-edit-replace-background",
          input: [
              "image": "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
              "prompt": "A sunny beach with palm trees and a clear blue sky",
          ]
      )
      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/bria/image-edit-replace-background/requests \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $(uuidgen)" \
        -H "Content-Type: application/json" \
        -d "{\"image\": \"https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80\", \"prompt\": \"A sunny beach with palm trees and a clear blue sky\"}"

      # 2. 轮询直到状态为 COMPLETED，每次响应都会给出需要等待的 Retry-After 秒数。
      REQUEST_ID="<request_id from the 201 body>"
      curl -i https://api.comfy.org/v2/models/bria/image-edit-replace-background/requests/$REQUEST_ID/status \
        -H "X-API-Key: $COMFY_API_KEY"

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

## Schema

### 输入

<ParamField body="enhance_ref_images" type="boolean">
  当为 true（默认值）时，对参考图像进行额外处理可改善结果。
</ParamField>

<ParamField body="force_background_detection" type="boolean">
  当为 true 时，即使输入图像带有透明度通道，也会强制进行背景检测与移除。
</ParamField>

<ParamField body="image" type="string" required>
  要编辑的图像。支持的输入类型为 Base64 编码的字符串，或指向可公开访问的图像文件的 URL。可接受的格式为 JPEG、JPG、PNG、WEBP。
</ParamField>

<ParamField body="mode" type="string">
  背景生成模式，可为 "base"、"high\_control"（默认值）或 "fast"。仅在提供 prompt 时生效。
</ParamField>

<ParamField body="negative_prompt" type="string">
  一段文本提示词，用于指定要从生成的背景中排除的概念、风格或对象。
</ParamField>

<ParamField body="original_quality" type="boolean">
  当为 true 时，输出保持原始图像尺寸。当为 false（默认值）时，输出会被缩放至 1MP。
</ParamField>

<ParamField body="prompt" type="string">
  对新背景的文本描述。请提供 prompt 或 ref\_images，不要两者同时提供。提示词中的十六进制颜色代码（例如 "#FF5733"）会生成纯色背景。
</ParamField>

<ParamField body="prompt_content_moderation" type="boolean">
  启用后，会对提示词应用内容审核。如果提示词未通过审核，则返回 422。
</ParamField>

<ParamField body="ref_images" type="object">
  一张参考图像或一组参考图像列表，用于指导背景生成，每项均为 Base64 编码的字符串，或指向可公开访问的图像文件的 URL。请提供 prompt 或 ref\_images，不要两者同时提供。
</ParamField>

<ParamField body="refine_prompt" type="boolean">
  当为 true（默认值）时，提示词会被自动调整，以获得最佳的生成结果。
</ParamField>

<ParamField body="seed" type="integer">
  用于确定性生成的种子。如果省略，则使用随机种子。
</ParamField>

<ParamField body="sync" type="boolean">
  当为 false（默认值）时，请求以异步方式处理。当为
  true 时，API 会保持连接打开，直至完成。在 COMFY
  ROUTER 上，第二种模式会被拒绝而不是被转发：Router
  会在派发前固定返回模式，并在调用内部轮询结果，
  因此 `POST /v2/models/bria/{model}` 对于该路由携带的
  任何非 `false` 或 `null` 的 `sync` 都会返回 422
  invalid\_input（routerForbiddenBodyFields）。同步调用
  仍可通过此操作自身的 `/proxy/` 路由使用，本 schema
  所描述的也正是该接口。
</ParamField>

<ParamField body="visual_output_content_moderation" type="boolean">
  启用后，会对结果视觉内容应用内容审核。如果输出未通过审核，则返回 422。
</ParamField>

本页内容根据 Router 在 `GET /v2/models/bria/image-edit-replace-background/openapi.json` 提供的 schema 生成，该文档与请求到达提供商之前用于校验调用的文档是同一份。

### 输出

<ResponseField name="error" type="object">
  错误对象（仅当 status 为 ERROR 时存在）
</ResponseField>

<ResponseField name="error.code" type="integer">
  错误代码。
</ResponseField>

<ResponseField name="error.details" type="string">
  额外的错误详情。
</ResponseField>

<ResponseField name="error.message" type="string">
  报错信息。
</ResponseField>

<ResponseField name="request_id" type="string">
  请求的唯一标识符。
</ResponseField>

<ResponseField name="result" type="object">
  结果对象（仅当 status 为 COMPLETED 时存在）
</ResponseField>

<ResponseField name="result.image_url" type="string">
  已生成或已编辑图像的 URL。
</ResponseField>

<ResponseField name="result.prompt" type="string">
  原始提示词。
</ResponseField>

<ResponseField name="result.refined_prompt" type="string">
  提示词的优化版本；对于 Bria 未进行优化的 COMPLETED 生成，则为 null。之所以可为 null，是因为该键是存在的并携带 null，而不是被省略；在 bria/image-edit-gen-fill 上已实际观察到。
</ResponseField>

<ResponseField name="result.seed" type="integer">
  用于生成的种子。
</ResponseField>

<ResponseField name="result.structured_prompt" type="string">
  详细的 JSON 结构化提示词。
</ResponseField>

<ResponseField name="result.video_url" type="string">
  已生成视频的 URL。
</ResponseField>

<ResponseField name="status" type="string">
  请求的当前状态。

  可能的值：`IN_PROGRESS`、`COMPLETED`、`ERROR`、`UNKNOWN`
</ResponseField>

## 示例

### 输入

```json theme={null}
{
  "image": "https://img.freepik.com/free-photo/portrait-woman_395237-33.jpg?w=740&q=80",
  "prompt": "A sunny beach with palm trees and a clear blue sky"
}
```

### 输出

```json theme={null}
{
  "request_id": "0b3f9d7e-2c41-4a8b-9f10-6d5c8e2a4b71",
  "result": {
    "image_url": "https://example.invalid/bria/image-edit-replace-background/generated.png",
    "seed": 42
  },
  "status": "COMPLETED"
}
```

## 发布前须知

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>
