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

# 将 Nano Banana 2 与 Comfy Router 配合使用

> 通过 Comfy Router 以 HTTP 方式调用 Nano Banana 2（Gemini 3.1 Flash Image）生成图像的 Python、TypeScript 和 cURL 代码片段，以及请求字段和返回结果结构

Nano Banana 2 的 API 参考。Nano Banana 2（Gemini 3.1 Flash Image）可根据文本生成图像，并在提供输入图像时对其进行编辑。

## 快速开始

在[你的 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：** `vertexai/gemini-3.1-flash-image`

**端点：** `POST https://api.comfy.org/v2/models/vertexai/gemini-3.1-flash-image`

<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(
              "vertexai/gemini-3.1-flash-image",
              {
                  "contents": [
                      {
                          "role": "user",
                          "parts": [
                              {
                                  "text": "a single red maple leaf on a plain white background, studio lighting",
                              },
                          ],
                      },
                  ],
                  "generationConfig": {
                      "responseModalities": ["IMAGE"],
                      "imageConfig": {
                          "aspectRatio": "1:1",
                      },
                  },
              },
          )

      print("image (base64):", result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"])
      ```

      ```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.
      type Result = { candidates: { content: { parts: { inlineData: { data: string } }[] } }[] };
      const { data } = await comfy.models.run<Result>("vertexai/gemini-3.1-flash-image", {
        contents: [
          {
            role: "user",
            parts: [
              {
                text: "a single red maple leaf on a plain white background, studio lighting",
              },
            ],
          },
        ],
        generationConfig: {
          responseModalities: ["IMAGE"],
          imageConfig: {
            aspectRatio: "1:1",
          },
        },
      });

      console.log("image (base64):", data.candidates[0].content.parts[0].inlineData.data);
      ```

      ```bash cURL theme={null}
      curl https://api.comfy.org/v2/models/vertexai/gemini-3.1-flash-image \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $(uuidgen)" \
        -H "Content-Type: application/json" \
        -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"a single red maple leaf on a plain white background, studio lighting\"}]}], \"generationConfig\": {\"responseModalities\":[\"IMAGE\"],\"imageConfig\":{\"aspectRatio\":\"1:1\"}}}"
      ```
    </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(
              "vertexai/gemini-3.1-flash-image",
              {
                  "contents": [
                      {
                          "role": "user",
                          "parts": [
                              {
                                  "text": "a single red maple leaf on a plain white background, studio lighting",
                              },
                          ],
                      },
                  ],
                  "generationConfig": {
                      "responseModalities": ["IMAGE"],
                      "imageConfig": {
                          "aspectRatio": "1:1",
                      },
                  },
              },
          )
          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("image (base64):", result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"])
      ```

      ```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.
      type Result = { candidates: { content: { parts: { inlineData: { data: string } }[] } }[] };
      const handle = await comfy.models.submit<Result>("vertexai/gemini-3.1-flash-image", {
        contents: [
          {
            role: "user",
            parts: [
              {
                text: "a single red maple leaf on a plain white background, studio lighting",
              },
            ],
          },
        ],
        generationConfig: {
          responseModalities: ["IMAGE"],
          imageConfig: {
            aspectRatio: "1:1",
          },
        },
      });
      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();
      if (result.kind !== "json") throw new Error("expected a JSON result");

      console.log("image (base64):", result.data.candidates[0].content.parts[0].inlineData.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/vertexai/gemini-3.1-flash-image/requests \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $(uuidgen)" \
        -H "Content-Type: application/json" \
        -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"a single red maple leaf on a plain white background, studio lighting\"}]}], \"generationConfig\": {\"responseModalities\":[\"IMAGE\"],\"imageConfig\":{\"aspectRatio\":\"1:1\"}}}"

      # 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/vertexai/gemini-3.1-flash-image/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/vertexai/gemini-3.1-flash-image/requests/$REQUEST_ID \
        -H "X-API-Key: $COMFY_API_KEY"
      ```
    </CodeGroup>
  </Tab>
</Tabs>

## Schema

### 输入

<ParamField body="contents" type="object[]" required>
  与模型进行当前对话的内容。对于单轮查询，这是单个实例。对于多轮查询，这是一个重复字段，包含对话历史和最新请求。
</ParamField>

<ParamField body="contents[].parts" type="object[]" required />

<ParamField body="contents[].parts[].fileData" type="object">
  基于 URI 的数据。
</ParamField>

<ParamField body="contents[].parts[].fileData.fileUri" type="string">
  URI
</ParamField>

<ParamField body="contents[].parts[].fileData.mimeType" type="string">
  data 或 fileUri 字段中指定的文件媒体类型。可接受的值包括以下内容。对于 gemini-2.0-flash-lite 和 gemini-2.0-flash，音频文件的最大长度为 8.4 小时，视频文件（无音频）的最大长度为一小时。有关更多信息，请参阅 Gemini 音频和视频要求。文本文件必须为 UTF-8 编码。文本文件的内容计入 token 限制。图像分辨率无限制。

  可能的值：`application/pdf`, `audio/mpeg`, `audio/mp3`, `audio/wav`, `image/png`, `image/jpeg`, `image/webp`, `text/plain`, `video/mov`, `video/mpeg`, `video/mp4`, `video/mpg`, `video/avi`, `video/wmv`, `video/mpegps`, `video/flv`, `image/heic`, `image/heif`, `audio/flac`, `video/webm`
</ParamField>

<ParamField body="contents[].parts[].inlineData" type="object">
  以原始字节表示的内联数据。对于 gemini-2.0-flash-lite 和 gemini-2.0-flash，通过 inlineData 最多可以指定 3000 张图像。
</ParamField>

<ParamField body="contents[].parts[].inlineData.data" type="string (byte)">
  要在提示词中内联包含的图像、PDF 或视频的 base64 编码。内联包含媒体时，还必须指定数据的媒体类型（mimeType）。大小限制：20MB

  格式：`byte`
</ParamField>

<ParamField body="contents[].parts[].inlineData.mimeType" type="string">
  data 或 fileUri 字段中指定的文件媒体类型。可接受的值包括以下内容。对于 gemini-2.0-flash-lite 和 gemini-2.0-flash，音频文件的最大长度为 8.4 小时，视频文件（无音频）的最大长度为一小时。有关更多信息，请参阅 Gemini 音频和视频要求。文本文件必须为 UTF-8 编码。文本文件的内容计入 token 限制。图像分辨率无限制。

  可能的值：`application/pdf`, `audio/mpeg`, `audio/mp3`, `audio/wav`, `image/png`, `image/jpeg`, `image/webp`, `text/plain`, `video/mov`, `video/mpeg`, `video/mp4`, `video/mpg`, `video/avi`, `video/wmv`, `video/mpegps`, `video/flv`, `image/heic`, `image/heif`, `audio/flac`, `video/webm`
</ParamField>

<ParamField body="contents[].parts[].mediaProcessing" type="string">
  模型读取该部分视频的方式。设置为 "AGENTIC" 可让模型自行决定要检查的片段，而不是按固定速率采样帧。使用默认的固定速率采样时请省略。在 gemini-3.7-flash 及更新的 Flash 模型上受支持。
</ParamField>

<ParamField body="contents[].parts[].text" type="string">
  文本提示词或代码片段。
</ParamField>

<ParamField body="contents[].parts[].thought" type="boolean">
  表示该部分是模型产生的思考/推理步骤。
</ParamField>

<ParamField body="contents[].role" type="string">
  可能的值：`user`、`model`
</ParamField>

<ParamField body="generationConfig" type="object">
  用于生成的采样、长度和输出设置。每个字段都是可选的：下面声明了 `default` 的字段在省略时会使用该默认值，其余字段则回退到模型自身的行为。
</ParamField>

<ParamField body="generationConfig.imageConfig" type="object">
  图像生成配置
</ParamField>

<ParamField body="generationConfig.imageConfig.aspectRatio" type="string">
  已生成图像的宽高比
</ParamField>

<ParamField body="generationConfig.imageConfig.imageOutputOptions" type="object">
  可选。已生成图像的图像输出格式。
</ParamField>

<ParamField body="generationConfig.imageConfig.imageOutputOptions.compressionQuality" type="integer">
  可选。输出图像的压缩质量。
</ParamField>

<ParamField body="generationConfig.imageConfig.imageOutputOptions.mimeType" type="string">
  可选。输出应保存为的图像格式。
</ParamField>

<ParamField body="generationConfig.imageConfig.imageSize" type="string">
  可选。指定已生成图像的尺寸。支持的值为 1K、2K、4K。如果未指定，模型将使用默认值 1K。
</ParamField>

<ParamField body="generationConfig.maxOutputTokens" type="integer">
  响应中可以生成的最大 token 数。一个 token 约等于 4 个字符。100 个 token 大致对应 60-80 个单词。

  范围：`16` 到 `65536`
</ParamField>

<ParamField body="generationConfig.responseModalities" type="`TEXT`, `IMAGE`[]" />

<ParamField body="generationConfig.seed" type="integer">
  当种子固定为特定值时，模型会尽力为重复请求提供相同的响应。无法保证输出是确定性的。此外，更改模型或参数设置（例如温度）可能导致响应发生变化，即使使用相同的种子值也是如此。默认情况下，会使用随机种子值。适用于以下模型：gemini-2.5-flash、gemini-2.5-pro、gemini-2.5-flash-preview-04-1、gemini-2.5-pro-preview-05-0、gemini-2.0-flash-lite-00、gemini-2.0-flash-001
</ParamField>

<ParamField body="generationConfig.stopSequences" type="string[]" />

<ParamField body="generationConfig.temperature" type="number" default="1">
  温度用于响应生成期间的采样，采样发生在应用 topP 和 topK 时。温度控制 token 选择中的随机程度。较低的温度适合需要更收敛或更少创造性响应的提示词，而较高的温度则可能带来更多样化或更具创造性的结果。温度为 0 表示始终选择概率最高的 token。在这种情况下，给定提示词的响应大多是确定性的，但仍可能存在少量变化。如果模型返回的响应过于笼统、过于简短，或者模型给出了兜底响应，请尝试提高温度

  范围：`0` 到 `2`

  格式：`float`
</ParamField>

<ParamField body="generationConfig.thinkingConfig" type="object">
  可选。思考功能的配置。思考是模型将复杂任务拆解为更小步骤以生成更高质量响应的过程。
</ParamField>

<ParamField body="generationConfig.thinkingConfig.includeThoughts" type="boolean">
  可选。如果为是，模型将在响应中包含其思考内容。
</ParamField>

<ParamField body="generationConfig.thinkingConfig.thinkingBudget" type="integer">
  可选。模型思考过程的 token 预算。模型将尽力保持在此预算范围内。
</ParamField>

<ParamField body="generationConfig.thinkingConfig.thinkingLevel" type="string">
  可选。模型的思考级别。

  可选值：`THINKING_LEVEL_UNSPECIFIED`、`LOW`、`MEDIUM`、`HIGH`、`MINIMAL`
</ParamField>

<ParamField body="generationConfig.topK" type="integer" default="40">
  Top-K 会改变模型选择输出 token 的方式。Top-K 为 1 表示下一个被选择的 token 是模型词表中所有 token 里概率最高的。Top-K 为 3 表示下一个 token 通过温度从概率最高的 3 个 token 中选出。

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

<ParamField body="generationConfig.topP" type="number" default="0.95">
  如果指定，将使用核采样。
  Top-P 会改变模型选择输出 token 的方式。token 按概率从最高（参见 top-K）到最低进行选择，直到它们的概率之和等于 top-P 值。例如，如果 token A、B 和 C 的概率分别为 0.3、0.2 和 0.1，且 top-P 值为 0.5，那么模型将使用温度从 A 或 B 中选择下一个 token，并排除 C 作为候选项。
  指定较低的值可获得随机性更低的响应，指定较高的值可获得随机性更高的响应。

  范围：`0` 到 `1`

  格式：`float`
</ParamField>

<ParamField body="safetySettings" type="object[]">
  用于拦截不安全内容的按请求设置。在 GenerateContentResponse.candidates 上强制执行。
</ParamField>

<ParamField body="safetySettings[].category" type="string" required>
  可选值：`HARM_CATEGORY_SEXUALLY_EXPLICIT`、`HARM_CATEGORY_HATE_SPEECH`、`HARM_CATEGORY_HARASSMENT`、`HARM_CATEGORY_DANGEROUS_CONTENT`
</ParamField>

<ParamField body="safetySettings[].threshold" type="string" required>
  可选值：`OFF`、`BLOCK_NONE`、`BLOCK_LOW_AND_ABOVE`、`BLOCK_MEDIUM_AND_ABOVE`、`BLOCK_ONLY_HIGH`
</ParamField>

<ParamField body="systemInstruction" type="object">
  用于引导模型获得更佳表现的指令。例如，"尽可能简洁地回答"或"不要在响应中使用技术术语"。文本字符串会计入 token 限制。systemInstruction 的 role 字段会被忽略，不会影响模型的表现。注意：parts 中只应使用文本，且每个 part 的内容应位于单独的段落中。
</ParamField>

<ParamField body="systemInstruction.parts" type="object[]" required>
  组成单条消息的有序 parts 列表。不同 part 可以有不同的 IANA MIME 类型。有关输入的限制，例如最大 token 数量或图像数量，请参阅 Google 模型页面上的模型规格。
</ParamField>

<ParamField body="systemInstruction.parts[].text" type="string">
  文本提示词或代码片段。
</ParamField>

<ParamField body="systemInstruction.role" type="string">
  创建该消息的实体的身份。支持以下值：user：表示消息由真实的人发送，通常是用户生成的消息。model：表示消息由模型生成。在多轮对话中，使用 model 值将模型的消息插入到对话中。对于非多轮对话，此字段可以留空或不设置。

  可选值：`user`、`model`
</ParamField>

<ParamField body="tools" type="object[]">
  一段代码，使系统能够与外部系统交互，以在模型的知识和范围之外执行某项操作或一组操作。参见函数调用。
</ParamField>

<ParamField body="tools[].functionDeclarations" type="object[]" />

<ParamField body="tools[].functionDeclarations[].description" type="string" />

<ParamField body="tools[].functionDeclarations[].name" type="string" required />

<ParamField body="tools[].functionDeclarations[].parameters" type="object">
  函数参数的 JSON schema
</ParamField>

<ParamField body="uploadImagesToStorage" type="boolean">
  如果为是，生成的图像将上传到云端存储，并以签名 URL 的形式返回，而不是内联 base64 数据。这些 URL 会在 24 小时后过期。
</ParamField>

<ParamField body="videoMetadata" type="object">
  对于视频输入，指视频以 Duration 格式表示的起始和结束偏移量。例如，要指定从 1:00 开始的 10 秒片段，请设置 "startOffset": \{ "seconds": 60 } 和 "endOffset": \{ "seconds": 70 }。仅当视频数据以 inlineData 或 fileData 呈现时，才应指定该元数据。
</ParamField>

<ParamField body="videoMetadata.endOffset" type="object">
  表示视频时间轴位置的时间时长偏移量。
</ParamField>

<ParamField body="videoMetadata.endOffset.nanos" type="integer">
  以纳秒为单位的带符号秒数小数部分。带有小数部分的负秒值，其 nanos 值仍必须为非负数。

  范围：`0` 至 `999999999`
</ParamField>

<ParamField body="videoMetadata.endOffset.seconds" type="integer">
  时间段内带符号的秒数。必须介于 -315,576,000,000 至 +315,576,000,000（含边界值）之间。

  范围：`-315576000000` 至 `315576000000`
</ParamField>

<ParamField body="videoMetadata.startOffset" type="object">
  表示视频时间轴位置的时间时长偏移量。
</ParamField>

<ParamField body="videoMetadata.startOffset.nanos" type="integer">
  以纳秒为单位的带符号秒数小数部分。带有小数部分的负秒值，其 nanos 值仍必须为非负数。

  范围：`0` 至 `999999999`
</ParamField>

<ParamField body="videoMetadata.startOffset.seconds" type="integer">
  时间段内带符号的秒数。必须介于 -315,576,000,000 至 +315,576,000,000（含边界值）之间。

  范围：`-315576000000` 至 `315576000000`
</ParamField>

由 Router 在 `GET /v2/models/vertexai/gemini-3.1-flash-image/openapi.json` 提供的 schema 生成，该文档与其在请求到达提供商之前用于验证调用的文档相同。

### 输出

<ResponseField name="candidates" type="object[]" />

<ResponseField name="candidates[].citationMetadata" type="object" />

<ResponseField name="candidates[].citationMetadata.citations" type="object[]" />

<ResponseField name="candidates[].citationMetadata.citations[].authors" type="string[]" />

<ResponseField name="candidates[].citationMetadata.citations[].endIndex" type="integer" />

<ResponseField name="candidates[].citationMetadata.citations[].license" type="string" />

<ResponseField name="candidates[].citationMetadata.citations[].publicationDate" type="string (date)">
  格式：`date`
</ResponseField>

<ResponseField name="candidates[].citationMetadata.citations[].startIndex" type="integer" />

<ResponseField name="candidates[].citationMetadata.citations[].title" type="string" />

<ResponseField name="candidates[].citationMetadata.citations[].uri" type="string" />

<ResponseField name="candidates[].content" type="object">
  与模型进行的当前对话内容。对于单轮查询，这是一个单独的实例。对于多轮查询，这是一个重复字段，包含对话历史和最新的请求。
</ResponseField>

<ResponseField name="candidates[].content.parts" type="object[]" required />

<ResponseField name="candidates[].content.parts[].fileData" type="object">
  基于 URI 的数据。
</ResponseField>

<ResponseField name="candidates[].content.parts[].fileData.fileUri" type="string">
  URI
</ResponseField>

<ResponseField name="candidates[].content.parts[].fileData.mimeType" type="string">
  在 data 或 fileUri 字段中指定的文件的媒体类型。可接受的值包括以下内容。对于 gemini-2.0-flash-lite 和 gemini-2.0-flash，音频文件的最大长度为 8.4 小时，视频文件（不含音频）的最大长度为一小时。有关更多信息，请参阅 Gemini 音频和视频要求。文本文件必须采用 UTF-8 编码。文本文件的内容计入 token 上限。图像分辨率无限制。

  可能的值：`application/pdf`、`audio/mpeg`、`audio/mp3`、`audio/wav`、`image/png`、`image/jpeg`、`image/webp`、`text/plain`、`video/mov`、`video/mpeg`、`video/mp4`、`video/mpg`、`video/avi`、`video/wmv`、`video/mpegps`、`video/flv`、`image/heic`、`image/heif`、`audio/flac`、`video/webm`
</ResponseField>

<ResponseField name="candidates[].content.parts[].inlineData" type="object">
  以原始字节形式内联的数据。对于 gemini-2.0-flash-lite 和 gemini-2.0-flash，你最多可以通过 inlineData 指定 3000 张图像。
</ResponseField>

<ResponseField name="candidates[].content.parts[].inlineData.data" type="string (byte)">
  图像、PDF 或视频的 base64 编码，以内联方式包含在提示词中。以内联方式包含媒体时，还必须指定数据的媒体类型（mimeType）。大小限制：20MB

  格式：`byte`
</ResponseField>

<ResponseField name="candidates[].content.parts[].inlineData.mimeType" type="string">
  在 data 或 fileUri 字段中指定的文件的媒体类型。可接受的值包括以下内容。对于 gemini-2.0-flash-lite 和 gemini-2.0-flash，音频文件的最大长度为 8.4 小时，视频文件（不含音频）的最大长度为一小时。有关更多信息，请参阅 Gemini 音频和视频要求。文本文件必须采用 UTF-8 编码。文本文件的内容计入 token 上限。图像分辨率无限制。

  可能的值：`application/pdf`、`audio/mpeg`、`audio/mp3`、`audio/wav`、`image/png`、`image/jpeg`、`image/webp`、`text/plain`、`video/mov`、`video/mpeg`、`video/mp4`、`video/mpg`、`video/avi`、`video/wmv`、`video/mpegps`、`video/flv`、`image/heic`、`image/heif`、`audio/flac`、`video/webm`
</ResponseField>

<ResponseField name="candidates[].content.parts[].mediaProcessing" type="string">
  模型读取该部分视频的方式。设置为 "AGENTIC" 可让模型自行决定要检查的片段，而不是按固定速率采样帧。使用默认的固定速率采样时请省略。在 gemini-3.7-flash 及更新的 Flash 模型上受支持。
</ResponseField>

<ResponseField name="candidates[].content.parts[].text" type="string">
  文本提示词或代码片段。
</ResponseField>

<ResponseField name="candidates[].content.parts[].thought" type="boolean">
  表示该部分来自模型的思考/推理步骤。
</ResponseField>

<ResponseField name="candidates[].content.role" type="string">
  可能的值：`user`、`model`
</ResponseField>

<ResponseField name="candidates[].finishReason" type="string" />

<ResponseField name="candidates[].safetyRatings" type="object[]" />

<ResponseField name="candidates[].safetyRatings[].category" type="string">
  可能的值：`HARM_CATEGORY_SEXUALLY_EXPLICIT`、`HARM_CATEGORY_HATE_SPEECH`、`HARM_CATEGORY_HARASSMENT`、`HARM_CATEGORY_DANGEROUS_CONTENT`
</ResponseField>

<ResponseField name="candidates[].safetyRatings[].probability" type="string">
  内容违反指定安全类别的概率

  可能的值：`NEGLIGIBLE`、`LOW`、`MEDIUM`、`HIGH`、`UNKNOWN`
</ResponseField>

<ResponseField name="createTime" type="string">
  响应创建时的时间戳。
</ResponseField>

<ResponseField name="modelVersion" type="string">
  用于生成响应的模型版本。
</ResponseField>

<ResponseField name="promptFeedback" type="object" />

<ResponseField name="promptFeedback.blockReason" type="string" />

<ResponseField name="promptFeedback.blockReasonMessage" type="string" />

<ResponseField name="promptFeedback.safetyRatings" type="object[]" />

<ResponseField name="promptFeedback.safetyRatings[].category" type="string">
  可能的值：`HARM_CATEGORY_SEXUALLY_EXPLICIT`、`HARM_CATEGORY_HATE_SPEECH`、`HARM_CATEGORY_HARASSMENT`、`HARM_CATEGORY_DANGEROUS_CONTENT`
</ResponseField>

<ResponseField name="promptFeedback.safetyRatings[].probability" type="string">
  内容违反指定安全类别的概率

  可能的值：`NEGLIGIBLE`、`LOW`、`MEDIUM`、`HIGH`、`UNKNOWN`
</ResponseField>

<ResponseField name="responseId" type="string">
  响应的唯一标识符。
</ResponseField>

<ResponseField name="usageMetadata" type="object" />

<ResponseField name="usageMetadata.cachedContentTokenCount" type="integer">
  仅输出。输入中缓存部分（缓存内容）的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.candidatesTokenCount" type="integer">
  响应中的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.candidatesTokensDetails" type="object[]">
  按模态划分的候选 token 明细。
</ResponseField>

<ResponseField name="usageMetadata.candidatesTokensDetails[].modality" type="string">
  输入或输出内容的模态类型。

  可能的值：`MODALITY_UNSPECIFIED`、`TEXT`、`IMAGE`、`VIDEO`、`AUDIO`、`DOCUMENT`
</ResponseField>

<ResponseField name="usageMetadata.candidatesTokensDetails[].tokenCount" type="integer">
  给定模态的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.promptTokenCount" type="integer">
  请求中的 token 数量。当设置了 cachedContent 时，这仍然是有效的提示词总大小，也就是说它包含缓存内容中的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.promptTokensDetails" type="object[]">
  按模态划分的提示词 token 明细。
</ResponseField>

<ResponseField name="usageMetadata.promptTokensDetails[].modality" type="string">
  输入或输出内容的模态类型。

  可能的值：`MODALITY_UNSPECIFIED`、`TEXT`、`IMAGE`、`VIDEO`、`AUDIO`、`DOCUMENT`
</ResponseField>

<ResponseField name="usageMetadata.promptTokensDetails[].tokenCount" type="integer">
  给定模态的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.thoughtsTokenCount" type="integer">
  思考输出中存在的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.toolUsePromptTokenCount" type="integer">
  工具使用提示词中存在的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.toolUsePromptTokensDetails" type="object[]">
  按模态细分的工具使用提示 token。
</ResponseField>

<ResponseField name="usageMetadata.toolUsePromptTokensDetails[].modality" type="string">
  输入或输出内容模态的类型。

  可能的值：`MODALITY_UNSPECIFIED`、`TEXT`、`IMAGE`、`VIDEO`、`AUDIO`、`DOCUMENT`
</ResponseField>

<ResponseField name="usageMetadata.toolUsePromptTokensDetails[].tokenCount" type="integer">
  给定模态的 token 数量。
</ResponseField>

<ResponseField name="usageMetadata.totalTokenCount" type="integer">
  token 总数（提示词 + 候选）。
</ResponseField>

<ResponseField name="usageMetadata.trafficType" type="string">
  用于请求的流量类型（例如 PROVISIONED\_THROUGHPUT）。
</ResponseField>

## 示例

### 输入

```json theme={null}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "a single red maple leaf on a plain white background, studio lighting"
        }
      ]
    }
  ],
  "generationConfig": {
    "responseModalities": [
      "IMAGE"
    ],
    "imageConfig": {
      "aspectRatio": "1:1"
    }
  }
}
```

### 输出

```json theme={null}
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "inlineData": {
              "mimeType": "image/png",
              "data": "PGJhc2U2ND4="
            }
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 12,
    "candidatesTokenCount": 1290
  }
}
```

默认情况下，已生成的图像部分在 `inlineData.data` 中包含 base64 字节，并在 `inlineData.mimeType` 中包含媒体类型。请解码这些字节并将其保存到文件中。当 `uploadImagesToStorage: true` 时，上传的图像则使用 `fileData.fileUri` 提供签名 URL，并使用 `fileData.mimeType` 表示媒体类型。请在 URL 过期之前下载这些图像，即创建后 24 小时内。上传失败会使该图像保持内联形式，因此请检查每个部分中的 `inlineData` 或 `fileData`；文本部分也可能出现，并且图像不保证是第一个部分。

## 发布前须知

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>
