Google’s Nano Banana Pro model — officially Gemini 3 Pro Image — has become the model developers reach for when a chat-app image generator isn’t enough and they need programmatic control: batch generation, multi-image compositing, or an app that renders images on demand. Since its November 2025 rollout to developers and enterprises across the Gemini API, Google AI Studio, Antigravity, and Vertex AI, Google has pitched it as its premium image model for complex visual tasks — built around deeper world knowledge, localization, brand consistency, and creative control rather than raw speed — and by May 2026 Google Cloud pushed that positioning further, making Nano Banana Pro generally available inside the Gemini Enterprise Agent Platform. But the API is a different animal from the consumer app. You need a Google AI Studio account, billing enabled, an SDK, and a working understanding of a pricing model that bills per output resolution rather than per generation. This tutorial walks through setting up the Nano Banana Pro API from a blank terminal to a working multi-model image generation pipeline that also calls GPT Image, FLUX.2, Recraft, and Ideogram so you can compare cost and quality side by side.
By the end, you’ll have a working Python CLI that generates images through five different providers, handles async polling and rate limits, and logs cost per image — the kind of tool you’d actually keep around after the tutorial is over.
Don't miss new tech stories on Google
Add Tech Insider once in the Google app and our stories appear in your news suggestions.
What Is the Nano Banana Pro API, and Why It’s Different From the App
Nano Banana Pro is the developer-facing name that stuck after Google shipped Gemini 3 Pro Image, a reasoning-driven image model that can follow multi-step compositing instructions, keep text legible inside generated graphics, and accept multiple reference images in a single call. Google officially rolled the model out to developers and enterprises across the Gemini API, Google AI Studio, Antigravity, and Vertex AI on November 20, 2025, and third-party platforms moved just as fast — fal.ai lists it as a hosted endpoint (fal-ai/nano-banana-pro) dating to that same launch. The consumer version lives inside the Gemini app and Google AI Studio’s playground. The Nano Banana Pro API is the same model exposed through the Gemini API and Vertex AI, billed per request rather than folded into a subscription.
Google actually ships three tiers under the Nano Banana family — the lineup grew in February 2026 when Google added Nano Banana 2 (gemini-3.1-flash-image), giving developers preview access through the Gemini API, Gemini CLI, and Vertex API, as TechCrunch reported at the time — and picking the wrong one is the single most common cost mistake developers make:
- Nano Banana 2 Lite (model ID
gemini-3.1-flash-lite-image) — cheapest tier, best for thumbnails, drafts, and high-volume low-stakes generation. - Nano Banana 2 (model ID
gemini-3.1-flash-image) — mid-tier, faster than Pro, good default for most app features. - Nano Banana Pro (model ID
gemini-3-pro-image) — the reasoning-heavy flagship, best for complex multi-image composition, legible in-image text, and print-quality 4K output.
As of August 2026, Google’s Standard API tier has no free image-output allowance for any of the three models — every call bills against your project’s billing account from the first image. Google’s own AI Studio documentation lists Nano Banana with a 65,536-token context window, 1K/2K/4K output options, and 10 configurable settings covering things like resolution and aspect ratio, and that 65,536-token ceiling is what maps internally to the 4K resolution cap across all three tiers. That’s a change worth planning around if you’re used to prototyping on free tiers.
Prerequisites: Accounts, Tools, and Versions You’ll Need
Gather these before you start. Nothing here is optional — skipping the billing step is the most common reason the first API call fails.
- A Google account with access to Google AI Studio and a linked Google Cloud billing account.
- Python 3.10+ (or Node.js 20 LTS+, if you prefer JavaScript) installed locally.
- The
google-genaiPython package, Google’s current unified SDK for Gemini (installed via pip; always pull the latest version rather than pinning an old one, since the SDK ships frequent updates alongside new model releases). - An OpenAI API key if you want to run the GPT Image comparison steps (optional but recommended).
- API keys for any of FLUX.2 (via Black Forest Labs or fal.ai), Recraft, or Ideogram if you want the full five-model comparison pipeline.
- A terminal and a code editor. VS Code, Cursor, or plain vim all work fine — nothing in this tutorial depends on a specific editor.
- Roughly $5–$10 in API credit to run through every example in this tutorial without worrying about cost.
You do not need a GPU, a local model download, or Docker for this tutorial — everything here calls hosted APIs. If you’d rather run image generation locally instead of through a paid API, see our guide on running FLUX locally in ComfyUI.
Step 1: Create a Google AI Studio Account and Generate an API Key
Sign in to Google AI Studio with any Google account. From the dashboard, open the API keys panel and create a new key scoped to a Google Cloud project. If you don’t already have a Cloud project, AI Studio will create one for you automatically — but you still need to attach a billing account before the Nano Banana Pro API will accept requests, since the Standard tier has no free image quota.
Copy the generated key somewhere safe. Never commit it to a repository — store it as an environment variable instead:
export GEMINI_API_KEY="your-key-here"
export OPENAI_API_KEY="your-openai-key-here" # only needed for the GPT Image comparison steps
If you’re deploying to a shared environment later, use a secrets manager rather than plain environment variables — see our walkthrough on setting up AWS Secrets Manager for a pattern that transfers directly to this project.
Step 2: Understand Nano Banana Pro’s Token-Based Pricing
This is the step most tutorials skip, and it’s the one that determines whether your monthly bill is $12 or $120 per million image-output tokens. The Nano Banana Pro API doesn’t bill per “image” in the way you’d expect — it bills per output resolution, which maps to a token count internally and translates to about $0.134 per 1K/2K image and $0.24 per 4K image. Independent pricing trackers like Evolink AI were already confirming those exact figures back in January 2026, and Dev.to’s June 2026 report on the model reaching general availability logged the same $0.134/$0.24 split, so the rate has held steady for months rather than drifting. On the Standard processing tier as of August 2026:
- 1K or 2K resolution output: $0.134 per image
- 4K resolution output: $0.24 per image
Google also runs Batch and Flex lanes at roughly 50% off Standard pricing — $0.067 per 1K/2K image and $0.12 per 4K image on Batch/Flex.067 for 1K/2K and $0.12 for 4K — intended for jobs that don’t need synchronous, real-time responses. If your app generates images in response to a background job rather than a live user request, routing through Batch instead of Standard cuts your image bill in half with zero code changes beyond the endpoint you call.
For comparison, the lighter Nano Banana 2 and Nano Banana 2 Lite tiers cost meaningfully less per call — which is why picking the right model tier for each feature in your app, rather than defaulting to Pro everywhere, is the fastest lever you have for controlling spend.
Step 3: Install and Configure the google-genai SDK
Install Google’s unified SDK. It replaced the older, model-specific client libraries and now covers both the Gemini Developer API and Vertex AI through the same interface:
pip install -U google-genai
# Node.js equivalent
npm install @google/genai@latest
Verify the install worked and your key is recognized:
from google import genai
client = genai.Client(api_key="your-key-here") # or reads GEMINI_API_KEY automatically
print("Client initialized:", client is not None)
If this raises an authentication error, double check that billing is actually attached to the project the key belongs to — an invalid key and an unbilled project throw nearly identical error messages, which is a common source of confusion for first-time users.
Step 4: Generate Your First AI Image
With the client configured, generating an image is a single call to generate_content against the gemini-3-pro-image model:
from google import genai
from google.genai import types
client = genai.Client() # reads GEMINI_API_KEY from environment
response = client.models.generate_content(
model="gemini-3-pro-image",
contents="A minimalist product shot of a matte ceramic coffee mug on a "
"concrete surface, soft studio lighting, shallow depth of field",
)
for part in response.candidates[0].content.parts:
if part.inline_data:
with open("mug.png", "wb") as f:
f.write(part.inline_data.data)
print("Saved mug.png")
Run it, and within a few seconds you’ll have a PNG on disk. That single call, at default 1K/2K resolution, costs $0.134 against your billing account. It’s worth generating one deliberately wasteful test image early just to see the charge appear in your Cloud billing console — it makes the pricing model concrete in a way the docs alone don’t.
Step 5: Control Resolution, Aspect Ratio, and Multi-Image Input
Nano Banana Pro accepts generation config for resolution and aspect ratio, and — unlike most competing APIs — it can take multiple reference images as input to a single generation call, which is what makes it useful for compositing and product-photo style workflows:
response = client.models.generate_content(
model="gemini-3-pro-image",
contents=[
"Combine these two reference images into one photo: place the product "
"from image 1 on the table surface from image 2, matching the lighting.",
types.Part.from_bytes(data=open("product.png", "rb").read(), mime_type="image/png"),
types.Part.from_bytes(data=open("table.png", "rb").read(), mime_type="image/png"),
],
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(aspect_ratio="16:9"),
),
)
Bumping the resolution to 4K roughly doubles your per-image cost (from $0.134 to $0.24 on Standard), so reserve 4K output for cases where the extra resolution actually matters — hero images, print assets, anything a user will zoom into. Thumbnails and previews should stay at 1K/2K, or drop to Nano Banana 2 Lite entirely.
Step 6: Edit, Composite, and Iterate on Generated Images
What sets Nano Banana Pro apart from a straight text-to-image model is that editing is a first-class operation, not a separate inpainting endpoint bolted on afterward. You pass the previous output back in as an input image along with a follow-up instruction:
edit_response = client.models.generate_content(
model="gemini-3-pro-image",
contents=[
"Change the background to a warm sunset gradient, keep the mug identical.",
types.Part.from_bytes(data=open("mug.png", "rb").read(), mime_type="image/png"),
],
config=types.GenerateContentConfig(response_modalities=["IMAGE"]),
)
This iterate-in-place pattern is what makes Nano Banana Pro a good fit for design tools and product-catalog pipelines, where you’re refining one asset across several passes rather than generating a fresh image every time. Every edit call bills the same as a fresh generation, though, so a five-pass refinement loop on a 4K image adds up fast — batch your edit instructions into fewer, more specific prompts where you can.
Step 7: Add GPT Image as a Second Model for Comparison
No single image model wins every use case, so a production pipeline is usually multi-model. OpenAI’s current image lineup gives you a straightforward second provider to add: GPT Image 1.5 is the flagship as of August 2026, with the older GPT Image 1 and the budget-oriented GPT Image 1 Mini also still available for lower-cost drafts. Wire it in with the standard openai package:
pip install -U openai
from openai import OpenAI
openai_client = OpenAI() # reads OPENAI_API_KEY from environment
gpt_response = openai_client.images.generate(
model="gpt-image-1.5",
prompt="A minimalist product shot of a matte ceramic coffee mug on a "
"concrete surface, soft studio lighting, shallow depth of field",
size="1024x1024",
quality="high",
)
import base64
image_bytes = base64.b64decode(gpt_response.data[0].b64_json)
with open("mug_gpt.png", "wb") as f:
f.write(image_bytes)
At high quality and 1024×1024, GPT Image 1.5 runs $0.133 per image — nearly identical to Nano Banana Pro’s Standard 1K/2K price of $0.134. That closeness is exactly why side-by-side testing matters more than pricing sheets: at near-equal cost, the deciding factor becomes which model actually nails your specific prompt style. If you already use GPT models for text generation, see our comparison of Claude Opus vs GPT-5.5 vs Gemini 3.5 Flash for how the same providers stack up on the text side.
Step 8: Add FLUX.2, Recraft, and Ideogram via Direct or Aggregator APIs
Rounding out the pipeline with three more models gives you real coverage across styles and price points. Each of these ships its own SDK or REST API; the fastest path for a comparison tool is calling their REST endpoints directly with requests, since you don’t need every feature of each provider’s full SDK for a side-by-side test:
import requests, os
def generate_flux(prompt: str) -> bytes:
resp = requests.post(
"https://api.bfl.ai/v1/flux-2-pro",
headers={"x-key": os.environ["BFL_API_KEY"]},
json={"prompt": prompt, "width": 1024, "height": 1024},
timeout=60,
)
resp.raise_for_status()
return resp.json()
def generate_recraft(prompt: str) -> bytes:
resp = requests.post(
"https://external.api.recraft.ai/v1/images/generations",
headers={"Authorization": f"Bearer {os.environ['RECRAFT_API_KEY']}"},
json={"prompt": prompt, "style": "realistic_image", "model": "recraftv4"},
timeout=60,
)
resp.raise_for_status()
return resp.json()
FLUX.2 [pro], via Black Forest Labs directly or through fal.ai, runs about $0.030 per image — the cheapest of the flagship-tier models in this lineup. Recraft’s V4/V4.1 raster generation sits at $0.035–$0.04 per image, with vector output at $0.08 and a Pro tier reaching $0.21–$0.30 for higher-fidelity raster and vector work respectively. Ideogram 4.0 splits into Turbo ($0.03), Default ($0.06), and Quality ($0.10) tiers — Ideogram is also the strongest of this group specifically at rendering legible text inside images, which matters if your use case involves posters, packaging mockups, or UI screenshots.
Midjourney is conspicuously absent from direct API integration here — its API access remains enterprise-only with pricing that isn’t publicly disclosed, so most independent developers won’t have a self-serve path onto it the way they do with the other four providers.
Step 9: Build an Async Job Queue With Polling and Backoff
Nano Banana Pro and GPT Image both return images synchronously in the response body, but several providers — FLUX among them, depending on the endpoint — return a job ID first and require you to poll for the result. Mixing sync and async providers in one pipeline without normalizing the interface is a common source of bugs, so wrap every provider in the same async-style function even if some of them resolve instantly:
import time
def poll_until_ready(job_id: str, fetch_status_fn, max_wait_seconds: int = 90) -> dict:
waited = 0
backoff = 1.5
while waited < max_wait_seconds:
status = fetch_status_fn(job_id)
if status["state"] in ("completed", "succeeded"):
return status
if status["state"] in ("failed", "error"):
raise RuntimeError(f"Job {job_id} failed: {status.get('error')}")
time.sleep(backoff)
waited += backoff
backoff = min(backoff * 1.5, 8) # exponential backoff, capped at 8s
raise TimeoutError(f"Job {job_id} did not complete within {max_wait_seconds}s")
Poll too aggressively (sub-second intervals) and you'll burn through rate limits without speeding anything up — the job isn't done any faster because you asked more often. Starting at a 1.5-second interval with exponential backoff, capped around 8 seconds, is a reasonable default that keeps your request volume sane on any provider's free or early-tier rate limits.
Step 10: Handle Content Moderation Rejections and SynthID Watermarks
Every provider in this pipeline runs a safety filter in front of generation, and every one of them will occasionally reject a completely benign prompt — historical clothing references, medical illustration requests, and anything involving real public figures are common false-positive triggers. Build a specific exception path for moderation rejections rather than letting them fall through as generic errors:
class ContentModerationError(Exception):
pass
def generate_with_moderation_handling(prompt: str):
try:
return client.models.generate_content(model="gemini-3-pro-image", contents=prompt)
except Exception as e:
if "safety" in str(e).lower() or "blocked" in str(e).lower():
raise ContentModerationError(f"Prompt rejected by safety filter: {prompt[:80]}")
raise
Separately: every image Nano Banana Pro generates is embedded with an invisible SynthID watermark, Google's imperceptible provenance marker. It survives common edits like cropping and recompression, and it doesn't affect image quality — but if your app strips or re-encodes images in a pipeline step, verify you're not accidentally stripping metadata you actually want to keep for provenance tracking.
Step 11: Cut Costs With Batch and Flex Pricing Tiers
If your pipeline generates images for a queue rather than in direct response to a live user request — nightly catalog refreshes, pre-generating variant sets, anything that can tolerate a delay — route those calls through Batch or Flex processing instead of Standard. The discount is real and immediate: 1K/2K drops from $0.134 to $0.067, and 4K drops from $0.24 to $0.12, roughly halving your bill for the exact same output with no quality tradeoff.
A simple router that sends live-request traffic to Standard and everything else to Batch pays for itself almost immediately in any pipeline generating more than a handful of images a day:
def route_generation(prompt: str, is_live_request: bool):
processing_tier = "standard" if is_live_request else "batch"
return client.models.generate_content(
model="gemini-3-pro-image",
contents=prompt,
config=types.GenerateContentConfig(
image_config=types.ImageConfig(processing_tier=processing_tier),
),
)
Step 12: Deploy Your Pipeline to Production
Wrap the pipeline in a small FastAPI service and deploy it somewhere that scales to zero, since image generation traffic tends to be bursty rather than constant. Google Cloud Run is the natural fit if you're already on the Gemini API, but the same container runs fine on any serverless platform:
# Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
If you haven't deployed a containerized service to Cloud Run before, our Google Cloud Run setup guide covers the deployment steps in detail — everything there applies directly to this image generation service. Store all five provider API keys as Cloud Run secrets rather than plain environment variables once you're past local development.
Real-World Use Cases for a Multi-Model Image Pipeline
The pattern this tutorial builds shows up in a handful of recurring shapes once teams start using it in production. E-commerce catalogs are the most common: a product photography pipeline that takes a raw studio shot and generates a dozen variants — different backgrounds, different crops, different lifestyle contexts — without booking another photo shoot. Nano Banana Pro's multi-image compositing is a natural fit here, since it can place a product image against a new background while preserving the product's exact shape and color, which matters far more for a retailer than for a general creative-generation use case.
Marketing and social teams use a similar pipeline for a different reason: volume and speed of iteration. A single campaign might need the same core visual resized and restyled for a dozen ad placements and three brand variants. Routing that batch work through Batch or Flex pricing rather than Standard is exactly the kind of case where the 50% discount matters — the images don't need to appear instantly, they need to exist by tomorrow morning.
App developers building AI-native products — mood boards, avatar generators, design tools — tend to land on a hybrid setup: Nano Banana 2 Lite or Imagen 4 Fast for live, in-app previews where latency and cost per request matter most, and Nano Banana Pro or GPT Image 1.5 reserved for a "generate final version" button the user presses once they've settled on a direction. That two-tier structure keeps the bulk of traffic cheap while still offering flagship quality where it counts.
Ideogram earns its place in a pipeline specifically when a use case involves text inside the image itself — posters, packaging mockups, meme templates, UI screenshots for marketing pages — since legible in-image text remains a weak point for several other models even at flagship tiers.
Security Best Practices When Calling Multiple Image Generation APIs
A pipeline that authenticates against five different providers is a pipeline with five different ways to leak a credential, so treat key management as a first-class part of the build rather than an afterthought. Keep every provider key in a secrets manager rather than a .env file once code leaves your laptop — a compromised API key for an image generation service is a direct line to your billing account, and unlike a leaked read-only token, there's no way to limit the blast radius after the fact beyond revoking the key immediately.
Scope keys as narrowly as each provider allows. Google Cloud lets you restrict an API key to specific APIs and, optionally, specific IP ranges or HTTP referrers — apply that restriction even in early development, since it costs nothing and closes off an entire class of accidental exposure if a key ends up in a public repository or a client-side bundle by mistake. Never call these APIs directly from client-side JavaScript in a browser; every request should route through your own backend, both to keep keys server-side and to enforce your own rate limiting and cost caps before a request ever reaches the provider.
Finally, set billing alerts on every provider account before you deploy anything to production. A bug that generates images in a retry loop — a genuinely common failure mode when error handling is incomplete — can turn a $10 testing budget into a four-figure bill within hours if nothing is watching. Google Cloud, OpenAI, and most of the smaller providers all support budget alerts that email or page you well before a runaway loop becomes an expensive lesson.
Nano Banana Pro vs GPT Image vs FLUX vs Recraft vs Ideogram: Pricing and Feature Table
Here's how the five models this tutorial integrates actually compare on cost, as of August 2026:
| Model | Provider | Price per Image (Standard) | Strongest Use Case | Async or Sync |
|---|---|---|---|---|
| Nano Banana Pro (Gemini 3 Pro Image) | $0.134 (1K/2K), $0.24 (4K) | Multi-image compositing, iterative edits | Sync | |
| GPT Image 1.5 (high quality) | OpenAI | $0.133 (1024×1024) | Complex scene composition | Sync |
| GPT Image 1 Mini (high quality) | OpenAI | $0.036 (1024×1024) | Low-cost drafts and previews | Sync |
| FLUX.2 [pro] | Black Forest Labs / fal.ai | $0.030 | Cheapest flagship-tier output | Async (varies by route) |
| Recraft V4.1 (raster) | Recraft | $0.035 | Design systems, brand assets | Sync |
| Recraft V3 (vector) | Recraft | $0.08 | Vector/SVG output | Sync |
| Ideogram 4.0 Turbo | Ideogram | $0.03 | Legible in-image text | Sync |
| Imagen 4 Fast | $0.02 (1K) | High-volume, speed-first, lower quality tolerance | Sync |
The takeaway: at flagship quality, Nano Banana Pro and GPT Image 1.5 are priced within a fraction of a cent of each other, so cost alone won't decide which one to standardize on. FLUX.2 and Ideogram's Turbo tier undercut both meaningfully if raw price per image is your primary constraint, and Imagen 4 Fast is the cheapest option here by a wide margin if you can tolerate lower fidelity for high-volume use cases like thumbnail generation.
Nano Banana Model Tiers: Which One to Use When
| Model Tier | Model ID | Best For | Relative Cost |
|---|---|---|---|
| Nano Banana 2 Lite | gemini-3.1-flash-lite-image | Thumbnails, drafts, high-volume low-stakes generation | Lowest |
| Nano Banana 2 | gemini-3.1-flash-image | General app features, faster turnaround than Pro | Mid |
| Nano Banana Pro | gemini-3-pro-image | Multi-image compositing, legible text, 4K/print assets | Highest |
SDK and Package Reference
Quick reference for the package names used throughout this tutorial. Always install the latest published version rather than pinning to a specific number — every one of these providers ships frequent updates alongside model releases, and pinning an old version is a common source of confusing errors when a model ID from this tutorial isn't recognized by an outdated client.
| Provider | Python Package | Node.js Package | Install Command |
|---|---|---|---|
| Google Gemini (Nano Banana Pro) | google-genai | @google/genai | pip install -U google-genai |
| OpenAI (GPT Image) | openai | openai | pip install -U openai |
| Black Forest Labs (FLUX) | requests (REST) | fetch/axios (REST) | No dedicated SDK required |
| fal.ai (aggregator) | fal-client / fal | @fal-ai/client | pip install fal-client |
| Replicate (aggregator) | replicate | replicate | pip install replicate |
Common Pitfalls When Integrating AI Image Generator APIs
These are the mistakes that show up repeatedly in production image pipelines, roughly in order of how expensive they are to leave unfixed:
- Defaulting every call to the Pro tier. Using Nano Banana Pro for a thumbnail that Nano Banana 2 Lite would handle just as well quietly multiplies your bill for no visible benefit to the user.
- Ignoring the Standard vs Batch/Flex split. Any background job routed through Standard pricing when it could tolerate Batch's latency is leaving roughly half your image spend on the table.
- Treating every provider as synchronous. Some FLUX endpoints and several aggregator routes return a job ID, not an image. Code that assumes a synchronous response will silently fail or hang on those providers.
- Polling too aggressively. Sub-second polling loops burn rate limit headroom without making a job finish any faster — use exponential backoff, not a tight loop.
- No fallback when a moderation filter rejects a prompt. A single rejected prompt shouldn't crash a batch job; catch the moderation exception specifically and either retry with a rephrased prompt or skip and log it.
- Forgetting the 4K cost multiplier. Jumping from 1K/2K to 4K roughly doubles Nano Banana Pro's per-image price — fine for a hero image, wasteful for anything a user won't zoom into.
- Hardcoding aspect ratios and resolutions. Different providers accept different size formats (some take width/height pairs, others take named aspect ratios) — normalize this in your own wrapper rather than special-casing every call site.
- Not tracking cost per provider in logs. Once you're calling five APIs with different pricing models, you need per-call cost logging from day one, or you'll have no idea which provider is driving your bill until the invoice arrives.
Troubleshooting: Common Errors and Fixes
Here are the errors you're most likely to hit while building this pipeline, and what actually fixes each one:
- "API key not valid" despite a correct key. Usually means billing isn't attached to the project the key belongs to — the Standard tier rejects image requests from unbilled projects with an error that looks identical to a bad key.
- Image generation returns text instead of image data. Check that
response_modalitiesis explicitly set to["IMAGE"]in your generation config — without it, some prompts can return a text-only response describing what it would generate instead of generating it. - Multi-image compositing ignores the second reference image. Make sure both
Part.from_bytesobjects are included in the samecontentslist as the instruction text, in the order you reference them in the prompt. - Rate limit errors (HTTP 429) under moderate load. Add exponential backoff with jitter, and check your project's quota tier in the Cloud console — new billing accounts often start on a lower default quota than established ones.
- FLUX job stuck in "processing" indefinitely. Set a hard timeout (60–90 seconds is reasonable) and treat expiry as a retryable failure rather than waiting forever — occasional stuck jobs happen on any provider's queue.
- Recraft or Ideogram returns a 401 despite a valid-looking key. Confirm you're using the API key generated from each provider's developer dashboard specifically — not a key or token generated for their web app, which uses a separate auth scheme.
- Generated images look washed out or lower quality than the playground. Double check the
qualityparameter (OpenAI) or resolution tier (Gemini) — default values in raw API calls are sometimes lower than the playground's UI defaults. - Costs don't match your estimate at month end. Almost always traced back to Standard-tier calls that should have been routed to Batch, or a 4K default left in code that was only meant to run at 1K during testing.
Advanced Tips for Scaling an AI Image Pipeline
Once the basic pipeline works, a few refinements make a real difference at production volume. First, cache aggressively on prompt hash — if your app regenerates the same or near-identical prompt repeatedly (common in e-commerce catalog tools), a cache keyed on a normalized prompt hash plus model ID avoids paying for duplicate generations entirely.
Second, consider aggregator platforms like fal.ai and Replicate for the non-Google models in your pipeline. Rather than managing five separate API keys, rate limits, and billing relationships, an aggregator normalizes the interface and consolidates billing — at the cost of an extra hop and, usually, a small markup over calling providers directly. That markup isn't universal, though: a June 2026 partner API review clocked Kie.ai reselling Nano Banana Pro access at around $0.12 per image, roughly 20% under Google's official Standard rate, and by February 2026 the reseller NanoBananaPro.site was advertising generations from as little as $0.008 per image across 1K–4K resolutions — discounts steep enough that they're worth stress-testing for reliability and support before routing production traffic through them. For a pipeline calling more than two or three third-party models, the aggregator trade is often worth it purely for the reduction in integration surface area.
Third, build an automatic fallback chain: if Nano Banana Pro's safety filter rejects a prompt, retry against GPT Image or FLUX before surfacing an error to the user. Different providers train their moderation filters differently, so a prompt rejected by one frequently succeeds on another without any change to the wording.
Finally, if your app is already built around orchestrating multiple LLM providers, the same routing patterns apply directly to image generation. Our guide on setting up OpenRouter covers unified multi-provider routing for text models — the underlying problem of picking the right model for the right request at the right price is identical for images.
Complete Working Project: The Multi-Model Image CLI
Here's the full pipeline assembled into one runnable script. Save it as generate.py, install the dependencies, and set your API keys as environment variables before running it:
#!/usr/bin/env python3
"""Multi-model AI image generator CLI: compares cost and output across
Nano Banana Pro, GPT Image, and Ideogram for a single prompt."""
import os
import sys
import base64
import requests
from google import genai
from google.genai import types
from openai import OpenAI
PROVIDER_COSTS = {
"nano_banana_pro": 0.134,
"gpt_image_1_5": 0.133,
"ideogram_turbo": 0.03,
}
def generate_nano_banana(prompt: str, out_path: str) -> float:
client = genai.Client()
response = client.models.generate_content(
model="gemini-3-pro-image",
contents=prompt,
config=types.GenerateContentConfig(response_modalities=["IMAGE"]),
)
for part in response.candidates[0].content.parts:
if part.inline_data:
with open(out_path, "wb") as f:
f.write(part.inline_data.data)
return PROVIDER_COSTS["nano_banana_pro"]
def generate_gpt_image(prompt: str, out_path: str) -> float:
client = OpenAI()
response = client.images.generate(
model="gpt-image-1.5", prompt=prompt, size="1024x1024", quality="high",
)
image_bytes = base64.b64decode(response.data[0].b64_json)
with open(out_path, "wb") as f:
f.write(image_bytes)
return PROVIDER_COSTS["gpt_image_1_5"]
def generate_ideogram(prompt: str, out_path: str) -> float:
resp = requests.post(
"https://api.ideogram.ai/v1/ideogram-v3/generate",
headers={"Api-Key": os.environ["IDEOGRAM_API_KEY"]},
json={"prompt": prompt, "rendering_speed": "TURBO"},
timeout=60,
)
resp.raise_for_status()
image_url = resp.json()["data"][0]["url"]
img_bytes = requests.get(image_url, timeout=30).content
with open(out_path, "wb") as f:
f.write(img_bytes)
return PROVIDER_COSTS["ideogram_turbo"]
def main():
prompt = " ".join(sys.argv[1:]) or "A minimalist ceramic mug on concrete, studio lighting"
total_cost = 0.0
providers = [
("nano_banana.png", generate_nano_banana),
("gpt_image.png", generate_gpt_image),
("ideogram.png", generate_ideogram),
]
for out_path, fn in providers:
try:
cost = fn(prompt, out_path)
total_cost += cost
print(f"Generated {out_path} — ${cost:.3f}")
except Exception as e:
print(f"Skipped {out_path}: {e}")
print(f"Total run cost: ${total_cost:.3f}")
if __name__ == "__main__":
main()
Run it with python generate.py "your prompt here" and it'll produce three images plus a cost breakdown in your terminal. From here, extending it to FLUX and Recraft is a matter of adding two more functions following the same pattern — each one takes a prompt, returns a cost, and writes a file.
Output Example: What a Successful Run Looks Like
A working run of the CLI above against a well-formed prompt produces output like this:
$ python generate.py "A minimalist ceramic mug on concrete, studio lighting"
Generated nano_banana.png — $0.134
Generated gpt_image.png — $0.133
Generated ideogram.png — $0.030
Total run cost: $0.297
If a provider's key is missing or a request fails, the script logs the skip and keeps going rather than aborting the whole run — useful when you're testing incrementally and haven't set up every provider's key yet.
Frequently Asked Questions
Is there a free tier for the Nano Banana Pro API?
No. As of August 2026, Google's own AI Studio documentation confirms the Standard API tier has no free image-output allowance for Nano Banana Pro, Nano Banana 2, or Nano Banana 2 Lite — every call bills against your linked billing account starting from the first image, whether you reach the model through the Gemini API, Vertex AI, or the Gemini Enterprise Agent Platform, where Nano Banana Pro reached general availability in May 2026.
How much does the Nano Banana Pro API cost per image?
$0.134 per image at 1K or 2K resolution on the Standard tier, and $0.24 per image at 4K. Batch and Flex processing lanes cut both prices roughly in half, to $0.067 and $0.12 respectively.
What's the difference between Nano Banana Pro and the regular Nano Banana app?
The app is the consumer-facing product inside Gemini. The API — what this tutorial covers — is the same underlying Gemini 3 Pro Image model exposed for programmatic access through Google AI Studio and Vertex AI, billed per request instead of through a subscription.
Can I use the Nano Banana Pro API without a Google Cloud billing account?
No. Because there's no free tier for image output, you must attach a billing account to the Google Cloud project your API key belongs to before any generation request will succeed.
Which is cheaper for high-volume generation: Nano Banana Pro or FLUX.2?
FLUX.2 [pro], at roughly $0.030 per image, is cheaper than Nano Banana Pro's Standard-tier price of $0.134. If you route Nano Banana Pro traffic through Batch/Flex instead ($0.067), the gap narrows considerably, but FLUX.2 still comes out ahead on raw per-image cost.
Does Nano Banana Pro support editing existing images, not just generating new ones?
Yes. Pass a previously generated (or any reference) image back in as input alongside an editing instruction, and the model applies the change while preserving the rest of the image — this iterative editing is one of its core strengths over single-shot text-to-image models.
What is SynthID and does it affect image quality?
SynthID is Google's imperceptible digital watermark embedded in every image the model generates, used for provenance verification. It does not visibly alter the image and survives common edits like cropping or recompression.
Can I access Midjourney through a self-serve API the way I can with these other models?
Not currently. Midjourney's API access remains enterprise-only as of August 2026, with pricing not publicly disclosed, so it isn't included in the self-serve multi-model pipeline this tutorial builds.





