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

# Nano Banana 2.1 流式返回

> streamGenerateContent 的真实 SSE 观测：图片在一个事件里完整返回。

Nano Banana 2.1 支持 Gemini 原生流式接口：`POST https://code.heihuzi.ai/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent?alt=sse`，请求体与[图像生成](https://docs.heihuzi.ai/cn/api-reference/images/nano-banana-2/generation.md)相同。验证日期：**2026-10-08**。

## 真实观测

| 请求 | 鉴权头 | 事件数 | 收到图片 | 结果 |
| - | - | - | - | - |
| `1:1`、`1K` | `x-goog-api-key` | 1 | 约 15 秒 | 1024×1024 JPEG，`finishReason: STOP` |
| `16:9`、`2K` | `Authorization: Bearer` | 1 | 约 16 秒 | 2752×1536 JPEG，`finishReason: STOP` |

两次都只收到**一个事件**，里面同时包含完整图片、`finishReason` 和 `usageMetadata`；没有预览图或分段图片。流式的作用是在等待期间保持连接，不会更早拿到图片。上表是实测耗时记录，不是响应时间承诺。

## cURL 保存原始事件流

```bash theme={null}
curl --fail-with-body --silent --show-error --max-time 600 --no-buffer \
  --request POST \
  --url 'https://code.heihuzi.ai/v1beta/models/gemini-nano-banana-2.1:streamGenerateContent?alt=sse' \
  --header "x-goog-api-key: $HEIHUZI_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "A simple blue ceramic cup on a white background."}]
    }
  ],
  "generationConfig": {
    "responseModalities": ["IMAGE"],
    "imageConfig": {"aspectRatio": "1:1", "imageSize": "1K"}
  }
}' \
  --output stream.sse
```

完整事件流保存到 `stream.sse`。每个事件是一行 `data: {...}`，`{...}` 的结构与非流式响应相同，不能把整个文件当作一个 JSON 读取。

实测的事件流格式：`data: ` 后面是一整行 JSON，接着一个空行；换行符为 `\n`；没有 `[DONE]` 之类的结束标记，事件发完后连接结束。边收边解析时按标准 SSE 处理即可。图片在这一行里，1K 时这一行实测约 2 MB，2K 实测约 6 MB，逐行读取时不要设过小的单行长度上限。

请求参数有误时（例如比例写成 `5:3`），实测直接返回 HTTP 400：响应体是一段普通 JSON 错误（格式见[错误响应](https://docs.heihuzi.ai/cn/api-reference/images/nano-banana-2/generation.md#错误响应)），没有 `data:` 前缀，但 `Content-Type` 仍为 `text/event-stream`。请先判断 HTTP 状态码，只在 200 时按事件流解析。下面的命令取出其中的图片，保存为 `stream.jpg`：

```bash theme={null}
python3 - <<'EOF'
import base64
import json

saved = 0
for line in open("stream.sse"):
    if not line.startswith("data:"):
        continue
    event = json.loads(line[5:])
    for candidate in event.get("candidates", []):
        for part in candidate.get("content", {}).get("parts", []):
            if "inlineData" in part and not part.get("thought"):
                saved += 1
                open("stream.jpg", "wb").write(base64.b64decode(part["inlineData"]["data"]))
print("Saved", saved, "image(s)")
EOF
```

## Python SDK 流式保存图片

官方工具包从 `google-genai` 1.49.0 起才有 `image_size` 参数，`1.47.0` 实测会报错。这段代码已用 `google-genai==2.28.0`（需要 Python 3.10 及以上）真实执行，收到一个事件并保存 1024×1024 JPEG 到 `stream-1.jpg`。

```python theme={null}
import os

from google import genai
from google.genai import types

client = genai.Client(
    api_key=os.environ["HEIHUZI_API_KEY"],
    http_options=types.HttpOptions(base_url="https://code.heihuzi.ai", timeout=600_000),
)
saved = 0
for chunk in client.models.generate_content_stream(
    model="gemini-nano-banana-2.1",
    contents="A simple blue ceramic cup on a white background.",
    config=types.GenerateContentConfig(
        response_modalities=["IMAGE"],
        image_config=types.ImageConfig(aspect_ratio="1:1", image_size="1K"),
    ),
):
    for candidate in chunk.candidates or []:
        for part in candidate.content.parts or []:
            if part.inline_data and not part.thought:
                saved += 1
                with open(f"stream-{saved}.jpg", "wb") as file:
                    file.write(part.inline_data.data)
if saved == 0:
    raise RuntimeError("No image returned")
print("Saved", saved, "image(s)")
```

以收到可解码的图片为成功依据，不要假设一定会先收到预览。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.