> ## 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 native image generation (streaming)

> Receive native Gemini streamGenerateContent image results over SSE, for Google/Gemini image models only

Use the native Gemini `streamGenerateContent` endpoint to receive results in chunks. **For image models, this endpoint is supported only for Google/Gemini image models.** Use the appropriate [OpenAI image endpoint](/docs/en/api-reference/images/openai/generation) for other image models. Native streaming for Gemini chat models is outside the scope of this image reference.

## Features

* Use the native Gemini `streamGenerateContent` endpoint to receive image results as SSE frames
* Use the same request body as the [non-streaming endpoint](/docs/en/api-reference/images/gemini/generation) for text-to-image, image editing, multiple references, or multi-turn editing
* Configure image output with `generationConfig.responseModalities` and `generationConfig.imageConfig`; no `stream: true` field is needed
* Receive text and Base64 images in `candidates[].content.parts[]`, not OpenAI image URLs or named events

## Authentication

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

`{model}` is an available Google/Gemini image model from the [model list](https://portal.hairoute.ai/en/models), not a request-body field. Use your HaiRoute API key in `x-goog-api-key: YOUR_API_KEY` or `Authorization: Bearer YOUR_API_KEY`. The body can include `contents`, `generationConfig.responseModalities`, and optionally `generationConfig.imageConfig`; this route always responds with `text/event-stream`.

## Supported image models

This endpoint is only for Google/Gemini image models.

| Model identifier              | Model type                   | Description                                                                            |
| ----------------------------- | ---------------------------- | -------------------------------------------------------------------------------------- |
| `gemini-3.1-flash-lite-image` | Image generation and editing | Gemini 3.1 Flash Lite Image; configured output tier: `1K`.                             |
| `gemini-3.1-flash-image`      | Image generation and editing | Gemini 3.1 Flash Image; configured output tiers: `512` (about 0.5K), `1K`, `2K`, `4K`. |
| `gemini-3-pro-image`          | Image generation and editing | Gemini 3 Pro Image; configured output tiers: `1K`, `2K`, `4K`.                         |

## Quick example

```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": "Draw an orange cat walking on the moon"}]}],
    "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
  }'
```

## Generation modes

These examples show request bodies only. All four modes use this page's endpoint and authentication; no separate `mode` parameter is needed. Replace every Base64 placeholder with actual raw Base64 image data.

### Text-to-image

Send a text prompt without an input image; the **Quick example** above is ready to adapt. Local changes and style adjustments are prompt instructions, not separate API parameters.

### Single-image editing

Put one image and an editing instruction in the same `user` message. This example replaces the background; you can also ask to preserve the subject, change an element, or adjust the style.

```json theme={null}
{
  "contents": [{"role": "user", "parts": [
    {"inlineData": {"mimeType": "image/png", "data": "<BASE64_INPUT_IMAGE>"}},
    {"text": "Replace the background with a sunset beach and keep the subject"}
  ]}],
  "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}
```

### Multiple-reference composition

Put multiple reference images in one `user` message's `parts` and describe the role of each image in the text. Input count, size limits, and results depend on the selected model and channel.

```json theme={null}
{
  "contents": [{"role": "user", "parts": [
    {"inlineData": {"mimeType": "image/png", "data": "<BASE64_SUBJECT_IMAGE>"}},
    {"inlineData": {"mimeType": "image/jpeg", "data": "<BASE64_BACKGROUND_IMAGE>"}},
    {"text": "Use the person in the first image as the subject and the scene in the second as the background; make a natural composite"}
  ]}],
  "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}
```

### Multi-turn editing

Send the previous `user` request, the actual previous `candidates[0].content` as a `model` message, and your new instruction in that order within `contents`. This body illustrates the structure only:

```json theme={null}
{
  "contents": [
    {"role": "user", "parts": [{"text": "Draw an orange cat wearing a scarf"}]},
    {"role": "model", "parts": [
      {"inlineData": {"mimeType": "image/png", "data": "<BASE64_FROM_PREVIOUS_RESPONSE>"}}
    ]},
    {"role": "user", "parts": [{"text": "Keep the cat and scarf, but replace the background with a snowy landscape"}]}
  ],
  "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}
}
```

For a real request, do not reconstruct or trim the prior `model` content. If the prior response was streamed, collect `content.parts` for the same candidate from all `data:` frames in order, then replay the complete content as the `model` message, preserving images, text, and `thoughtSignature` when present. The last SSE frame alone is not enough. Multiple references and multi-turn results depend on the selected image model.

## Streaming response

The server sends SSE frames. Each `data:` line contains one complete Gemini `GenerateContentResponse` JSON chunk. The following frames are illustrative; the Base64 string is a placeholder:

```text theme={null}
data: {"candidates":[{"content":{"role":"model","parts":[{"text":"Generating image"}]}}]}

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

```

Parse each SSE `data` frame and inspect `candidates[].content.parts[]`: `text` contains text; `inlineData.data` contains a Base64 image and `inlineData.mimeType` identifies its format. Some frames may omit these fields; usage usually arrives in a later chunk. This stream has **no** OpenAI-style named events or `[DONE]` marker. Do not treat a frame or Base64 image as an image URL.

## Troubleshooting

Check the HTTP status and the `error` in the response body first; for streaming requests, inspect every received SSE `data:` frame. Never paste API keys or complete image Base64 in logs or support requests.

| Symptom                                           | What to check                                                                                                                                                                                                                                                                                                                                |
| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Authentication fails (for example, 401/403)       | Use a **HaiRoute API key** in either `x-goog-api-key` or `Authorization: Bearer`; do not use a Google API key here. Check that the key is valid and allowed to access the model.                                                                                                                                                             |
| Model not found or unavailable                    | Check that `{model}` in the URL is an available Google/Gemini **image model** in your account’s [model list](https://portal.hairoute.ai/en/models). Do not put the model name in the request body or use a different image model on this endpoint.                                                                                           |
| Invalid request or input image                    | Check `contents[].parts`, `generationConfig.responseModalities` (`["TEXT", "IMAGE"]` for image output), and the selected model’s supported `imageConfig`. `inlineData.data` must be raw Base64 without a `data:image/...;base64,` prefix; `mimeType` must match the input image format.                                                      |
| Request succeeds but no image appears             | Inspect all `candidates[].content.parts[].inlineData`; the image is not in `data[].url`. If absent, inspect `finishReason`, `promptFeedback`, and returned text before adjusting the prompt or request. HTTP 200 alone does not prove an image was generated.                                                                                |
| No image in streaming output or SSE parsing fails | Split SSE events at blank lines and parse the JSON in each `data:` line. An image may appear in `candidates[].content.parts[].inlineData` in any frame; do not read only the last one. This endpoint has no OpenAI-style named events or `[DONE]`. If the connection drops early, text or usage alone does not prove an image was generated. |
| Multi-turn edit fails or ignores earlier output   | Replay the prior `user` message, the complete previous `candidates[0].content` (including `thoughtSignature` if returned), and the new `user` instruction in order; sending only the image Base64 is insufficient.                                                                                                                           |

## Next steps

* See the [non-streaming endpoint](/docs/en/api-reference/images/gemini/generation) for a full non-streaming response example
* See the [model list](https://portal.hairoute.ai/en/models) to choose an available image model


## OpenAPI

````yaml en/api-reference/images/gemini/stream-generation/openapi.json POST /v1/models/{model}:streamGenerateContent
openapi: 3.0.1
info:
  title: Gemini native image API
  version: 1.0.0
servers:
  - url: https://api.hairoute.ai
security: []
paths:
  /v1/models/{model}:streamGenerateContent:
    post:
      summary: Generate an image (native Gemini, SSE streaming)
      description: >-
        For image models, only Google/Gemini image models are supported; use
        other image endpoints for other models. HaiRoute API key. Use this
        header or Authorization: Bearer YOUR_API_KEY (not both).
      parameters:
        - name: model
          in: path
          required: true
          description: An available Google/Gemini image model in HaiRoute
          schema:
            type: string
          example: YOUR_GEMINI_IMAGE_MODEL
        - name: x-goog-api-key
          in: header
          required: true
          description: >-
            HaiRoute API key for the native request. Alternatively, use
            Authorization: Bearer YOUR_API_KEY instead (choose one).
          schema:
            type: string
          example: YOUR_API_KEY
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateRequest'
            example:
              contents:
                - role: user
                  parts:
                    - text: Draw an orange cat
              generationConfig:
                responseModalities:
                  - TEXT
                  - IMAGE
                imageConfig:
                  aspectRatio: '1:1'
                  imageSize: 1K
      responses:
        '200':
          description: >-
            SSE data stream: each data frame contains a Gemini
            GenerateContentResponse JSON chunk; no named events or [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-style error response.
          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: >-
            Required native Gemini messages. Use a user text part for
            text-to-image; add inlineData for image-to-image.
        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-style error response.
    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: >-
        Native Gemini generation settings; availability depends on the image
        model.
      properties:
        responseModalities:
          type: array
          items:
            type: string
            enum:
              - TEXT
              - IMAGE
          example:
            - TEXT
            - IMAGE
          description: Use ["TEXT", "IMAGE"] for image output; text may also be returned.
        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: Text or image content parts.
    ImageConfig:
      type: object
      description: >-
        Image aspect ratio and output size tier; supported values depend on the
        model.
      properties:
        aspectRatio:
          type: string
          example: '1:1'
        imageSize:
          type: string
          example: 1K
      additionalProperties: true
    InlineData:
      type: object
      description: Image MIME type and raw Base64 data without a data URI prefix.
      properties:
        mimeType:
          type: string
          example: image/png
        data:
          type: string
          format: byte
          example: <BASE64_IMAGE_DATA>
      required:
        - mimeType
        - data

````