Gemini Native
使用 Google Gen AI SDK 或 HTTP 调用 🍌 Nano Banana,处理多模态输入和图片返回。
从这里切换协议
pip install google-genaiimport jsonfrom google import genaifrom google.genai import typesapi_key = "YOUR_API_KEY"api_base = "https://api.1route.dev"payload = { "contents": [ { "role": "user", "parts": [ { "text": "Editorial portrait of a woman in profile beside a wind-bent tree, late afternoon light, deep cobalt coat, pale concrete wall, subtle film grain, restrained color palette, clean composition, vertical 4:5." } ] } ], "generationConfig": { "responseModalities": [ "TEXT", "IMAGE" ], "imageConfig": { "imageSize": "1K", "aspectRatio": "1:1" }, "responseFormat": { "image": { "delivery": "INLINE" } } }}client = genai.Client( api_key=api_key, http_options=types.HttpOptions(base_url=api_base, api_version="v1beta", timeout=1500000),)response = client.models.generate_content( model="gemini-3.1-flash-image", contents=payload["contents"], config=types.GenerateContentConfig( http_options=types.HttpOptions(extra_body=payload), ),)result = response.model_dump(mode="json", by_alias=True, exclude_none=True)print(json.dumps(result, ensure_ascii=False, indent=2))生成图片
https://api.1route.dev/v1beta/models/{model}:generateContenthttps://api.1route.dev频繁超时可改用 https://image-api.1route.dev模型名放在路径里:gemini-3.1-flash-image 是 🍌 Nano Banana 2,gemini-3-pro-image 是 🍌 Nano Banana Pro。请求体为 JSON,认证使用 x-goog-api-key: YOUR_API_KEY 或 Authorization: Bearer YOUR_API_KEY。
{
"contents": [{
"role": "user",
"parts": [{ "text": "为咖啡店设计一张春季菜单海报,标题为 SPRING MENU" }]
}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": {
"imageSize": "2K",
"aspectRatio": "3:4"
}
}
}请求结构
请求
├─ contents[] 按顺序排列的对话
│ ├─ role user 或 model
│ └─ parts[] 这一轮的内容
│ ├─ text 文字提示词
│ ├─ inlineData 本地图片的 Base64
│ └─ fileData 图片 URL
└─ generationConfig 生成选项
├─ responseModalities 返回文字、图片或两者
└─ imageConfig 图片尺寸与比例
├─ imageSize 1K、2K、4K
└─ aspectRatio 例如 1:1、3:4、16:9contents 是对话列表,parts 是一轮对话里的内容列表。一条 part 表达一种内容,文字和多张图片可以放在同一轮。图片生成使用 IMAGE,需要同时返回解释文字时加入 TEXT。不要把整段响应当成单张图片。
imageSize 使用大写档位;不指定尺寸与比例时由模型处理。🍌 Nano Banana 2 / Pro 常用 1K、2K、4K,常用比例包括 1:1、2:3、3:2、3:4、4:3、4:5、5:4、9:16、16:9、21:9。
Google 官方 Python SDK
安装 google-genai。base_url 使用服务根地址,不加 /v1;版本单独设为 v1beta。下面保存响应中的图片,并输出文字部分。
from google import genai
from google.genai import types
from pathlib import Path
client = genai.Client(
api_key="YOUR_API_KEY",
http_options=types.HttpOptions(
base_url="https://api.1route.dev",
api_version="v1beta",
timeout=1500000,
),
)
response = client.models.generate_content(
model="gemini-3.1-flash-image",
contents="为咖啡店设计一张春季菜单海报,标题为 SPRING MENU",
config=types.GenerateContentConfig(
response_modalities=["TEXT", "IMAGE"],
image_config=types.ImageConfig(image_size="2K", aspect_ratio="3:4"),
),
)
for index, part in enumerate(response.candidates[0].content.parts):
if part.text:
print(part.text)
elif part.inline_data:
Path(f"output-{index}.png").write_bytes(part.inline_data.data)SDK 的 inline_data.data 已是字节,不要再次 Base64 解码。原始 HTTP JSON 的 inlineData.data 才是 Base64 字符串。JavaScript SDK 使用 @google/genai;工作台还提供 httpx、requests 和 fetch。
添加参考图
仍调用 generateContent,没有单独的 edits 路径。把提示词和图片一起放进 contents[].parts。
本地文件
{
"contents": [{
"role": "user",
"parts": [
{ "text": "保留人物的面部特征,把外套换成深绿色" },
{
"inlineData": {
"mimeType": "image/png",
"data": "<不带 Data URL 前缀的 Base64>"
}
}
]
}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": { "imageSize": "1K", "aspectRatio": "3:4" }
}
}mimeType 应与文件一致,例如 image/png、image/jpeg、image/webp。使用 SDK 时可直接从字节创建 part:
reference = types.Part.from_bytes(
data=Path("portrait.png").read_bytes(),
mime_type="image/png",
)
response = client.models.generate_content(
model="gemini-3-pro-image",
contents=["保留人物的面部特征,把外套换成深绿色", reference],
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"]),
)图片 URL
将图片 part 换成 fileData。使用可以直接下载图片的 URL,声明 MIME 类型:
{
"fileData": {
"mimeType": "image/jpeg",
"fileUri": "https://your-image-host.example/portrait.jpg"
}
}多个 fileData / inlineData part 可以混用,顺序会保留。服务端下载 URL 后提交图片;单张媒体上限为 80 MiB,请求体上限为 512 MiB,模型本身的输入限制仍适用。
图片返回方式
默认以 inlineData 返回图片。想拿到可直接显示的图片 URL,可以设置本站的交付扩展:
{
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": { "imageSize": "2K", "aspectRatio": "16:9" },
"responseFormat": {
"image": { "delivery": "URI" }
}
}
}delivery: "INLINE" 返回 Base64;delivery: "URI" 返回 fileData.fileUri。URL 保留 72 小时,过期返回 410 result_expired。媒体地址支持 GET / HEAD,长期使用请下载。
新旧尺寸字段
服务同时接受上面的 imageConfig 简写,以及 responseFormat.image 枚举形式:
{
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"responseFormat": {
"image": {
"imageSize": "IMAGE_SIZE_TWO_K",
"aspectRatio": "ASPECT_RATIO_SIXTEEN_BY_NINE",
"delivery": "URI"
}
}
}
}1K / 2K / 4K 分别映射到 IMAGE_SIZE_ONE_K / IMAGE_SIZE_TWO_K / IMAGE_SIZE_FOUR_K。两种结构同时指定同一字段时,responseFormat.image 优先。不要在这里使用 OpenAI 的 size 或 response_format。
SDK 尚未覆盖的服务扩展通过 http_options.extra_body 发送:
response = client.models.generate_content(
model="gemini-3.1-flash-image",
contents=payload["contents"],
config=types.GenerateContentConfig(
http_options=types.HttpOptions(extra_body=payload),
),
)这里的 payload 是完整 JSON 请求,与工作台的“请求”视图一致。
解析响应
{
"candidates": [{
"index": 0,
"content": {
"role": "model",
"parts": [
{ "text": "已将外套换成深绿色。" },
{ "inlineData": { "mimeType": "image/png", "data": "<图片数据>" } }
]
},
"finishReason": "STOP"
}],
"usageMetadata": {
"promptTokenCount": 120,
"candidatesTokenCount": 1120,
"totalTokenCount": 1240
},
"modelVersion": "gemini-3.1-flash-image"
}逐项读取 candidates[].content.parts[]。text 是文字,inlineData 是图片字节的 Base64;URI 模式将图片 part 换为 fileData,文字仍保留。用 mimeType 选择文件扩展名。响应还可能含 responseId、safetyRatings、finishMessage 等信息。
usageMetadata 中,promptTokenCount 为输入 token,candidatesTokenCount 为输出 token,totalTokenCount 为总用量;存在思考用量时还可能包含 thoughtsTokenCount。这些是 token 统计,不是费用或图片张数。
结束状态与空结果
finishReason: "STOP" 表示这一候选正常结束;仍需从 parts 中读取实际图片。常见的其他状态:
| 状态 | 含义 |
|---|---|
MAX_TOKENS | 达到输出 token 限制 |
SAFETY / IMAGE_SAFETY | 文字或图片被安全策略阻止 |
PROHIBITED_CONTENT / IMAGE_PROHIBITED_CONTENT | 命中禁止内容 |
RECITATION / IMAGE_RECITATION | 内容复现限制 |
NO_IMAGE | 未生成图片 |
IMAGE_OTHER / OTHER | 其他原因,读取 finishMessage |
没有候选时,查看 promptFeedback.blockReason 和 promptFeedback.safetyRatings。有候选但没有图片时,检查文字回复、finishReason 和 finishMessage。HTTP 200 本身不能代表生成了图片。
多轮编辑
保留上一轮完整的 model content,再追加新的 user content。thoughtSignature 等字段属于模型返回的上下文,保持原样。
history = [
types.Content(role="user", parts=[types.Part(text="生成一张咖啡店海报")]),
response.candidates[0].content,
types.Content(role="user", parts=[types.Part(text="保留布局,把标题改成 SUMMER MENU")]),
]
response = client.models.generate_content(
model="gemini-3.1-flash-image",
contents=history,
config=types.GenerateContentConfig(response_modalities=["TEXT", "IMAGE"]),
)实际使用时,history 的第一轮应对应生成 response 的原始请求。后续每轮继续追加 model / user content。若只需要独立编辑一张已有图片,直接使用参考图请求即可。
更多生成选项
可按模型能力添加原生顶层 systemInstruction、safetySettings、tools,以及 generationConfig 内的 temperature、topP、maxOutputTokens、thinkingConfig。例如:
{
"systemInstruction": {
"parts": [{ "text": "为同一个品牌制作图片,保留提供的标识与品牌色。" }]
},
"contents": [{
"role": "user",
"parts": [{ "text": "设计一张春季促销海报" }]
}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": { "imageSize": "2K", "aspectRatio": "3:4" },
"temperature": 0.7
}
}systemInstruction 设定整体要求;temperature / topP 控制采样;maxOutputTokens 限制输出 token,不是图片像素。safetySettings 按内容类别配置审核阈值,tools 依赖模型支持。批量图片使用独立请求,不把 candidateCount 当作通用生图张数开关。
流式请求与错误
流式路径为 POST /v1beta/models/{model}:streamGenerateContent?alt=sse,请求体与非流式相同。每个 SSE data 是一个响应片段,按顺序处理其中的候选、文字和图片。它没有 Studio 的 queued / running 任务状态。
非流式支持 Idempotency-Key;同一个幂等值只能对应相同请求。冲突返回 409,流式携带此头返回 400。已存结果保留 72 小时。
{
"error": {
"code": 400,
"status": "INVALID_ARGUMENT",
"message": "delivery must be INLINE or URI"
}
}HTTP 400 检查结构、枚举和 MIME;401 检查 Key;413 减小请求;429 检查额度与并发;500 / 502 / 504 读取具体错误。流开始后的错误放在 SSE JSON 的 error 中。频繁超时可手动改用备用地址。


