> ## 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 图像生成

> Gemini 原生接口生成图片：14 种比例、1K/2K/4K 清晰度、思考档位，均经过生产 API 验证。

Nano Banana 2.1 是谷歌的图片模型，模型 ID 为 `gemini-nano-banana-2.1`。便利店按 **Gemini 原生接口**提供：`POST https://code.heihuzi.ai/v1beta/models/gemini-nano-banana-2.1:generateContent`。验证日期：**2026-10-08**。

旧模型 ID `gemini-3.1-flash-image` 仍可调用，会自动转到 Nano Banana 2.1：实测用旧 ID 请求，响应里的 `modelVersion` 为 `gemini-nano-banana-2.1`，按 2.1 计费。新接入请直接使用 `gemini-nano-banana-2.1`。

请使用绑定「Nano Banana 2.1 画图」分组的 API Key。这个分组不支持 OpenAI Images 接口：用 `/v1/images/generations` 请求本模型实测返回 404（`Images API is not supported for this platform`），请按本页使用原生接口。

```bash theme={null}
curl --fail-with-body --silent --show-error --max-time 600 \
  --request POST \
  --url https://code.heihuzi.ai/v1beta/models/gemini-nano-banana-2.1:generateContent \
  --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": "16:9", "imageSize": "1K"}
  }
}' \
  --output generation.json
```

请求把完整响应保存到 `generation.json`。运行前设置环境变量 `HEIHUZI_API_KEY`。鉴权头 `x-goog-api-key` 与 `Authorization: Bearer <Key>` 均已验证可用。

响应中的图片是 base64 编码的 JPEG。下面的命令从 `generation.json` 取出图片，保存为 `generation.jpg`：

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

payload = json.load(open("generation.json"))
parts = payload["candidates"][0]["content"]["parts"]
image = next(p["inlineData"] for p in parts if "inlineData" in p and not p.get("thought"))
open("generation.jpg", "wb").write(base64.b64decode(image["data"]))
print("Saved generation.jpg")
EOF
```

## 请求参数

**contents** `object[]` *required*

对话内容。生成图片时放一条 `role: "user"` 消息，`parts` 里写提示词。缺少 `contents` 实测返回 400。带参考图的写法见[图像编辑](https://docs.heihuzi.ai/cn/api-reference/images/nano-banana-2/edits.md)。

**contents 字段**

**role** `string`

本页使用 `user`。

**parts** `object[]`

消息内容。本页使用一个 `{"text": "提示词"}`。

**generationConfig** `object`

生成设置。比例和清晰度写在 `generationConfig.imageConfig` 里，思考档位写在 `generationConfig.thinkingConfig` 里。

**generationConfig 字段**

**responseModalities** `string[]`

本页使用 `["IMAGE"]`。`["TEXT", "IMAGE"]` 也已验证，本次只返回了图片、没有文字。

**imageConfig** `object`

图片设置，只有下面两个字段，与谷歌官方接口说明一致。

**imageConfig 字段**

**aspectRatio** `string`

画面比例。谷歌官方列出的 14 种均已验证：`1:1`、`2:3`、`3:2`、`3:4`、`4:3`、`4:5`、`5:4`、`9:16`、`16:9`、`21:9`、`1:4`、`4:1`、`1:8`、`8:1`，实际尺寸见下表。不支持的比例（如 `5:3`）返回 400。

谷歌官方说明：不填时由模型决定比例，有参考图时参照参考图。本次不带参考图、完全不传 `imageConfig` 实测返回 1376×768（16:9），图片用量与 1K 相同；需要固定比例时请填写。

**imageSize** `string`

清晰度。可选 `1K`、`2K`、`4K`，均已验证。请使用大写 `K`，这是谷歌官方要求的写法。不支持 `512`（0.5K）：实测返回 400（`Image size 512 is not supported for this model`）。其他不支持的值（如 `8K`）同样返回 400。

**thinkingConfig** `object`

思考设置。生成图片前模型会先“思考”，思考产生的 token 按用量计费。

**thinkingConfig 字段**

**thinkingLevel** `string`

思考档位。可选 `minimal`、`medium`、`high`，均已验证；`low` 返回 400（`Thinking level LOW is not supported for this model`）。

本次实测：填 `minimal` 时，所有请求的 `usageMetadata` 里都没有 `thoughtsTokenCount`（不产生思考 token）；填 `medium`、`high` 或不填时都会思考，`thoughtsTokenCount` 在 153～884 之间，每次请求差别较大。只想控制用量时填 `minimal`。

## 已验证的比例与尺寸

每行都是一次真实的生产请求：请求结构与上方示例相同，`imageSize` 为 `1K`、`thinkingLevel` 为 `minimal`，只改 `aspectRatio`。返回图片均为 JPEG，尺寸为解码后的实际像素。

| `aspectRatio` | `1K` 实际尺寸 |
| - | - |
| `1:1` | 1024×1024 |
| `2:3` | 848×1264 |
| `3:2` | 1264×848 |
| `3:4` | 896×1200 |
| `4:3` | 1200×896 |
| `4:5` | 928×1152 |
| `5:4` | 1152×928 |
| `9:16` | 768×1376 |
| `16:9` | 1376×768 |
| `21:9` | 1584×672 |
| `1:4` | 512×2064 |
| `4:1` | 2064×512 |
| `1:8` | 352×2928 |
| `8:1` | 2928×352 |

`1:4`、`4:1`、`1:8`、`8:1` 的实际像素与谷歌文档的尺寸表略有出入，表中为实测值。

更高清晰度已验证：`16:9` + `2K` 返回 2752×1536；`9:16` + `4K` 返回 3072×5504。单张图片一次请求，生成 1K 实测约 10–20 秒（个别请求 30–41 秒），2K 约 18 秒，4K 约 31 秒；偶尔会慢很多，请把客户端超时设为 10 分钟以上。以上是实测耗时，不是响应时间承诺。

## 真实响应节选

下面是上方示例（`16:9`、`1K`、不填思考档位）一次真实响应的节选：图片和 `thoughtSignature` 的长内容已省略，`responseId`、`turnToken` 等字段未列出；token 数和签名大小每次请求都不同。

```json theme={null}
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "inlineData": {
              "mimeType": "image/jpeg",
              "data": "<此处省略真实图片的 base64>"
            },
            "thoughtSignature": "<此处省略，约 1.4 MB>"
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 11,
    "candidatesTokenCount": 1313,
    "totalTokenCount": 1804,
    "promptTokensDetails": [{"modality": "TEXT", "tokenCount": 11}],
    "candidatesTokensDetails": [{"modality": "IMAGE", "tokenCount": 1120}],
    "thoughtsTokenCount": 480
  },
  "modelVersion": "gemini-nano-banana-2.1"
}
```

* 图片在 `candidates[].content.parts[].inlineData`：`mimeType` 本次均为 `image/jpeg`，`data` 是 base64。保存图片时跳过带 `"thought": true` 的部分（模型思考过程中的草图）。本次测试的响应里没有出现这类部分，示例保留跳过逻辑以防上游返回。
* `thoughtSignature` 是模型的思考签名，单次生成用不到，可以忽略。它和图片一起返回，所以响应体较大：1K 实测约 1.5～2.4 MB（`1:8`、`8:1` 实测 3.1 MB、5.4 MB），2K 约 5.8 MB，4K 约 18 MB，14 张参考图约 7 MB；请按 20 MB 以上预留内存，并设置足够的超时。
* `usageMetadata.candidatesTokensDetails` 里 `IMAGE` 的 token 数，本次 1K 为 1120、2K 为 1680、4K 为 3780。`thoughtsTokenCount` 是思考 token 数，填 `thinkingLevel: "minimal"` 时不出现。

费用以便利店当前分组配置和用量明细为准：图片按张计费，提示词、参考图和思考、文字输出按用量计费。

## 错误响应

出错时 HTTP 状态码不是 2xx，响应体是 JSON，都带 `error.message`（错误说明）。其余字段因出错环节不同而不同：有的 `code` 是数字、有的是字符串，有的带 `status`、有的带 `type`。判断成败请看 HTTP 状态码，向用户展示原因请读 `error.message`。下表为 2026-10-08 实测：

| 情况 | HTTP | `error.message`（节选） | 其他字段 |
| - | - | - | - |
| `aspectRatio: "5:3"` | 400 | `aspect_ratio must be one of '1:1', … or '21:9'.` | `type: "upstream_error"`、`code: 400` |
| `imageSize: "512"` | 400 | `Image size 512 is not supported for this model` | `type: "upstream_error"`、`code: 400` |
| `imageSize: "8K"` | 400 | `Unsupported image_size '8K'. Supported values are: …` | `type: "upstream_error"`、`code: 400` |
| `thinkingLevel: "low"` | 400 | `Thinking level LOW is not supported for this model. …` | `type: "upstream_error"`、`code: 400` |
| 缺少 `contents` | 400 | `contents is required (request id: …)` | `type: "new_api_error"`、`code: "invalid_request"` |
| 不带 Key | 401 | `API key is required` | `code: 401`、`status: "UNAUTHENTICATED"` |
| 本分组没有的模型（如 `gemini-2.5-pro`） | 404 | `Model "gemini-2.5-pro" is not supported by any configured account in this group` | `code: 404`、`status: "NOT_FOUND"` |

`aspectRatio: "5:3"` 的完整响应体：

```json theme={null}
{
  "error": {
    "message": "* GenerateContentRequest.generation_config.image_config.aspect_ratio: aspect_ratio must be one of '1:1', '1:4', '1:8', '2:3', '3:2', '3:4', '4:1', '4:3', '4:5', '5:4', '8:1', '9:16', '16:9', or '21:9'.\n",
    "type": "upstream_error",
    "param": "",
    "code": 400
  }
}
```

## Python 生成并保存图片

这段完整代码已用 `requests==2.32.5` 真实执行，返回并保存一张 1376×768 JPEG 到 `generated-1.jpg`。

```python theme={null}
import base64
import os
from pathlib import Path

import requests

response = requests.post(
    "https://code.heihuzi.ai/v1beta/models/gemini-nano-banana-2.1:generateContent",
    headers={"x-goog-api-key": os.environ["HEIHUZI_API_KEY"]},
    json={
        "contents": [
            {"role": "user", "parts": [{"text": "A simple blue ceramic cup on a white background."}]}
        ],
        "generationConfig": {
            "responseModalities": ["IMAGE"],
            "imageConfig": {"aspectRatio": "16:9", "imageSize": "1K"},
        },
    },
    timeout=(15, 600),
)
response.raise_for_status()
payload = response.json()
images = [
    part["inlineData"]
    for candidate in payload.get("candidates", [])
    for part in candidate.get("content", {}).get("parts", [])
    if "inlineData" in part and not part.get("thought")
]
if not images:
    raise RuntimeError(payload.get("error", "No image returned"))
for index, image in enumerate(images, 1):
    Path(f"generated-{index}.jpg").write_bytes(base64.b64decode(image["data"]))
print("Saved", len(images), "image(s)")
```

## 使用 Google GenAI SDK

谷歌官方 Python SDK 只需把地址改为便利店，并填便利店 Key。官方工具包从 `google-genai` 1.49.0 起才有 `image_size` 参数，`1.47.0` 实测会报错。这段代码已用 `google-genai==2.28.0`（需要 Python 3.10 及以上）真实执行，保存一张 2752×1536 JPEG 到 `nano-banana-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),
)
response = client.models.generate_content(
    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="16:9", image_size="2K"),
    ),
)
saved = 0
for part in response.candidates[0].content.parts:
    if part.inline_data and not part.thought:
        saved += 1
        with open(f"nano-banana-{saved}.jpg", "wb") as file:
            file.write(part.inline_data.data)
if saved == 0:
    raise RuntimeError("No image returned")
print("Saved", saved, "image(s)")
```

`HttpOptions` 的 `timeout` 单位是毫秒。SDK 会自动使用 `x-goog-api-key` 鉴权并请求 `/v1beta/models/...:generateContent`。

成功处理应检查 HTTP 状态、响应是否含 `error`，并确认 `parts` 里有可解码的图片。错误响应的格式见上方[错误响应](#错误响应)。


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