
Nano Banana 2.1: Product Shots With Edit Chains in Python
Summary
Half-price image gen: build a hero-plus-variants pipeline with a budget guard.
Google shipped Nano Banana 2.1 on October 6, 2026, and the number that got developers talking is the price: image output dropped to $30 per million tokens, which works out to about $0.034 for a 1K image, half what Nano Banana 2 (Gemini 3.1 Flash Image) charged. The older model also shows up on Google's deprecation schedule with an earliest possible shutdown of October 29, so a lot of teams have three weeks to move.
This guide builds something concrete with it: a small product-shot pipeline. You generate one hero image, then derive every colorway and every translated-label variant from it with edit chains (each edit references the previous interaction instead of re-describing the scene). You will also add a hard budget guard, so a loop bug cannot quietly burn money.
Everything here uses the new Interactions API (client.interactions.create) as documented on ai.google.dev. If you have older code on generate_content with image_config, the migration notes near the end cover what changes.
Prerequisites
- Python 3.10+ and the
google-genaiSDK (pip install -U google-genai). - A Gemini API key on a paid tier, exported as
GEMINI_API_KEY. No free-tier access is listed for this model. - Rough budget: under $0.50 for everything below.
What is actually new in 2.1
Per the model page, gemini-nano-banana-2.1 takes text, image, video and PDF input and returns image and text. Input limit is 131,072 tokens, output 32,768. It supports 1K, 2K and 4K output, up to 14 reference images (character consistency for up to 4 characters, object fidelity for up to 10 objects), Google Search grounding including image search, the Batch API, and thinking levels minimal, medium (default) and high. Google also says it fixed tiling artifacts on extreme aspect ratios like 1:8 and 8:1 at 2K and 4K, and improved text rendering and infographic layout.
What it does not support matters just as much for design: no function calling, no structured outputs, no caching, no code execution, no URL context, and no Live API. Do not plan an agent that tool-calls through this model; call it as a service from your own code, as we do below.
| Size | Standard / image | Batch / image |
|---|---|---|
| 1K | $0.0336 | $0.0168 |
| 2K | $0.0504 | $0.0252 |
| 4K | $0.113 | $0.0567 |
Text input costs $1.50 per million tokens and text/thinking output $7.50 per million. Thinking tokens are billed by default, so high thinking costs a little more than the table suggests.
Step 1: Your first image
The Interactions API returns the image base64-encoded on interaction.output_image.data. Output options go in response_format, and the size string must use an uppercase K.
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-nano-banana-2.1",
input="Studio photo of a matte-black 350ml coffee tumbler on a walnut desk, "
"soft window light. The label reads 'KODA COLD BREW'.",
response_format={"type": "image", "mime_type": "image/png",
"aspect_ratio": "4:5", "image_size": "2K"},
)
with open("hero.png", "wb") as f:
f.write(base64.b64decode(interaction.output_image.data))
print(interaction.id)
Expected output: a file hero.png and an interaction id string printed to the terminal. Keep that id. It is what makes edit chains work.
Step 2: Edit chains with previous_interaction_id
The cheapest and most consistent way to produce variants is to continue the conversation. Pass previous_interaction_id and describe only the change. The model keeps the scene, lighting and framing from the earlier turn.
second = client.interactions.create(
model="gemini-nano-banana-2.1",
input="Change only the product color to forest green. Keep the lighting, "
"camera angle, background and every label exactly as they are.",
previous_interaction_id=interaction.id,
response_format={"type": "image", "mime_type": "image/png",
"aspect_ratio": "4:5", "image_size": "1K"},
)
Note the phrasing. Edits that say what to keep drift far less than edits that only say what to change. The keep-unchanged clause is the main consistency lever, and the docs' own multi-turn example uses the same pattern (translate text, keep everything else unchanged).
Two cost tricks follow from this. First, render the hero at 2K and the variants at 1K, since variants are usually thumbnails or catalog tiles. Second, if you need dozens of variants overnight, move them to the Batch API at half price.
Step 3: The full pipeline with a budget guard
Here is the whole thing in one file. It generates a hero, chains colorway and translation edits off it, retries transient errors with backoff, and refuses to make a call if the next one would cross your budget. The budget check happens before the request, so a runaway loop stops at the cap rather than after it.
"""Product-shot pipeline on Nano Banana 2.1 (Interactions API)."""
import base64, json, pathlib, time
from google import genai
MODEL = "gemini-nano-banana-2.1"
# Paid-tier price per output image, USD (Oct 2026 pricing page)
PRICE = {"1K": 0.0336, "2K": 0.0504, "4K": 0.113}
BATCH_PRICE = {"1K": 0.0168, "2K": 0.0252, "4K": 0.0567}
client = genai.Client() # reads GEMINI_API_KEY
class Budget:
def __init__(self, limit_usd):
self.limit, self.spent = limit_usd, 0.0
def charge(self, size):
cost = PRICE[size]
if self.spent + cost > self.limit:
raise RuntimeError(f"budget exceeded: {self.spent:.3f} + {cost:.3f} > {self.limit}")
self.spent += cost
def save(interaction, path):
data = interaction.output_image.data # base64 string
pathlib.Path(path).write_bytes(base64.b64decode(data))
return path
def generate(prompt, budget, size="1K", aspect="1:1", thinking="medium",
refs=(), previous=None, retries=3):
if size not in PRICE:
raise ValueError("size must be 1K, 2K or 4K (uppercase K)")
parts = [{"type": "text", "text": prompt}]
for p in refs:
parts.append({"type": "image",
"data": base64.b64encode(pathlib.Path(p).read_bytes()).decode(),
"mime_type": "image/png"})
kwargs = dict(
model=MODEL,
input=parts if refs else prompt,
response_format={"type": "image", "mime_type": "image/png",
"aspect_ratio": aspect, "image_size": size},
generation_config={"thinking_level": thinking},
)
if previous is not None:
kwargs["previous_interaction_id"] = previous.id
for attempt in range(retries):
try:
budget.charge(size)
return client.interactions.create(**kwargs)
except RuntimeError:
raise
except Exception as e:
if attempt == retries - 1:
raise
time.sleep(2 ** attempt)
def run(brief, out_dir="shots"):
out = pathlib.Path(out_dir); out.mkdir(exist_ok=True)
budget = Budget(brief.get("budget_usd", 1.00))
hero = generate(brief["hero_prompt"], budget, size="2K", aspect="4:5", thinking="high")
save(hero, out / "hero.png")
log = {"hero": "hero.png"}
for color in brief["colorways"]:
edit = generate(
f"Change only the product color to {color}. Keep the lighting, "
"camera angle, background and every label exactly as they are.",
budget, size="1K", aspect="4:5", previous=hero)
save(edit, out / f"hero_{color.replace(' ', '_')}.png")
log[color] = "ok"
for lang in brief["languages"]:
loc = generate(
f"Translate the text on the packaging to {lang}. Keep everything else unchanged.",
budget, size="1K", aspect="4:5", previous=hero)
save(loc, out / f"hero_{lang}.png")
log[lang] = "ok"
log["spent_usd"] = round(budget.spent, 4)
(out / "log.json").write_text(json.dumps(log, indent=2))
return log
if __name__ == "__main__":
print(run({
"hero_prompt": ("Studio photo of a matte-black 350ml coffee tumbler on a "
"walnut desk, soft window light. The label reads 'KODA COLD BREW'."),
"colorways": ["forest green", "sand"],
"languages": ["Spanish", "Japanese"],
"budget_usd": 0.50,
}))
I ran this file against a stub client to check the control flow, the chaining and the budget guard (the stub is not the real service, so image quality is something you will judge yourself). With a real key, the run looks like this:
$ python pipeline.py
{'hero': 'hero.png', 'forest green': 'ok', 'sand': 'ok', 'Spanish': 'ok', 'Japanese': 'ok', 'spent_usd': 0.1848}
$ ls shots
hero.png hero_forest_green.png hero_sand.png hero_Spanish.png hero_Japanese.png log.json
The spend figure is computed from the published price table: one 2K hero ($0.0504) plus four 1K edits ($0.0336 each) is $0.1848. Check your Google AI Studio billing page to confirm actual charges, since thinking tokens add a little.
Step 4: Reference images for brand consistency
When the hero must match an existing product, pass photos in the input array, one entry per image. The model accepts up to 14 in total.
from pipeline import generate, Budget, save
b = Budget(0.25)
shot = generate(
"Place this exact tumbler on a marble kitchen counter at golden hour. "
"Do not change the logo or the lid.",
b, size="2K", aspect="16:9",
refs=["tumbler_front.png", "tumbler_side.png"])
save(shot, "kitchen.png")
Give it two or three angles of the same object rather than one. With a single angle the model has to invent the back of the product.
Step 5: Ground it with search when facts matter
For infographics or anything that depicts a real thing, enable the search tool. Nano Banana 2.1 supports both web and image search grounding.
infographic = client.interactions.create(
model="gemini-nano-banana-2.1",
input="Infographic: how a pour-over coffee extraction curve works",
tools=[{"type": "google_search", "search_types": ["web_search", "image_search"]}],
)
Grounding has its own meter: 5,000 free requests per month shared across Gemini 3.x models, then $14 per 1,000. Only turn it on for prompts that need real-world facts.
Migrating from Nano Banana 2 before October 29
- Model id: swap
gemini-3.1-flash-imageforgemini-nano-banana-2.1. - API style: the current docs use
client.interactions.createwithresponse_format. The oldergenerate_contentdocs, withimage_configandresponse_modalities, are now labeled legacy. - Sizes: the 512px option exists only on Gemini 3.1 Flash Image. If you relied on it, 1K is your new floor on 2.1.
- A/B before you cut over: run 50 of your real prompts through both models and compare text rendering and logo fidelity side by side. Google itself says to test against your own workloads.
- Dropped parameters: on the enterprise platform, seed, topK, logprobs, temperature and topP are not supported, so deterministic regeneration is not available there.
Common pitfalls
- Lowercase k.
"2k"fails; the docs require"2K". The pipeline validates this before spending anything. - Wrong file extension. If you request
image/jpeg, name the file.jpg. Even Google's own samples write a PNG-named file for a JPEG request. - Multi-image output.
output_imagereturns only the last image. For interleaved text and images, iterateinteraction.stepsand read each content block of typeimage. - Describing the whole scene in every edit. It invites drift. Chain from the previous interaction and describe only the delta plus what to keep.
- Small text. Google lists poor rendering of small text, hallucinations and imperfect character consistency as known limits. Put important copy in large type and check every output.
- Expecting tool calls. No function calling or structured outputs. Parse your own prompts upstream.
- Budget leaks. Retries multiply cost. Charge the budget on every attempt, as the pipeline does.
- Provenance. Outputs carry SynthID, and Google says the model supports Content Credentials (C2PA). Do not strip metadata if you publish.
Quick reference
| Need | How |
|---|---|
| Model id | gemini-nano-banana-2.1 |
| Call | client.interactions.create(...) |
| Read image | base64.b64decode(interaction.output_image.data) |
| Size / ratio | response_format={'type':'image','aspect_ratio':'4:5','image_size':'2K'} |
| Edit chain | previous_interaction_id=prev.id |
| Reference images | {'type':'image','data':b64,'mime_type':'image/png'} in input, up to 14 |
| Thinking | generation_config={'thinking_level':'minimal|medium|high'} |
| Search grounding | tools=[{'type':'google_search','search_types':['web_search','image_search']}] |
| Cheapest bulk | Batch API, $0.0168 per 1K image |
Next steps
- Add a QA pass: send each output back to a Gemini text model and ask whether the label text matches the expected string, then regenerate only failures.
- Move the colorway and language loops to the Batch API for half-price overnight runs.
- Add a 4K export step for only the winning hero, so you pay $0.113 once instead of per variant.
- Log the interaction id for every asset so an art director can resume a chain weeks later.
Sources: Gemini Nano Banana 2.1 model page, Gemini API image generation docs, Unite.AI pricing coverage, RuntimeWire on the deprecation schedule.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,605 newsletter subscribers.