> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hairoute.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini 原生图片生成（流式）

> 使用 Gemini 原生 streamGenerateContent 接口以 SSE 流式接收图片结果，仅适用于 Google/Gemini 图片模型

使用 Gemini 原生 `streamGenerateContent` 按块接收生成结果。**在图片模型中，此端点仅供 Google/Gemini 图片模型使用**；其他图片模型请使用其相应的 [OpenAI 图片接口](/docs/zh/api-reference/images/openai/generation)。Gemini 聊天模型的原生流式调用不属于本图片接口文档的范围。

## 功能特性

* 使用 Gemini 原生 `streamGenerateContent` 端点，按 SSE 数据块接收图片生成结果
* 请求体结构与[非流式接口](/docs/zh/api-reference/images/gemini/generation)相同，支持文生图、单图编辑、多图参考合成和多轮继续编辑
* 可通过 `generationConfig.responseModalities` 与 `generationConfig.imageConfig` 配置图片输出；不需要 `stream: true`
* 在 `candidates[].content.parts[]` 中接收文本和 Base64 图片，而不是 OpenAI 图片 URL 或命名事件

## 认证方式

`POST https://api.hairoute.ai/v1/models/{model}:streamGenerateContent`

`{model}` 是 [模型列表](https://portal.hairoute.ai/zh/models) 中可用的 Google/Gemini 图片模型名，不放在请求体中。使用 HaiRoute API Key，通过 `x-goog-api-key: YOUR_API_KEY` 或 `Authorization: Bearer YOUR_API_KEY` 认证。请求体可传 `contents`、`generationConfig.responseModalities` 和 `generationConfig.imageConfig`；该路由始终返回 `text/event-stream`。

## 支持的图片模型

此端点仅用于 Google/Gemini 图片模型。

| 模型标识                          | 模型类型    | 模型描述                                                          |
| ----------------------------- | ------- | ------------------------------------------------------------- |
| `gemini-3.1-flash-lite-image` | 图片生成与编辑 | Gemini 3.1 Flash Lite Image；配置的输出档位为 `1K`。                    |
| `gemini-3.1-flash-image`      | 图片生成与编辑 | Gemini 3.1 Flash Image；配置的输出档位为 `512`（约 0.5K）、`1K`、`2K`、`4K`。 |
| `gemini-3-pro-image`          | 图片生成与编辑 | Gemini 3 Pro Image；配置的输出档位为 `1K`、`2K`、`4K`。                   |

## 快速示例

```bash theme={null}
curl -N -X POST 'https://api.hairoute.ai/v1/models/YOUR_GEMINI_IMAGE_MODEL:streamGenerateContent' \
  -H 'x-goog-api-key: YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -H 'Accept: text/event-stream' \
  -d '{
    "contents": [{"role": "user", "parts": [{"text": "画一只在月球上行走的橘猫"}]}],
    "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
  }'
```

## 生成方式

以下示例只展示请求体；四种方式都使用本页同一个端点与认证方式，不需要新增 `mode` 参数。图片 Base64 均为占位符，需替换为真实图片的纯 Base64 数据。

### 文生图

只传文本提示词，不传输入图片；可直接使用上面的**快速示例**。局部修改、风格转换等是提示词要求，不是独立的接口参数。

### 单图编辑

在同一条 `user` 消息中传入一张图片和编辑指令。下面是更换背景的例子；也可以在文本中要求保留主体、修改局部元素或调整风格。

```json theme={null}
{
  "contents": [{"role": "user", "parts": [
    {"inlineData": {"mimeType": "image/png", "data": "<BASE64_INPUT_IMAGE>"}},
    {"text": "将背景改为日落海滩，保留主体"}
  ]}],
  "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}
```

### 多图参考合成

将多张参考图放入同一条 `user` 消息的 `parts`，用文本说明各图的用途。图片数量、尺寸及实际效果取决于所选模型和渠道的限制。

```json theme={null}
{
  "contents": [{"role": "user", "parts": [
    {"inlineData": {"mimeType": "image/png", "data": "<BASE64_SUBJECT_IMAGE>"}},
    {"inlineData": {"mimeType": "image/jpeg", "data": "<BASE64_BACKGROUND_IMAGE>"}},
    {"text": "以第一张图的人物为主体，使用第二张图的场景作为背景，生成一张自然的合照"}
  ]}],
  "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}
```

### 多轮继续编辑

把前一轮的 `user` 请求、实际返回的 `candidates[0].content`（作为 `model` 消息）和本轮的新指令依次放进 `contents`。下面仅示意结构：

```json theme={null}
{
  "contents": [
    {"role": "user", "parts": [{"text": "画一只戴围巾的橘猫"}]},
    {"role": "model", "parts": [
      {"inlineData": {"mimeType": "image/png", "data": "<BASE64_FROM_PREVIOUS_RESPONSE>"}}
    ]},
    {"role": "user", "parts": [{"text": "保持橘猫与围巾不变，把背景换成雪地"}]}
  ],
  "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}
```

实际调用时不要手写或裁剪上一轮的 `model` 内容；如果上一轮是流式响应，先按顺序汇总各 `data:` 块中同一候选的 `content.parts`，再将完整内容作为 `model` 消息回传，保留图片、文本及 `thoughtSignature`（如果返回）。不能只使用最后一个 SSE 块。多轮编辑和多图参考的效果取决于所选图片模型。

## 流式响应

服务端按 SSE 格式输出，每个 `data:` 行是一个完整的 Gemini `GenerateContentResponse` JSON 块；以下为示意，Base64 是占位值：

```text theme={null}
data: {"candidates":[{"content":{"role":"model","parts":[{"text":"正在生成图片"}]}}]}

data: {"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"image/png","data":"<BASE64_IMAGE_DATA>"}}]},"finishReason":"STOP"}],"usageMetadata":{"totalTokenCount":1302}}

```

逐个解析 SSE `data`，检查 `candidates[].content.parts[]`：`text` 为文本，`inlineData.data` 为 Base64 图片，`inlineData.mimeType` 表示图片格式。块可能只包含部分字段；用量通常在后续块出现。此流**没有** OpenAI 格式的命名事件和 `[DONE]` 标记，不要将 Base64 片段或单个块当作图片 URL。

## 常见错误排查

先检查 HTTP 状态及返回体中的 `error`；流式请求还需检查已收到的每个 SSE `data:` 块。不要在日志或求助信息中贴出 API Key、完整图片 Base64。

| 现象              | 排查方法                                                                                                                                                                                             |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 认证失败（如 401/403） | 确认使用 **HaiRoute API Key**，并通过 `x-goog-api-key` 或 `Authorization: Bearer` 传入；不要把 Google API Key 填在这里。检查 Key 是否有效、是否有模型访问权限。                                                                       |
| 模型找不到或不可用       | 检查 URL 中的 `{model}` 是否为当前账户 [模型列表](https://portal.hairoute.ai/zh/models) 中可用的 Google/Gemini **图片模型**；不要把模型名放在请求体里，也不要用其他图片模型调用此端点。                                                               |
| 请求参数或输入图片报错     | 核对 `contents[].parts`、`generationConfig.responseModalities`（图片输出为 `["TEXT", "IMAGE"]`）和所选模型支持的 `imageConfig`；`inlineData.data` 必须是纯 Base64，不含 `data:image/...;base64,` 前缀，`mimeType` 要与输入图片格式一致。 |
| 响应成功但没找到图片      | 逐个检查 `candidates[].content.parts[].inlineData`；图片不在 `data[].url`。若没有图片，检查返回的 `finishReason`、`promptFeedback` 和文本内容，再调整提示词或请求配置；不要把 HTTP 200 等同于已出图。                                              |
| 流式没有图片或解析失败     | 以空行分隔 SSE 事件，逐条解析 `data:` 后面的 JSON；图片可能在任意块的 `candidates[].content.parts[].inlineData`，不能只读取最后一块。本端点没有 OpenAI 命名事件或 `[DONE]`。若连接中途断开，不能仅凭已收到的文本或用量判断出图成功。                                        |
| 多轮编辑失败或没有延续上轮   | 按顺序回传先前的 `user` 消息、上一轮完整的 `candidates[0].content`（包括 `thoughtSignature`，如果返回）以及新的 `user` 指令；不要只回传图片 Base64。                                                                                      |

## 下一步

* 查看 [非流式接口](/docs/zh/api-reference/images/gemini/generation) 了解非流式完整响应
* 查看 [模型列表](https://portal.hairoute.ai/zh/models) 选择可用图片模型


## OpenAPI

````yaml zh/api-reference/images/gemini/stream-generation/openapi.json POST /v1/models/{model}:streamGenerateContent
openapi: 3.0.1
info:
  title: Gemini 原生图片接口
  version: 1.0.0
servers:
  - url: https://api.hairoute.ai
security: []
paths:
  /v1/models/{model}:streamGenerateContent:
    post:
      summary: 生成图片（Gemini 原生，SSE 流式）
      description: >-
        在图片模型中仅支持 Google/Gemini 图片模型；其他图片模型使用对应图片接口。 HaiRoute API Key。传入此请求头或
        Authorization: Bearer YOUR_API_KEY（二选一）。
      parameters:
        - name: model
          in: path
          required: true
          description: HaiRoute 可用的 Google/Gemini 图片模型名称
          schema:
            type: string
          example: YOUR_GEMINI_IMAGE_MODEL
        - name: x-goog-api-key
          in: header
          required: true
          description: >-
            HaiRoute API Key。此处展示原生请求头；也可改用 Authorization: Bearer YOUR_API_KEY
            认证（二选一）。
          schema:
            type: string
          example: YOUR_API_KEY
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateRequest'
            example:
              contents:
                - role: user
                  parts:
                    - text: 画一只橘猫
              generationConfig:
                responseModalities:
                  - TEXT
                  - IMAGE
                imageConfig:
                  aspectRatio: '1:1'
                  imageSize: 1K
      responses:
        '200':
          description: >-
            SSE 数据流：每个 data 帧为一个 Gemini GenerateContentResponse JSON 块，无命名事件或
            [DONE]。
          content:
            text/event-stream:
              schema:
                type: string
              example: >+
                data:
                {"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"image/png","data":"<BASE64_IMAGE_DATA>"}}]},"finishReason":"STOP"}],"usageMetadata":{"totalTokenCount":1302}}

        '400':
          description: Gemini 风格错误体。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GeminiError'
components:
  schemas:
    GenerateRequest:
      type: object
      properties:
        contents:
          type: array
          minItems: 1
          items:
            $ref: '#/components/schemas/Content'
          description: 必填。Gemini 原生消息；文生图使用 user 消息及 text part，图生图可加入 inlineData part。
        systemInstruction:
          $ref: '#/components/schemas/Content'
        generationConfig:
          $ref: '#/components/schemas/GenerationConfig'
      required:
        - contents
      additionalProperties: true
    GeminiError:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: integer
            message:
              type: string
            status:
              type: string
      description: Gemini 风格错误体。
    Content:
      type: object
      properties:
        role:
          type: string
          example: user
        parts:
          type: array
          items:
            $ref: '#/components/schemas/Part'
      required:
        - parts
      additionalProperties: true
    GenerationConfig:
      type: object
      description: Gemini 原生生成配置；具体能力由所选图片模型决定。
      properties:
        responseModalities:
          type: array
          items:
            type: string
            enum:
              - TEXT
              - IMAGE
          example:
            - TEXT
            - IMAGE
          description: 生成图片使用 ["TEXT", "IMAGE"]；可能同时返回文本。
        imageConfig:
          $ref: '#/components/schemas/ImageConfig'
        candidateCount:
          type: integer
          minimum: 1
      additionalProperties: true
    Part:
      type: object
      properties:
        text:
          type: string
        inlineData:
          $ref: '#/components/schemas/InlineData'
      additionalProperties: true
      description: 文本或图片部件。
    ImageConfig:
      type: object
      description: 图片宽高比和输出档位；支持值取决于模型。
      properties:
        aspectRatio:
          type: string
          example: '1:1'
        imageSize:
          type: string
          example: 1K
      additionalProperties: true
    InlineData:
      type: object
      description: 图片 MIME 类型与纯 Base64 数据（不含 data URI 前缀）。
      properties:
        mimeType:
          type: string
          example: image/png
        data:
          type: string
          format: byte
          example: <BASE64_IMAGE_DATA>
      required:
        - mimeType
        - data

````