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

# 通过 Comfy Router 使用 Google Gemini

> 通过 Comfy Router 以 HTTP 方式调用 Google Gemini 文本模型的 Python、TypeScript 和 cURL 代码片段，以及请求字段和返回结果的结构

Google Gemini 的 API 参考。Google Gemini 是 Google 的多模态文本模型系列，在 Flash 和 Pro 各层级中覆盖从快速起草到深度推理的各类场景。

## 快速开始

在[你的 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 发出的同一调用。

选择你想要调用的模型。这些模型共用同一套请求和响应结构，下文会统一说明一次。

<Tabs>
  <Tab title="Gemini 3.1 Pro">
    **模型 ID：** `vertexai/gemini-3.1-pro-preview`

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

    <Tabs>
      <Tab title="等待结果">
        <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-pro-preview",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )

          print("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const { data } = await comfy.models.run<Result>("vertexai/gemini-3.1-pro-preview", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });

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

          ```bash cURL theme={null}
          curl https://api.comfy.org/v2/models/vertexai/gemini-3.1-pro-preview \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"
          ```
        </CodeGroup>
      </Tab>

      <Tab title="排队并稍后收集">
        将相同的请求体发送到 `POST https://api.comfy.org/v2/models/vertexai/gemini-3.1-pro-preview/requests`。Router 会在运行被受理后立即返回 `201` 和 `request_id`，结果就绪后即可从本进程或其他进程收集。[队列投递](/zh/development/comfy-router/queue)详细介绍了状态查询、取消和结果收集。

        <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-pro-preview",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )
              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("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const handle = await comfy.models.submit<Result>("vertexai/gemini-3.1-pro-preview", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });
          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("text:", result.data.candidates[0].content.parts[0].text);
          ```

          ```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-pro-preview/requests \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"

          # 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-pro-preview/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-pro-preview/requests/$REQUEST_ID \
            -H "X-API-Key: $COMFY_API_KEY"
          ```
        </CodeGroup>
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="Gemini 3.5 Flash">
    **模型 ID：** `vertexai/gemini-3.5-flash`

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

    <Tabs>
      <Tab title="等待结果">
        <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.5-flash",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )

          print("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const { data } = await comfy.models.run<Result>("vertexai/gemini-3.5-flash", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });

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

          ```bash cURL theme={null}
          curl https://api.comfy.org/v2/models/vertexai/gemini-3.5-flash \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"
          ```
        </CodeGroup>
      </Tab>

      <Tab title="排队并稍后收集">
        将相同的请求体发送到 `POST https://api.comfy.org/v2/models/vertexai/gemini-3.5-flash/requests`。Router 会在运行被受理后立即返回 `201` 和 `request_id`，结果就绪后即可从本进程或其他进程收集。[队列投递](/zh/development/comfy-router/queue)详细介绍了状态查询、取消和结果收集。

        <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.5-flash",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )
              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("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const handle = await comfy.models.submit<Result>("vertexai/gemini-3.5-flash", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });
          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("text:", result.data.candidates[0].content.parts[0].text);
          ```

          ```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.5-flash/requests \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"

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

  <Tab title="Gemini 2.5 Pro">
    **模型 ID：** `vertexai/gemini-2.5-pro`

    **端点：** `POST https://api.comfy.org/v2/models/vertexai/gemini-2.5-pro`

    <Tabs>
      <Tab title="等待结果">
        <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-2.5-pro",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )

          print("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const { data } = await comfy.models.run<Result>("vertexai/gemini-2.5-pro", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });

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

          ```bash cURL theme={null}
          curl https://api.comfy.org/v2/models/vertexai/gemini-2.5-pro \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"
          ```
        </CodeGroup>
      </Tab>

      <Tab title="排队并稍后收集">
        将相同的请求体发送到 `POST https://api.comfy.org/v2/models/vertexai/gemini-2.5-pro/requests`。Router 会在运行被受理后立即返回 `201` 和 `request_id`，结果就绪后即可从本进程或其他进程收集。[队列投递](/zh/development/comfy-router/queue)详细介绍了状态查询、取消和结果收集。

        <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-2.5-pro",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )
              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("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const handle = await comfy.models.submit<Result>("vertexai/gemini-2.5-pro", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });
          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("text:", result.data.candidates[0].content.parts[0].text);
          ```

          ```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-2.5-pro/requests \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"

          # 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-2.5-pro/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-2.5-pro/requests/$REQUEST_ID \
            -H "X-API-Key: $COMFY_API_KEY"
          ```
        </CodeGroup>
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="Gemini 2.5 Flash">
    **模型 ID：** `vertexai/gemini-2.5-flash`

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

    <Tabs>
      <Tab title="等待结果">
        <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-2.5-flash",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )

          print("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const { data } = await comfy.models.run<Result>("vertexai/gemini-2.5-flash", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });

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

          ```bash cURL theme={null}
          curl https://api.comfy.org/v2/models/vertexai/gemini-2.5-flash \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"
          ```
        </CodeGroup>
      </Tab>

      <Tab title="排队并稍后收集">
        将相同的请求体发送到 `POST https://api.comfy.org/v2/models/vertexai/gemini-2.5-flash/requests`。Router 会在运行被受理后立即返回 `201` 和 `request_id`，结果就绪后即可从本进程或其他进程收集。[队列投递](/zh/development/comfy-router/queue)详细介绍了状态查询、取消和结果收集。

        <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-2.5-flash",
                  {
                      "contents": [
                          {
                              "role": "user",
                              "parts": [
                                  {
                                      "text": "Describe a single red maple leaf on a white background in one sentence.",
                                  },
                              ],
                          },
                      ],
                      "generationConfig": {
                          "temperature": 0.7,
                          "maxOutputTokens": 256,
                      },
                  },
              )
              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("text:", result["candidates"][0]["content"]["parts"][0]["text"])
          ```

          ```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: { text: string }[] } }[] };
          const handle = await comfy.models.submit<Result>("vertexai/gemini-2.5-flash", {
            contents: [
              {
                role: "user",
                parts: [
                  {
                    text: "Describe a single red maple leaf on a white background in one sentence.",
                  },
                ],
              },
            ],
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 256,
            },
          });
          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("text:", result.data.candidates[0].content.parts[0].text);
          ```

          ```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-2.5-flash/requests \
            -H "X-API-Key: $COMFY_API_KEY" \
            -H "Idempotency-Key: $(uuidgen)" \
            -H "Content-Type: application/json" \
            -d "{\"contents\": [{\"role\":\"user\",\"parts\":[{\"text\":\"Describe a single red maple leaf on a white background in one sentence.\"}]}], \"generationConfig\": {\"temperature\":0.7,\"maxOutputTokens\":256}}"

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

## 架构

### 输入

<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">
  可选。如果为 true，模型会在回答中包含其思考过程。
</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">
  如果为 true，生成的图像将上传到云端存储，并以签名 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-pro-preview/openapi.json` 上提供的 schema 生成，这也是请求到达提供商之前 Router 用于校验调用的同一份文档。

### 输出

<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">
  thoughts 输出中包含的 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": "Describe a single red maple leaf on a white background in one sentence."
        }
      ]
    }
  ],
  "generationConfig": {
    "temperature": 0.7,
    "maxOutputTokens": 256
  }
}
```

### 输出

```json theme={null}
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "A single red maple leaf rests on a plain white background, its edges sharp and its color deep."
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 18,
    "candidatesTokenCount": 24
  }
}
```

## 发布前须知

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>
