09.3 Image Generation and Editing

Agents & multimodalLesson 3 of 1014,729 wordsOptional12 parts
Module 09 · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Text-to-image models have crossed from demo to infrastructure: as of November 2026 you can generate and edit production images through ordinary HTTPS APIs on every major provider, with per-image prices from a fraction of a cent to a few cents, editing that understands masks and reference photos, and provenance signals (invisible watermarks and signed metadata) built into the output. This lesson is the complete engineering reference for that surface: the provider landscape, every generation and editing parameter that matters, prompt craft for stills, the generate → validate → post-process → store pipeline, cost and latency arithmetic, and the safety, provenance and operational concerns that separate a prototype from a product.

What you'll learn

  • The image-generation landscape as of November 2026: OpenAI's GPT Image family (two APIs), Google's Nano Banana family (and why Imagen is gone), Anthropic's deliberate absence, OpenRouter's dedicated Image API, the specialist providers (Stability, Black Forest Labs, Ideogram, Recraft, Midjourney's missing API), and open models you can self-host
  • How image models actually work at the level an engineer needs (diffusion vs autoregressive vs editing-as-conditioning), and why the same prompt gives different images
  • Every request parameter on the providers that matter: size, aspect ratio, quality, format, background and transparency, n, seeds, masks, markup, reference images and multi-turn editing
  • Streaming partial images, async jobs with polling and webhooks, and batch generation
  • Prompting for images: prompt anatomy, text-in-image, negative constraints, prompt expansion with an LLM, consistency across a series, and a prompt gallery
  • The production pipeline: generate → validate with a vision model → post-process with Pillow → store with provenance metadata, all in code
  • Cost per image arithmetic (per-image vs per-token pricing), latency budgets, caching, storage and fallbacks
  • Safety, ethics and provenance: content policies and moderation errors, deepfakes and likeness, copyright, C2PA Content Credentials, SynthID watermarks, disclosure and abuse prevention

What you don't need

  • Any image-generation experience. Diffusion internals are covered at awareness level; you need the engineering surface, not the research.
  • API keys. Every part has something concrete you can do without one: pure-Python image handling that runs locally, a cost calculator, reading outputs you supply, and samples labelled illustrative that you can run later with a key.
  • How to send images to a model. That is lesson 03.6; this lesson generates them instead. When generated images go back into a VLM for validation, the mechanics are the same ones 03.6 teaches.

Setup

The samples need Python 3.11+ and a few packages. Lessons 03.1 to 03.9 share one project folder, llm-apis. If you haven't created it yet, run uv init llm-apis --bare --python 3.13 && cd llm-apis first (see lesson 03.1, Part 4), then add:

bash
uv add openai google-genai pillow httpx python-dotenv
# or: pip install openai google-genai pillow httpx python-dotenv

These samples were written and checked against openai 3.42.1, google-genai 2.34.0 and pillow 13.0.0 as of November 2026. A plain install gives you the newest release. Image-generation fields are new and move quickly, so if your SDK lacks a typed field the lesson uses, see the SDK version trap in 3.8 for the extra_body fallback.

The .env file holds the keys (never commit it):

bash
# .env
OPENAI_API_KEY=...
GEMINI_API_KEY=...   # optional
OPENROUTER_API_KEY=...   # optional gateway
# Optional, for the specialist-provider sketches in Part 6:
BFL_API_KEY=...
STABILITY_API_KEY=...
IDEOGRAM_API_KEY=...

What you must be able to do after this lesson#

  • Choose an image-generation provider and model for a task
  • Generate and edit an image through an API
  • Write an image prompt with clear anatomy and constraints
  • Build a pipeline that generates, validates and stores images
  • Estimate the cost per image

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Use gpt-image-2.5-flare for drafts and Sunburst for finals." 3.1 The two APIs
"Call the image generation tool inside Responses so the model can iterate." 3.4 Responses API: the image generation tool
"Nano Banana 2.1 is the workhorse; Pro is for brand work." 4.1 The Nano Banana family
"Imagen is shut down — don't write docs that mention it." 4.1 The Nano Banana family
"Claude can't make images, so we route generation to Gemini." 1.2 The providers, one by one
"OpenRouter has a real /images endpoint, not just chat completions." 5.1 The dedicated Image API
"Midjourney has no API — don't plan around it." 6.4 Midjourney and the rest
"It's $30 per million image output tokens, not per image." 10.1 Cost arithmetic
"Every partial image costs 100 extra tokens." 3.5 Streaming partial images
"The prompt got moderation_blocked — that's not a retryable 500." 11.1 Content policies and moderation errors
"C2PA credentials and SynthID are different signals." 11.4 Provenance: credentials and watermarks
"BFL gives you a polling_url, not a result." 6.2 Black Forest Labs
"Generate → validate → post-process → store is the pipeline." Part 9: The production pipeline

Part 1: The landscape as of November 2026#

Reference

1.1 Three families of image models#

Before the provider-by-provider tour, one mental model. Image models come in three architectural families, and the family determines what the API looks like:

Family How it makes an image Examples (Nov 2026) What the API feels like
Diffusion / flow models Start from noise, iteratively denoise toward the prompt OpenAI's GPT Image line is not this; FLUX (BFL), Stable Diffusion / Stable Image (Stability), Ideogram, Seedream, most specialist APIs A dedicated generate/edit endpoint; quality maps to compute steps and resolution
Autoregressive / multimodal LLMs An LLM that emits image tokens (or calls an image head) as part of a conversation Gemini Nano Banana models, OpenAI's Responses image_generation tool (a mainline LLM orchestrates an image model), xAI Grok Imagine Conversational: multi-turn editing, references in context, text and image in one response
Hybrid / dedicated editing models Same diffusion base, fine-tuned or wrapped for edits, inpainting, references FLUX.1 Kontext, Ideogram edit endpoints, gpt-image images/edits Edit endpoints with masks, markup or reference arrays

The practical consequence: Gemini's image models are chat models that happen to output images — they take video input, search grounding and multi-turn context for free. OpenAI splits the roles — a mainline model (gpt-6-astra, gpt-6.1-sol, …) can call an image model as a tool, or you call the image model directly through the Image API. Specialists are single-purpose endpoints — one job, one bill, usually async.

1.2 The providers, one by one#

Everything below was checked against official documentation on 5 November 2026. Model names and prices rot fast — the "how to check" notes matter more than the numbers.

OpenAI: the GPT Image family, two APIs

OpenAI's current image models are the GPT Image 2.x line. The newest are gpt-image-2.6-sunburst and gpt-image-2.6-flare (complexity control, SVG and animated-GIF output, markup-guided edits); the previous generation gpt-image-2.5-sunburst and gpt-image-2.5-flare remains fully supported and is what most of OpenAI's own examples use — including every Responses-API example in the docs. Sunburst is positioned for editing precision; Flare for fast everyday generation. Older entries still listed: gpt-image-2 (custom resolutions, no xhigh/max quality), gpt-image-1.5, gpt-image-1-mini, chatgpt-image-latest. Deprecation clock: gpt-image-1.5, gpt-image-1-mini and chatgpt-image-latest are deprecated and shut down on 1 December 2026 — under four weeks from this lesson's "as of November 2026" date — with the 2.6 pair as the announced replacement, so do not start new work on them. gpt-image-2 is on the deprecations list too, shutting down on 10 February 2027 with the same replacement. gpt-image-1 was shut down on 23 October 2026, and DALL·E 2/3 were retired on 12 May 2026 — do not write code against either.

Two ways to reach them:

  • Image API — POST /v1/images/generations and POST /v1/images/edits. One prompt in, one image (or n images) out. Best for single-shot generation and scripted edits.
  • Responses API image_generation tool — a mainline model decides when to generate or edit, can iterate across turns, sees the image in context, and returns revised_prompt plus base64 results. Best for conversational and agentic image workflows.

Both need an API Organization Verification completed in the developer console before GPT Image models will serve you — a real onboarding step, not a formality.

Google: the Nano Banana family (Imagen is gone)

Google's image generation lives inside the Gemini API as the Nano Banana family — multimodal models that take text, images, video and PDF in and emit images (and text) out:

Model API ID Positioning (per Google's docs)
Nano Banana 2.1 gemini-nano-banana-2.1 Current workhorse: Flash-level speed/cost, 1K/2K/4K, multi-turn consistency, Search grounding
Nano Banana 2 Lite gemini-3.1-flash-lite-image Fastest and cheapest; not for multi-reference or multi-turn editing
Nano Banana 2 gemini-3.1-flash-image Previous-generation workhorse; Google recommends 2.1 for new projects
Nano Banana Pro gemini-3-pro-image Premium: thinking, brand consistency, high-fidelity text, up to 14 references with style refs
Nano Banana (legacy) gemini-2.5-flash-image Deprecated; shutdown scheduled 15 March 2027 — migrate

Two verified facts worth repeating: every Gemini-generated image carries a SynthID watermark, and Imagen models are shut down in the Gemini API — Google's own docs now say "Use Nano Banana for all image generation tasks". If you find Imagen in older tutorials or Stack Overflow answers, it is stale.

The documented call path is the Interactions API (client.interactions.create) — it is the only path Google's current image-generation guide shows. The older generate_content path (response_modalities + image_config) no longer appears on that page, though the google-genai SDK still ships types.ImageConfig; Part 4 shows both and flags what to verify before relying on the older path.

Anthropic: no image generation — by design, so far

Anthropic's Claude models accept text and image input and return text output only. The vision documentation states Claude is an image understanding model and cannot generate, edit or create images; there is no image-generation endpoint, tool or modality flag (checked 5 November 2026). Claude can write SVG/HTML that renders as an image, which is code, not pixels. If your stack is Claude-centric, the pattern is: Claude orchestrates, a Gemini/OpenAI/specialist model renders. That split is normal — see the decision table in 12.5.

OpenRouter: a real Image API, not a chat trick

OpenRouter now has a dedicated Image API: POST /api/v1/images, plus GET /api/v1/images/models for discovery with per-endpoint capabilities and pricing. It fronts many vendors' image models — OpenAI's GPT Image line, Google's Nano Banana line, BFL's FLUX, ByteDance Seedream, Ideogram, Recraft, Sourceful, xAI's Grok Imagine and more (the catalogue is live; filter ?output_modalities=image on the models page). Part 5 covers it fully, including the normalized parameters (aspect_ratio, resolution, quality, size) that map onto each provider's dialect.

Awareness tier: xAI, Amazon, and the chat-completions route

  • xAI Grok Imagine generates and edits images (and video) through xAI's API; as of November 2026 it is also reachable through OpenRouter's Image API. Per-image pricing in the $0.02–$0.04 range per lesson 02.9's verified table — check xAI's pricing page.
  • Amazon Nova Canvas (image) and Nova Reel (video) run on Bedrock as async jobs — relevant if your org is AWS-native; outside this lesson's scope.
  • Chat-completions image output: some OpenRouter models return images inside ordinary chat completions (modalities: ["text","image"] style responses). That path is real but second-class — no normalized parameters, provider-specific event shapes. Prefer the Image API where the model is listed.

1.3 Specialist providers#

When you outgrow the generalists — typography, specific aesthetics, cost at volume, self-hosting — the specialists earn their place. All verified to exist and offer APIs as of November 2026; Part 6 has the request shapes.

Provider What it's known for API shape Pricing structure
Stability AI Stable Diffusion lineage; Stable Image Ultra flagship REST POST /v2beta/stable-image/generate/*, synchronous, multipart Credits (1 credit = $0.01); 2.5–8 credits/image by model ($0.025–$0.08); 25 free credits on signup
Black Forest Labs FLUX family; photorealism and editing (Kontext) POST /v1/<model> → polling_url or webhook; EU/US/global endpoints Credits; per-megapixel, scales with resolution
Ideogram Best-in-class text rendering inside images REST v2 POST /v2/image/generate/<model>; sync by default, async: true or an HTTPS webhook_url returns a generation_id to poll at GET /v2/generations/{generation_id} Prepaid balance (top-ups $10–$300 in the dashboard); per image/operation at the API pricing page
Recraft Raster and editable SVG output REST at external.api.recraft.ai/v1 (/images/generations), Bearer token, OpenAI-SDK compatible Per image: from about $0.007 (V4.1 Flash) to $0.04 raster and $0.08 vector (V3/V4), more for V4 Pro 2K
Midjourney Aesthetic quality No public API — web/Discord only; enterprise access by application Subscription, not per-image
fal, Replicate Aggregators hosting many open and licensed models Per-model endpoints, mostly async Per output/compute — varies wildly

1.4 Open models and self-hosting#

The open-weight image ecosystem (Stable Diffusion 3.5/SDXL lineage, FLUX.1 [dev]/[schnell] open variants, SD3.5, community fine-tunes, plus newer open releases) is served two ways:

  • Hugging Face diffusers — the standard Python library. You download weights (tens of GB), run DiffusionPipeline locally or on a GPU you rent. Awareness level: this path is about operating a model, not calling an API — VRAM requirements (roughly 8–24 GB for usable speeds on popular models, more for the largest), licence terms that differ per checkpoint (some are non-commercial), and the fact that you now own moderation, safety filtering and uptime.
  • Hosted open-model endpoints — BFL hosts FLUX.1 [dev] free for non-commercial use; Stability, fal and Replicate host SD3.5-class models; OpenRouter routes to several. This is usually the right middle ground: open-model pricing and terms without GPU ops.

The decision "API vs self-host" is the same one lesson 02.9 Part 5 works through for LLMs — for images the hardware bar is lower but the ops surface (GPU drivers, model format churn, safety filters you must implement yourself) is real. Link: 02.9, 5.7 Self-hosting.

1.5 The comparison table#

One row per route, qualitative only — no invented benchmark scores. "Text rendering" means legible words inside the image, historically the hardest trick in the field.

Route Text rendering Editing depth Consistency tools Typical latency Price structure Provenance built in
OpenAI GPT Image 2.5/2.6 Good and improving; still the #1 failure mode Deep: masks, markup, multi-image refs, multi-turn Character/style refs via edits + Responses context Seconds to ~2 min for complex prompts Per image/text/image token ($8 in / $30 out per MTok image tokens) C2PA + SynthID; Content Provenance API
Gemini Nano Banana 2.1/Pro Strong; NB Pro best for brand text Conversational multi-turn; up to 14 refs; video→image Best-in-class character/scene consistency Seconds Per image token by resolution ($30–$120 per MTok image output) SynthID on every image
Anthropic Claude n/a (no generation) n/a n/a n/a n/a n/a
OpenRouter Image API Depends on underlying model Whatever the model supports Whatever the model supports Varies by provider Per image / MP / token — see endpoint pricing Passes through provider's signals
Stability Stable Image Moderate Edits + inpainting endpoints LoRA/style presets, seeds Seconds Credits per image (~$0.025–$0.08) None documented
BFL FLUX.2/3 Good (FLUX.2 flex targets typography) Kontext editing, fill/inpaint References, seeds Async: seconds–minutes Credits per megapixel None documented
Ideogram 4.x Best in class Edit + magic-prompt variants Style refs, character refs Sync or async Per image None documented
Self-hosted open models Variable by checkpoint Depends on pipeline LoRA, ControlNet-style adapters GPU-bound Your GPU bill None — you implement it

Two honesty notes. First, "quality" columns are directional, not measured — run your own evals (Module 10A owns that discipline; a 20-image bake-off on your prompts beats any table). Second, content policies differ: OpenAI and Google run mandatory moderation on prompts and outputs; several specialist APIs leave moderation to you or offer it as an option. That is a feature or a liability depending on your product — Part 11 covers it.


Part 2: Concepts every image engineer needs#

2.1 How generation actually works (engineer's version)#

You don't need diffusion math, but three facts explain most API behaviour:

  1. Generation is iterative. Whether it's a diffusion model denoising step by step or an autoregressive model emitting image tokens, producing an image takes many compute steps. That's why latency is seconds-to-minutes, why quality costs more (more steps or bigger output), and why partial-image streaming exists — you can watch the denoising converge.
  2. The prompt is conditioning, not code. There is no grammar guaranteeing "three items" or "the logo in the corner". The model usually follows spatial and counting instructions, usually gets text roughly right, and occasionally hallucinates a sixth finger or garbles a word. Everything in Part 7 is about raising the odds.
  3. Editing is the same machinery with the image as extra input. A mask, a markup overlay, a reference photo, or the previous turn's image in context all work by conditioning the same generative process — which is why "edit" and "generate" blur into each other on conversational APIs, and why iterative editing can drift (each pass re-renders everything unless the model is careful).

2.2 Two ways to pay: per-image vs per-token#

This is the single most important pricing concept in the lesson:

  • Per-image / per-megapixel pricing (Stability, BFL, Ideogram, most specialists, OpenRouter endpoints that bill output_image): you know the price before the call. $0.04/image means 10,000 images = $400, full stop.
  • Per-token pricing (OpenAI GPT Image, Gemini Nano Banana): the image is billed as output tokens, and the token count depends on resolution tier and quality setting — and you only learn the exact count from usage after the call. OpenAI bills image input tokens too when you pass reference images to edits, and Responses-API calls additionally bill the orchestrating text model.

The trap: per-token pricing makes "same price per image" tables lie. Two requests at quality: "high" and different sizes can cost 3× apart; a quality: "low" draft might cost 10× less than max. Part 10 builds the calculator.

2.3 What the knobs actually do#

Every provider converges on the same knob set, with different names:

Concept OpenAI GPT Image Gemini Nano Banana OpenRouter (normalized) Specialist typical
Dimensions size: presets or WIDTHxHEIGHT image_size (0.5K–4K) + aspect_ratio size / resolution + aspect_ratio width+height or tier
Quality/compute quality: low→max + complexity implicit per model tier quality: auto/low/medium/high steps/guidance or tier
Format output_format: png/jpeg/webp/svg/gif PNG/JPEG bytes (mime_type in response_format) output_format: png/jpeg/webp/svg/gif png/jpeg/webp
Transparency background: "transparent" (png/webp) not documented background (alpha formats) varies
Count n (1–10) one per call n (1–10) one per call
Reproducibility none documented for API none documented seed where supported seed common
Safety moderation: auto/low platform policy provider-dependent provider-dependent

2.4 Latency expectations#

Set client timeouts accordingly — these are documented or typical figures, not SLAs:

  • OpenAI: the docs warn complex prompts "may take up to 2 minutes". Simple 1K images typically land in single-digit seconds; xhigh/max quality and 4K sizes push toward the minute range.
  • Gemini Nano Banana: positioned as the fast/cheap conversational option; seconds for 1K, longer for 4K and Pro.
  • Specialists: BFL-style async jobs are explicitly poll-or-webhook because generation can take tens of seconds; Stability's synchronous endpoints are quicker but still multi-second.
  • Partial-image streaming (OpenAI Responses, OpenRouter SSE) exists precisely because full latency is user-visible: show the rough image at second 2, refine to final at second 20.

Rule of thumb for UX: budget 5–30 s for interactive use, and design async (job + poll/webhook + notify) for anything batch or premium.


Part 3: OpenAI image generation#

3.1 Two APIs, one model family#

Image API Responses API (image_generation tool)
Endpoints POST /v1/images/generations, POST /v1/images/edits POST /v1/responses with tools=[{"type": "image_generation", ...}]
Who decides to draw You, explicitly A mainline model (gpt-5 and newer support the tool)
Multi-turn editing No — stateless per call Yes: image stays in context; action: "auto"/"generate"/"edit"
Input images Bytes / file upload / file_id / URL (edits) File IDs, URLs, base64 data URLs in conversation
Output data[].b64_json (+ optional URL/revised prompt fields per model) image_generation_call output items; revised_prompt visible
Streaming stream: true + partial_images response.image_generation_call.partial_image events
Best for Scripts, pipelines, cost-controlled batch Agents, chat products, iterative creative tools

OpenAI's own guidance: single prompt → Image API; conversational/editable experiences → Responses. You can also mix: a cheap mainline model orchestrates, a specific gpt-image-* model renders (the tool takes a model field).

3.2 Generate an image (Image API)#

python
# s3_2_openai_generate.py — needs OPENAI_API_KEY in .env
import base64
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

result = client.images.generate(
    model="gpt-image-2.5-flare",
    prompt=(
        "A children's book illustration of a veterinarian using a stethoscope "
        "to listen to the heartbeat of a baby otter, soft watercolor, "
        "warm cream background, no text"
    ),
    size="1024x1024",
    quality="medium",
    output_format="png",
    n=1,
    safety_identifier="user_8f2a1c",   # stable, non-identifying; replaces deprecated `user`
)

image_bytes = base64.b64decode(result.data[0].b64_json)
Path("otter.png").write_bytes(image_bytes)
print(f"saved {len(image_bytes)} bytes; revised_prompt={getattr(result, 'revised_prompt', None)!r}")
Example output · illustrative1 line
saved 1843203 bytes; revised_prompt=None

Notes that matter:

  • The response is base64 inside JSON, not a URL — decode data[i].b64_json and write bytes yourself (shown above). n>1 gives data[0..n-1].
  • safety_identifier (max 128 chars, hash usernames/emails — never send raw PII) is OpenAI's abuse-monitoring hook; the older user param is deprecated but still accepted. Send it on every user-facing call.
  • size accepts the presets 1024x1024, 1536x1024, 1024x1536, auto, or arbitrary WIDTHxHEIGHT on gpt-image-2 and the 2.5/2.6 models: both edges multiples of 16, aspect ratio between 1:3 and 3:1, each edge ≤ 3840 px, total pixels between 655,360 and 8,294,400. Above 2560x1440 is experimental.
  • quality: low, medium, high, auto everywhere; xhigh and max on the 2.5/2.6 models only. low is your draft tier — iterate prompts at low, render finals at high+.
  • output_format: png (default), jpeg, webp; the 2.6 models add svg and gif — see 3.8 for their constraints. output_compression (0–100) applies to jpeg/webp only. JPEG encodes faster — prefer it when latency matters and you don't need alpha.
  • background: auto (default), opaque, transparent. For transparency use background="transparent" with output_format="png" or "webp". On gpt-image-2 it's preview-only; full support on 2.5/2.6.
  • moderation: auto (default) or low — see 11.1 before touching it.
  • partial_images (0–3) + stream=True for progressive previews — 3.5.

3.3 Editing: references, masks, markup#

client.images.edit accepts up to 16 input images (image= takes one file or a list), a prompt, and optional mask and markup:

python
# s3_3_openai_edit.py — needs OPENAI_API_KEY in .env and Pillow
import base64
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

with open("kitchen.png", "rb") as img, open("mask_alpha.png", "rb") as m:
    result = client.images.edit(
        model="gpt-image-2.6-flare",
        image=img,
        mask=m,                      # same format+dims as image, <50MB, alpha channel; alpha 0 = edit region
        prompt=(
            "Replace the countertop with white marble. Keep the cabinets, "
            "lighting and everything outside the masked area unchanged."
        ),
        size="1536x1024",
        quality="high",
    )

Path("kitchen_marble.png").write_bytes(base64.b64decode(result.data[0].b64_json))

The mask contract (from the current API reference — this changed from the old DALL·E-era "PNG under 4 MB" spec): the image and mask must be the same format and dimensions, together under 50 MB, and the mask must contain an alpha channel — pixels with alpha 0 mark the editable region. Any image format works (a WebP mask for a WebP image is legal); what matters is the alpha channel. When several images are sent, the mask is meant for the first one: keep the image you want edited first, and confirm that on the current edit reference before relying on it. OpenAI's docs include a Pillow recipe to build one from a black-and-white mask — copy the luminance into alpha:

python
# s3_3b_mask_alpha.py — needs Pillow (illustrative output)
from io import BytesIO
from pathlib import Path

from PIL import Image

mask = Image.open("mask_bw.png").convert("L")      # black = edit here, white = keep
mask_rgba = mask.convert("RGBA")
mask_rgba.putalpha(mask)                            # luminance -> alpha: black becomes alpha 0 (editable)
buf = BytesIO()
mask_rgba.save(buf, format="PNG")
Path("mask_alpha.png").write_bytes(buf.getvalue())
print(f"mask_alpha.png written: {mask_rgba.width}x{mask_rgba.height} {mask_rgba.mode} PNG")
Example output · illustrative1 line
mask_alpha.png written: 1536x1024 RGBA PNG

The black-and-white mask must be the same size as the image you edit; black pixels become fully transparent, which is the region the model may change.

Two more edit modes on the 2.5/2.6 models:

  • Markup-guided edits — send a separate transparent PNG overlay (circles, arrows, sketches) as markup alongside the base image. The overlay must match the first image's dimensions after orientation, contain real transparent pixels, and can't be combined with mask or prompt_rewriter. JSON requests take markup as {image_url} or {file_id}; multipart takes the file. Max 16,777,216 px per layer, 50 MB file limit.
  • Multi-image composition — pass several image files and describe the composite ("put the product from image 2 into the scene from image 1"). Each input image is billed as image input tokens at $8/MTok — edits with references are not cheap; check usage.

input_fidelity (high/low) controls how hard the model tries to preserve facial features and style from inputs — supported on gpt-image-1.5 (both) and gpt-image-1-mini (low only); omit it for gpt-image-2 and later, which process inputs at high fidelity without the parameter. Both supporting models are on the 1 December 2026 shutdown list (1.2), so treat this knob as historical. The 2.6 prompting guide adds one more exclusion: gpt-image-2.6-* does not support reasoning.summary.

3.4 Responses API: the image generation tool#

The tool lets a mainline model generate and edit inside a conversation:

python
# s3_4_responses_tool.py — needs OPENAI_API_KEY in .env
import base64
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

response = client.responses.create(
    model="gpt-6.1-sol",                    # any gpt-5+ mainline model with tool support
    input="Generate an image of a gray tabby cat hugging an otter wearing an orange scarf",
    tools=[{
        "type": "image_generation",
        "model": "gpt-image-2.5-sunburst",  # which image model renders
        "action": "generate",               # "auto" | "generate" | "edit"
        "quality": "high",
        "size": "1024x1024",
    }],
)

for item in response.output:
    if item.type == "image_generation_call":
        print("status:", item.status)
        print("revised_prompt:", item.revised_prompt)
        Path("cat_otter.png").write_bytes(base64.b64decode(item.result))
Example output · illustrative2 lines
status: completed
revised_prompt: A gray tabby cat hugging an otter. The otter wears an orange scarf. Warm, heartwarming children's-book style.

What just happened, precisely:

  • The mainline model (gpt-6.1-sol) decided to call the tool and wrote a better prompt — that's revised_prompt. You pay for both the text model's tokens and the image model's tokens.
  • action: "auto" lets the model choose generate vs edit based on whether an image is already in context; "generate"/"edit" force it. Use "edit" when the user says "make the scarf blue" — the previous image is still in the conversation (or referenced by file ID / previous_response_id).
  • Image outputs are image_generation_call items in response.output; item.result is base64. You can also pass the image's file ID back in later turns instead of resending bytes.
  • Multi-turn editing is the killer feature vs the Image API: "same image, but night-time" reuses context instead of re-describing the scene from scratch — which is also why results stay consistent.

3.5 Streaming partial images#

Both APIs stream progressive renders. Via Responses:

python
# s3_5_stream_partial.py — needs OPENAI_API_KEY in .env
import base64
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

def save_b64(name, b64):
    Path(name).write_bytes(base64.b64decode(b64))

stream = client.responses.create(
    model="gpt-6.1-sol",
    input="A lighthouse on a cliff at dusk, waves crashing, dramatic clouds",
    stream=True,
    tools=[{"type": "image_generation", "model": "gpt-image-2.5-flare",
            "partial_images": 2}],
)

for event in stream:
    if event.type == "response.image_generation_call.partial_image":
        save_b64(f"lighthouse-partial-{event.partial_image_index}.png",
                 event.partial_image_b64)
        print(f"partial {event.partial_image_index} arrived")
    elif event.type == "response.completed":
        for item in event.response.output:
            if item.type == "image_generation_call":
                save_b64("lighthouse-final.png", item.result)
                print("final image saved")
Example output · illustrative3 lines
partial 0 arrived
partial 1 arrived
final image saved

Rules: partial_images accepts 0–3; you may receive fewer than requested if the final lands fast; each partial image costs 100 extra image-output tokens; the Image API's stream: true gives the same progressive behaviour for direct calls. For UX: show partials as "still rendering" previews, never as finals.

3.6 Errors you'll actually hit#

Image generation failures are typed, and the types matter (03.8 owns the general retry taxonomy — this is the image-specific layer):

Error shape Meaning What to do
error.type = "image_generation_user_error", code = "moderation_blocked" Prompt or output blocked by safety filtering Do not blind-retry. Read error.moderation_details: moderation_stage is input (fix the prompt/images), output (regenerate with a different prompt), or unknown; categories gives coarse labels like harassment, self-harm, sexual, violence
image_generation_user_error, other codes Bad params, unsupported size/format combo, verification missing Fix the request; these are permanent
Rate limit / 5xx / timeout Transient Retry with backoff per 03.8 — but cap attempts: a 2-minute generation × retries is a cost event
Quota / billing Account-level Alert a human; never retry-loop

The OpenAI docs' own JavaScript example maps moderation_details.categories to user-facing hints — copy that pattern: log request_id + moderation_details, show the user a generic message with a remediation hint. Part 11 expands on policy.

3.7 Cost arithmetic for OpenAI#

Per the pricing page (standard tier, November 2026). Batch is half price — but only for models that support it: the batch image table covers gpt-image-2, gpt-image-2.5-* and earlier; gpt-image-2.6-* is not batch-eligible (its model pages list v1/batch as not supported). Check the model page's endpoint table before budgeting batch volume:

Model Image input Image output Cached image input Text input Cached text input
gpt-image-2.6-sunburst / -flare, gpt-image-2.5-sunburst / -flare, gpt-image-2 $8.00/MTok $30.00/MTok $2.00/MTok $5.00/MTok $1.25/MTok
gpt-image-1.5 (deprecated — shuts down 2026-12-01) $8.00 $32.00 $2.00 $5.00 $1.25
gpt-image-1-mini (deprecated — shuts down 2026-12-01) $2.50 $8.00 $0.25 $2.00 $0.20

Cached-input rates apply only to the Responses API tool, not direct Images API calls — a subtle billing asymmetry worth knowing. Token consumption varies by model, size and quality; the docs ship a calculator, and the only authoritative per-request number is usage in the response. Rule of thumb from the historical tables: a 1024×1024 high image on older models ran ~4,160 output tokens ≈ $0.12 at $30/MTok — expect similar order of magnitude on current models at high, and roughly an order of magnitude less at low. Verify against usage on your own calls; don't budget from this paragraph.

3.8 The 2.6 extras: complexity, SVG, GIF and prompt_rewriter#

The 2.6 models add request surface the 2.5 models don't have. All of it is Image-API-only as of November 2026: both 2.6 model pages list just v1/images/generations and v1/images/edits as supported endpoints (Batch, Responses and Chat Completions are all "not supported"), and every documented Responses-tool example still uses a 2.5 model.

  • complexity (low/medium/high; both 2.6 models default to high when omitted): how much the model plans before rendering — independent of quality, which controls rendering detail. There is no separate fee. Lower it for focused edits ("change the background", "fix the sign"); raise it for dense layouts, heavy text or scenes with many interacting objects. Higher complexity can increase latency and introduce unwanted changes, so compare results at fixed quality. On SVG output it controls planning for the reference image, independently of the SVG author's reasoning.
  • prompt_rewriter: not a knob you set — it's the prompt-rewrite machinery whose output you see as revised_prompt on Responses calls. The docs prohibit combining it with markup, SVG and GIF output; sending it as an Images-API field reportedly returns unknown_parameter (community-reported, November 2026 — the parameter appears in the docs only inside "do not combine" rules). Treat it as internals to be aware of, not a parameter.
  • SVG output — output_format="svg" on generations only: the API first renders a reference image, then a separate authoring model writes SVG vector paths from it. Requires n=1; no streaming, partial images, output_compression or prompt_rewriter; the edit endpoint doesn't support SVG, and an SVG is not a valid raster input for edits. The optional svg object selects the author: svg.model names the authoring model (required when SVG model selection is enabled — omit the whole object when it's disabled), and svg.reasoning.effort (none/minimal/low/medium/high/xhigh/max, defaulting to the author model's default) sets the author's reasoning effort, independent of image complexity. Billing is two-part: the image model's rate for the reference image plus the authoring model's token rate for the SVG itself. Access requires the SVG preview — check your org's feature access before shipping it.
  • GIF output — output_format="gif": an animated loop described in the prompt ("the lantern swings gently and the monkey blinks"). frame_count (2–16, default 9) and frame_duration_ms (minimum 20 ms, default 200, rounded to 10 ms, capped at 655,350 ms per encoded frame) apply only with GIF output — size describes each frame and the whole request must fit the model's pixel budget. GIF does not support streaming, partial images, masks, custom output_compression or prompt_rewriter, and requires access to the GIF preview for the selected model. The guide documents GIF on both generations and edits (the edits reference lists gif in output_format plus the frame parameters); some third-party write-ups claim generations-only — when in doubt, test the endpoint or check the model page.
  • reasoning.summary is not supported on 2.6 — the prompting guide calls this out explicitly; don't pass it.

Part 4: Gemini image generation#

Deep-dive

4.1 The Nano Banana family#

Covered in 1.2. Two API surfaces, both in google-genai:

  • Interactions API — client.interactions.create(...): the documented primary path for image generation in the current docs — the only path the image-generation guide shows.
  • generate_content — client.models.generate_content(...) with response_modalities and image_config: the path consistent with the rest of this module (03.6 uses it for vision input). Treat as legacy, not co-equal: it no longer appears on Google's image-generation page; the SDK still ships ImageConfig, so it may work — verify before relying on it (4.3).

Both emit the same models. Imagen is shut down in the Gemini API — Nano Banana is the only path.

4.2 Interactions API: generate#

python
# s4_2_gemini_interactions.py — needs GEMINI_API_KEY in .env
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A vibrant infographic explaining photosynthesis as a recipe: "
          "sunlight, water and CO2 as ingredients, sugar as the finished dish. "
          "Colorful kids' cookbook style, suitable for a 10-year-old.",
    response_format={
        "type": "image",
        "aspect_ratio": "4:3",
        "image_size": "2K",
    },
)

# output_image holds the LAST generated image; for interleaved text+image
# stories, iterate interaction.steps instead (see docs)
if interaction.output_image and interaction.output_image.data:
    Path("photosynthesis.png").write_bytes(
        base64.b64decode(interaction.output_image.data))
    print("saved photosynthesis.png")
else:
    print("no image in output; statuses:", [s.status for s in interaction.steps])
Example output · illustrative1 line
saved photosynthesis.png

response_format details (verified from the docs):

  • {"type": "image"} returns image only; [{"type": "text"}, {"type": "image"}] returns both — the model can write the caption and draw it.
  • aspect_ratio: 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, 21:9 — the ultra-wide/tall ratios (1:4, 4:1, 1:8, 8:1) are a Nano Banana 2/2.1 differentiator. Default: match input image, else 1:1.
  • image_size: "0.5K", "1K", "2K", "4K" — uppercase K required; 0.5K only on gemini-3.1-flash-image; 3.1 Flash Lite Image supports 1K only; NB 2.1 does 1K/2K/4K. This is the price dial — see 4.6.
  • mime_type: output format inside response_format — the docs show image/png and image/jpeg; check the model's accepted values before requesting a specific one.
  • Output arrives base64 in interaction.output_image.data (a convenience property for the last image block), in the requested mime_type (PNG unless you ask otherwise).

4.3 generate_content: the module-consistent path#

python
# s4_3_gemini_generate_content.py — needs GEMINI_API_KEY in .env and Pillow
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types
from PIL import Image

load_dotenv()
client = genai.Client()

response = client.models.generate_content(
    model="gemini-nano-banana-2.1",
    contents=[
        "Put this product on a clean white studio background, soft shadow, "
        "e-commerce hero shot",
        Image.open("product_photo.jpg"),          # PIL image = reference input
    ],
    config=types.GenerateContentConfig(
        response_modalities=["TEXT", "IMAGE"],
        image_config=types.ImageConfig(
            aspect_ratio="1:1",
            image_size="2K",
        ),
    ),
)

for part in response.parts:
    if part.text is not None:
        print("text:", part.text.strip()[:200])
    elif image := part.as_image():
        image.save("hero_shot.png")
        print("saved hero_shot.png")
Example output · illustrative2 lines
text: Here is the product on a clean white studio background with a soft shadow.
saved hero_shot.png

The trap to avoid (it's a real SDK behaviour): aspect_ratio and image_size are not top-level GenerateContentConfig fields — they nest inside image_config, and the field is image_size, not resolution. Passing them top-level raises a Pydantic validation error before any request is sent.

4.4 Editing: references, multi-turn, video#

Editing on Gemini is just generation with images in the input — there's no separate edits endpoint:

  • Reference images: up to 14 on NB 2.1 / 3.1 Flash Image (max 10 objects at high fidelity + 4 characters for consistency); NB Pro: 6 objects + 5 characters + 3 style references. gemini-2.5-flash-image (legacy): 3 images.
  • Multi-turn: send the conversation (previous image parts + new instruction) — the model iterates conversationally, which is why Google positions it for "conversational editing".
  • Video-to-image: NB 2.1, 3.1 Flash Image and 3.1 Flash Lite Image accept video input and can extract/animate frames into images.
  • Search grounding: tools=[{"type": "google_search"}] on Interactions (or types.Tool(google_search=types.GoogleSearch()) on generate_content) grounds generation in real-time web text and image results — for NB 2.1 and 3.1 Flash Image. Real-world photos of people are excluded from grounding results.
  • Inpainting is prompt-driven ("semantic masking"): describe the region and the change; there is no mask parameter on the Gemini path — masks are an OpenAI/BFL concept.

4.5 SynthID: the watermark you can't remove by metadata-stripping#

Every image Gemini generates carries Google's SynthID invisible watermark — embedded in pixels, designed to survive crops, filters and recompression, and detectable via Google's verification tooling. Practical consequences:

  • You don't add it; it's automatic on API output too.
  • It won't stop a determined adversary (screenshots, heavy edits degrade it), but it's a real provenance signal — pair it with your own C2PA signing if you redistribute (11.4).
  • It does not visibly mark the image; users won't see a logo.

4.6 Pricing per resolution#

Image output is billed per image token, and the docs publish exact token counts per cell (standard tier; batch is half price):

Model Image output $/MTok 1K image 2K image 4K image Image input
gemini-nano-banana-2.1 $30 ($15 batch) 1,120 tok ≈ $0.034 1,680 tok ≈ $0.050 3,780 tok ≈ $0.113 $1.50/MTok text+image+video
gemini-3.1-flash-image (NB 2) $60 1,120 tok ≈ $0.067 1,680 tok ≈ $0.101 2,520 tok ≈ $0.151 $0.50/MTok
gemini-3.1-flash-lite-image (NB 2 Lite) $30 1,120 tok ≈ $0.034 — — (1K only) $0.25/MTok
gemini-3-pro-image (NB Pro) $120 1,120 tok ≈ $0.134 1,120 tok ≈ $0.134 2,000 tok ≈ $0.24 $2.00/MTok (560 tok/image)
gemini-2.5-flash-image (deprecated) — $0.039/image flat — — $0.30/MTok

Text output tokens (the caption/thinking) bill at normal text rates; Search grounding bills per request after 5,000 free/month shared across Gemini 3+ models. Batch API is supported on the image models — 50% off, async, link 03.9.


Part 5: OpenRouter and the rest#

Deep-dive

5.1 The dedicated Image API#

OpenRouter's Image API is a normalized gateway: one endpoint shape in front of dozens of providers' image models.

python
# s5_1_openrouter_images.py — needs OPENROUTER_API_KEY in .env
import base64
from pathlib import Path

import httpx
from dotenv import load_dotenv

load_dotenv()

def generate_image(prompt: str, model: str = "google/gemini-nano-banana-2.1") -> bytes:
    resp = httpx.post(
        "https://openrouter.ai/api/v1/images",
        headers={"Authorization": f"Bearer {__import__('os').environ['OPENROUTER_API_KEY']}"},
        json={
            "model": model,
            "prompt": prompt,
            "aspect_ratio": "16:9",
            "resolution": "2K",
            "quality": "high",
            "output_format": "png",
            "n": 1,
        },
        timeout=180.0,          # image gen is slow; set real timeouts (03.8)
    )
    resp.raise_for_status()
    body = resp.json()
    print("usage:", body.get("usage"))       # tokens + cost in USD when reported
    return base64.b64decode(body["data"][0]["b64_json"])

if __name__ == "__main__":
    Path("openrouter_img.png").write_bytes(
        generate_image("a red panda astronaut floating in space, studio lighting"))
    print("saved openrouter_img.png")
Example output · illustrative2 lines
usage: {'prompt_tokens': 0, 'completion_tokens': 1680, 'total_tokens': 1680, 'cost': 0.0504}
saved openrouter_img.png

Response shape: {created, data: [{b64_json, media_type}], usage: {prompt_tokens, completion_tokens, total_tokens, cost}}. usage.cost is what OpenRouter charged — read it, don't re-price it (same rule as 03.7 for chat).

5.2 Discovery: don't guess parameters#

The killer feature vs raw provider APIs: capability discovery. Before you send a parameter, ask what the model's endpoints accept:

python
# s5_2_openrouter_discovery.py — needs OPENROUTER_API_KEY in .env
import os
import httpx
from dotenv import load_dotenv

load_dotenv()
key = os.environ["OPENROUTER_API_KEY"]

models = httpx.get("https://openrouter.ai/api/v1/images/models",
                   headers={"Authorization": f"Bearer {key}"}).json()["data"]

for m in models:
    if "banana" in m["id"] or "flux" in m["id"]:
        print(m["id"], "->", m["architecture"]["output_modalities"],
              "| params:", sorted(m["supported_parameters"]))

# Per-endpoint truth: definitive params + pricing lines for one model
eps = httpx.get("https://openrouter.ai/api/v1/images/models/"
                "google/gemini-nano-banana-2.1/endpoints",
                headers={"Authorization": f"Bearer {key}"}).json()
for ep in eps["endpoints"]:
    print(ep["provider_slug"], ep["supported_parameters"], ep["pricing"])
Example output · illustrative2 lines
google/gemini-nano-banana-2.1 -> ['image'] | params: ['aspect_ratio', 'image_size', 'n', 'output_format', 'resolution', 'seed']
google-ai-studio {'aspect_ratio': {...}, 'image_size': {...}} [{'billable': 'output_image', 'unit': 'image', 'cost_usd': 0.0336}]

supported_parameters values are typed descriptors (enum with values, range with min/max, boolean); absent key = unsupported. Endpoint pricing entries are billable lines like {billable: "output_image", unit: "image"|"megapixel"|"token", cost_usd, variant?} — resolution-tiered pricing shows up as variants (2k, 4k). This is how you build a provider-agnostic image client: store the discovered params per model, validate the request against them before sending, and price from pricing[] — the same "capability registry" pattern as 03.11, but for images.

5.3 Normalized parameters and provider routing#

Request fields (all optional unless noted): model, prompt (required), aspect_ratio (normalized set incl. auto), resolution (512/768/1K/1.5K/2K/4K), size (tier like "2K" or explicit "2048x2048" — explicit pixels are provider-dependent; xAI and Sourceful V2/V2.5 reject them), quality (auto/low/medium/high), output_format (png/jpeg/webp/svg/gif), output_compression (0–100, jpeg/webp), background (auto/transparent/opaque; transparent needs png/webp), n (1–10), input_references (reference images as {"type": "image_url", "image_url": {"url": ...}} — HTTP(S) or base64 data URL; the accepted count varies by provider — 16 is OpenAI's cap, so check supported_parameters/endpoint docs per model), frame_count/frame_duration_ms (GIF), markup (transparent PNG overlay for markup-guided edits on supporting models like gpt-image-2.6), seed where supported.

Routing mirrors chat completions: provider: {only, order, ignore, sort: "price"|"throughput"|"latency", allow_fallbacks} — pin provider_tag from the endpoints record when you need a specific host (e.g., data residency or a provider whose moderation you trust).

5.4 Streaming#

Models with supports_streaming: true accept stream: true and return SSE:

text
data: {"type":"image_generation.partial_image","partial_image_index":0,"b64_json":"..."}
data: {"type":"image_generation.completed","b64_json":"...","media_type":"image/png","created":1748372400,"usage":{"prompt_tokens":16,"completion_tokens":272,"total_tokens":288,"cost":0.011}}
data: [DONE]

Partial images arrive as image_generation.partial_image events; the final lands in image_generation.completed with usage.cost. Errors mid-stream come as {"type":"error","error":{...}}.

5.5 The chat-completions fallback#

Some image-capable models on OpenRouter are not on the Image API — they return images inside ordinary chat completions (image output parts in the message). That path works but gives you none of the normalized parameters, no usage.cost guarantee, and provider-specific quirks. Rule: check /api/v1/images/models first; if the model isn't listed, chat completions is the fallback, not the plan.


Part 6: Specialist providers#

Deep-dive

These are single-purpose APIs — different shapes, worth knowing even if the big three cover your needs. All request shapes below were verified against official docs on 5 November 2026; treat exact paths/fields as "check the docs page" pointers since these APIs version quickly.

6.1 Stability AI#

Hosted REST API (docs.stability.ai), synchronous, credits: 1 credit = $0.01; 25 free credits on signup.

python
# s6_1_stability.py — needs STABILITY_API_KEY in .env (illustrative)
import os
import httpx
from dotenv import load_dotenv

load_dotenv()

resp = httpx.post(
    "https://api.stability.ai/v2beta/stable-image/generate/core",
    headers={"Authorization": f"Bearer {os.environ['STABILITY_API_KEY']}",
             "Accept": "image/*"},   # or application/json for base64
    files={"prompt": (None, "a red panda barista pulling an espresso shot, warm cafe light")},
    data={"aspect_ratio": "16:9", "output_format": "png", "seed": 42},
    timeout=120.0,
)
resp.raise_for_status()
open("panda.png", "wb").write(resp.content)   # image/* accept -> raw bytes

Credit costs on Stability's pricing page (November 2026): Stable Image Core 3 credits (about $0.03), Stable Image Ultra 8, Stable Diffusion 3.5 Large 6.5, Large Turbo 4, Medium 3.5 and Flash 2.5; edit tools such as Inpaint, Erase Object and Search and Replace cost 5 each. Core and Ultra take multipart/form-data with prompt (required), aspect_ratio (default 1:1), negative_prompt, seed (0 to 4294967294; 0 or omitted means random), style_preset and output_format (png default, jpeg, webp); the Accept header chooses raw bytes (image/*) or base64 JSON (application/json). The docs say failed generations are not charged, and a 403 moderation rejection is not charged either; a blurred CONTENT_FILTERED image is still billed as a success. Sources: pricing, Core, Ultra. There are also edit/inpaint endpoints in the same API family — check docs.stability.ai for the current paths.

6.2 Black Forest Labs (FLUX)#

Direct API at api.bfl.ai (plus api.eu.bfl.ai/api.us.bfl.ai regional endpoints), async by design: submit → get polling_url → poll until Ready, or register a webhook.

python
# s6_2_bfl.py — needs BFL_API_KEY in .env (illustrative)
import os, time
import httpx
from dotenv import load_dotenv

load_dotenv()
KEY = os.environ["BFL_API_KEY"]
H = {"x-key": KEY, "accept": "application/json"}

sub = httpx.post(
    "https://api.bfl.ai/v1/flux-2-pro",
    headers={**H, "Content-Type": "application/json"},
    json={"prompt": "a dramatic portrait, cinematic lighting", "width": 1440, "height": 810},
    timeout=60.0,
).json()
# sub: {id, polling_url, cost, input_mp, output_mp} — ALWAYS poll the returned polling_url
while True:
    r = httpx.get(sub["polling_url"], headers=H, timeout=30.0).json()
    print("status:", r["status"])
    if r["status"] == "Ready":
        img = httpx.get(r["result"]["sample"], timeout=60.0).content  # signed URL, valid ~10 minutes
        open("flux.png", "wb").write(img)
        break
    if r["status"] in ("Error", "Failed", "Request Moderated", "Content Moderated"):
        raise RuntimeError(f"generation failed: {r}")
    time.sleep(2)
Example output · illustrative3 lines
status: Pending
status: Generating
status: Ready

Verified details: the OpenAPI spec (api.bfl.ai/openapi.json) lists the statuses Task not found, Pending, Reasoning, Generating, Request Moderated, Content Moderated, No Card Generated, Ready and Error (the docs' own examples also test for Failed, so the loop above treats it as terminal too); result.sample is a signed URL that is valid for only 10 minutes — download immediately, don't store the URL, and don't send your x-key to it. Pricing is credits (1 cr = $0.01): FLUX.2 is billed per megapixel and varies with output resolution (klein has a flat first-megapixel rate), FLUX 3 Image is billed per image by resolution tier, and batch requests multiply the base cost by the image count; the per-model figures are on BFL's pricing calculator, so read it before you budget (this lesson quotes no per-model figures). FLUX.2 [klein] variants are the cheap/fast tier, [pro] mid, [max] premium, [flex] for typography/control; the concurrency limit is 24 requests for most endpoints and 6 for flux-kontext-max; FLUX.1 Kontext endpoints (/v1/flux-kontext, -max) are the editing specialists; FLUX 3 Image is the newest line. The submit response's cost field tells you the price before you poll.

6.3 Ideogram#

Best-in-class text-in-image rendering. The current API is v2 at developer.ideogram.ai (the older /v1/ideogram-v3/generate endpoint is marked legacy): every endpoint follows POST https://api.ideogram.ai/v2/{content}/{action}/{model}, for example POST /v2/image/generate/ideogram-4-5 (also ideogram-4; remix, precise-edit, upscale, background removal and describe endpoints sit beside it). Authenticate with an Api-Key header; the body is multipart/form-data with prompt (required), magic_prompt (auto/on/off), up to five source images plus an optional mask, size (auto, source or WIDTHxHEIGHT), background (transparent/opaque/auto), quality, seed and num_images. Image endpoints answer synchronously with data[].url by default; set async=true or an HTTPS webhook_url (signed with Ed25519; keys at https://api.ideogram.ai/v1/.well-known/jwks.json) to get a generation_id back and poll GET /v2/generations/{generation_id} until completed or failed. dry_run=true validates and prices a request without generating or billing. Image URLs expire, so download anything you keep (the docs do not state the lifetime). Billing is a prepaid balance (one-time top-ups of $10, $20, $50, $100 or $1–$300 custom, capped at a $300 balance; auto-recharge optional) drawn down at the rates on Ideogram's API pricing page (check it for current per-image prices). Sources: overview, Ideogram 4.5 generate, API setup.

6.4 Midjourney and the rest#

  • Midjourney: no public API (web/Discord product; enterprise access by application). Covered in 1.3.
  • Recraft: raster and SVG output — the pick when you need editable vectors; reachable direct or via OpenRouter. Direct API: https://external.api.recraft.ai/v1/images/generations with a Bearer token, and the openai SDK works by pointing base_url at Recraft. Vector generation returns a link to an SVG file that the docs say is valid for about 24 hours (download it); Vectorize converts a PNG or JPG for $0.01. Prices per image on Recraft's pricing page: V3 and V4 $0.04 raster and $0.08 vector, V4 Pro (2K) $0.25 raster and $0.30 vector; the docs overview also lists a cheaper V4.1 Flash from about $0.007 and V4.1 from $0.035, so confirm the current model list and prices before budgeting (docs, pricing).
  • xAI Grok Imagine: image + video generation through xAI's API and OpenRouter's Image API.
  • Amazon Nova Canvas/Reel: Bedrock async jobs for AWS-native shops.
  • fal / Replicate: aggregators hosting open and licensed models — useful for trying checkpoints without GPU ops, with wildly variable per-output pricing.

6.5 Open models, briefly#

diffusers (Hugging Face) is the standard local path: download weights, run DiffusionPipeline. Budget VRAM (consumer GPUs handle popular checkpoints; the largest need datacenter cards or quantized variants), read each checkpoint's licence (several popular ones are non-commercial), and implement your own safety filtering — self-hosting moves moderation from the provider's problem to yours. For most products, a hosted endpoint (BFL's free non-commercial FLUX.1 dev tier, Stability, fal, Replicate, OpenRouter) is the sane middle.


Part 7: Prompting for images#

Image prompts are a different craft from text prompts: you're directing a renderer, not a reasoner. The failure modes are visual (garbled text, wrong count, melted hands, style drift), so the prompt's job is to pin down exactly those things.

7.1 Anatomy of an image prompt#

A reliable structure, in order:

text
[Subject + key details] + [Action/pose] + [Setting/background] +
[Style/medium] + [Lighting/mood] + [Camera/composition] + [Text constraints] + [Negative constraints]

Example (marketing hero shot):

text
A ceramic pour-over coffee dripper on a walnut counter, morning light through a
window, shallow depth of field, photorealistic product photography, 85mm lens,
soft shadows, no text, no watermark

vs the same idea written badly:

text
coffee thing, nice, professional photo

Specificity is leverage: "85mm lens, shallow depth of field" beats "professional photo" every time, because the model has actually seen a million photos tagged with those terms.

7.2 Negative constraints#

There's no negative_prompt field on most modern APIs — you express exclusions positively:

  • Bad: "no text, no watermark, no blurry background"
  • Good: "clean minimal composition, sharp focus throughout, studio backdrop"

Google's docs call this semantic negative prompting: describe the intended scene so the unwanted thing has nowhere to appear. Stability's API does have a real negative_prompt field — one of the few that kept it.

7.3 Text in images#

Legible text inside images is the hardest trick in the field. What helps:

  1. Put the exact string in quotes and repeat it: a storefront sign reading "OPEN 24 HOURS".
  2. Generate the text first, then the image: Gemini's docs explicitly recommend generating text content first, then asking for the image with that text — two-step beats one-shot for anything beyond a word or two.
  3. Short strings win: headlines, labels, prices — not paragraphs.
  4. Ideogram is the specialist for a reason; OpenAI and Nano Banana Pro are the generalists that get closest.
  5. Verify before shipping: a VLM check ("does the sign read X?") or human review — never trust first-render text on customer-facing assets.

7.4 Prompt expansion with an LLM#

A cheap text model can turn a one-line brief into a full image prompt — and this is a place where the module's earlier lessons plug straight in (structured output for the expansion schema):

python
# s7_4_prompt_expand.py — needs OPENAI_API_KEY in .env (illustrative output)
import json
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

brief = "hero image for a SaaS landing page: developer tools, midnight theme"

resp = client.responses.create(
    model="gpt-6-luna",                      # cheap text model is plenty
    input=(
        "Expand this image brief into a detailed text-to-image prompt. "
        "Return JSON with keys: subject, style, composition, lighting, "
        "palette, constraints.\n\nBrief: " + brief
    ),
    text={"format": {"type": "json_object"}},
)
expanded = json.loads(resp.output_text)
print(json.dumps(expanded, indent=2))
Example output · illustrative8 lines
{
  "subject": "A sleek laptop on a dark desk showing a code editor with syntax-highlighted terminal panels",
  "style": "minimalist 3D render, soft gradients, subtle glassmorphism UI elements",
  "composition": "laptop centered at slight angle, negative space on the left for headline text",
  "lighting": "cool blue ambient glow, rim light on keyboard edges, screen as key light",
  "palette": "deep navy #0B1020, electric blue #4F7CFF, soft cyan accents",
  "constraints": "no people, no logos, no readable text, no watermark"
}

7.5 Consistency across a series#

Products need sets: ten thumbnails, a campaign, an icon family. Techniques, roughly in order of reliability:

  1. Reference images (edits / multi-image input): generate one approved hero, then pass it as a reference for every variant — "same scene and style, change only the headline text to X". This is the strongest lever on every provider.
  2. Locked prompt scaffold: keep subject/style/lighting clauses byte-identical; vary only the slot that should change. Log the scaffold (link 04.10 prompt versioning — treat image prompts as prompts).
  3. Seeds: Stability, BFL, Ideogram and OpenRouter-passthrough support seed; OpenAI and Gemini don't document one for the API. Even where supported, seeds give similarity, not identity — use references for identity.
  4. Character/style anchors: Gemini's 4-character / 3-style-reference slots and OpenAI's multi-image edits exist precisely for this — a character sheet of 3–4 views beats any prompt trick.
  5. Post-process for true consistency: if it's a logo or brand mark, generate the concept then render the final deterministically (SVG, Pillow compositing) — don't ask the model to redraw your trademark ten times.

7.6 Aspect ratio and composition planning#

Decide the canvas before the prompt — cropping a 16:9 generation to 1:1 throws away a third of the image and often decapitates the subject. Map deliverables to ratios up front (the parameter tables in Parts 3–5 give each provider's supported set). For text-overlay layouts, ask for the text-free version and composite typography in post — you get crisp, correct, localizable text for free.

Goal Prompt skeleton Provider tip
Product hero [product] on [surface], [lighting], [lens/style], sharp focus, no text Edits with your real product photo beat text-only
Thumbnail [subject] close-up, high contrast, bold simple background, room for overlay text on left Generate text-free; overlay in post
Icon set flat vector icon of [X], [style], centered, solid [colour] background Request a grid then slice, or one-per-call for consistency
Lifestyle scene [product] in use by [persona] in [setting], candid photography, natural light Reference the product photo
Social graphic [visual] with space for headline; no text → composite Always composite text in post
Data-viz-ish image avoid — models garble charts; generate the illustration and build the chart in code —
Alt-text round trip generate image → VLM caption → compare to intent see 9.2

The gallery is the quick reference; these five recipes recur in real products enough to deserve their own pipelines.

Background removal and replacement. Two-step: (1) obtain a clean cut-out — ask for the subject on a flat chroma background and key it out in post, use a dedicated remove-background model or endpoint (several specialists and the fal/Replicate aggregators host them), or supply a mask; (2) composite onto the new scene deterministically with Pillow, or send subject + target scene as references for a generative composite. For "product on a marble counter"-style edits, mask the old background where the API supports it (8.2). Deterministic compositing wins whenever the subject must stay pixel-exact — generative fill is for when the scene itself should change.

Virtual try-on style edits. Dress, furniture and eyewear "try it on" is a reference-image edit: garment photo + person photo in, "the person wears this garment; keep face, pose and lighting" out. Consent is the product requirement, not a footnote: get documented consent before storing body or face images, tell users their photos go to third-party models, and follow each provider's likeness rules (11.2). For minors or sensitive categories, prefer "see it in your space" scenes over real-person edits.

Diagrams and infographics — the honest limits. Models produce illustrations, not diagrams: arrows, axis labels, node text and precise layouts are exactly where generation fails. The working recipe is hybrid — generate the hero illustration and icons, then build the actual chart or diagram in code (matplotlib, SVG, a design tool) and composite. If the deliverable is mostly text and structure, skip the image model entirely: an LLM writing HTML/SVG beats a diffusion model at diagrams every time.

Game and design asset sets. Consistency is the whole problem: lock a style-prompt scaffold (7.5), generate one approved hero per asset class, then produce variants via reference-image edits. For sprite and UI work, ask for grid sheets and slice in post — but expect to hand-fix edges. Icons, logos and anything needing editable vectors suit SVG output (gpt-image-2.6, 3.8) or Recraft better than raster diffusion. Keep a style bible (palette hex codes, line weights, corner radii) and validate every asset against it with a VLM rubric (9.2).

Data augmentation for CV training. Generate varied scenes and labels to bulk up a small dataset — product shots on new backgrounds, documents with different layouts, defect-free vs defective variants. Three rules: check each provider's terms for whether outputs may train models (commercial-use rights vary by tier — 11.3); record provenance per generated image; and verify the data actually helps — a bake-off on a held-out real set beats intuition (Module 10A owns evals). Synthetic data also amplifies biases: whatever the generator can't produce, your model can't learn.


Part 8: Editing workflows in depth#

Deep-dive

8.1 The edit taxonomy#

Edit type What it is Best mechanism
Global restyle Whole image, new look (watercolor, noir, brand palette) Text prompt + reference image
Local edit Change one region (swap background, fix an object) Mask/inpaint (OpenAI mask, BFL fill) or markup overlay
Composition Combine elements from multiple images Multi-image input (OpenAI ≤16, Gemini ≤14)
Character/style lock Same person/character/style across generations Reference images / Gemini character refs
Iterative refinement "Same, but…" conversation Responses tool / Gemini multi-turn
Generative fill Extend canvas, remove object Mask + prompt ("empty street, no cars")

8.2 Mask mechanics (OpenAI path)#

Already covered in 3.3: same format and dimensions as the image, under 50 MB, alpha channel required, alpha-0 = editable. Two production notes:

  • Generate the mask programmatically, not by hand: segment with a VLM ("give me a bounding box for the vase"), rasterise the box to an alpha mask with Pillow, dilate slightly — models need a margin.
  • The mask is a hint, not a contract: GPT Image edits are prompt-based — the mask biases where change happens but the model re-renders the whole image. Always instruct what must stay unchanged ("keep everything outside the mask identical"), then verify.

8.3 Markup-guided edits#

OpenAI's markup (2.5/2.6) and OpenRouter's passthrough take a different approach: a transparent annotation layer (circle the vase, arrow the sign) overlaid on the first image. Cheaper to produce than a precise mask — a designer can sketch it — and the model reads intent, not just region. Constraints: same dims as image 1, real alpha, can't combine with mask, ≤16.7 MP per layer.

8.4 Edit vs regenerate — the decision#

  • Edit when the image is mostly right: preserves composition, lighting, everything you already approved. Costs input-image tokens but saves prompt-engineering iterations.
  • Regenerate when the image is mostly wrong or you need a different seed of the idea: cheaper mentally, riskier for consistency.
  • Rule of thumb: one approved image → edit for variants; new concept → regenerate with the approved image as reference (not as edit target).

Part 9: The production pipeline#

Real products don't call images.generate and ship the bytes. The pipeline is four stages, each independently testable:

flowchart LR
    A["Brief + refs"] --> B["Generate<br/>(provider call)"]
    B --> C["Validate<br/>(VLM check vs brief)"]
    C -->|"fail, attempts left"| B
    C -->|"pass / budget out"| D["Post-process<br/>(Pillow/resize/optimise)"]
    D --> E["Store + provenance<br/>(bytes, metadata, prompt version)"]

9.1 The orchestrator#

python
# s9_1_pipeline.py — illustrative provider calls; pure-local parts runnable
import base64, hashlib, json, time
from dataclasses import dataclass, field
from pathlib import Path

@dataclass
class Generated:
    png_bytes: bytes
    model: str
    prompt: str
    revised_prompt: str | None = None
    cost_usd: float | None = None
    latency_s: float = 0.0
    provenance: dict = field(default_factory=dict)

def generate(prompt: str, refs: list[Path] | None = None) -> Generated:
    """Provider call — illustrative. Swap for OpenAI/Gemini/OpenRouter/BFL."""
    t0 = time.time()
    # ... client.images.generate(...) or interactions.create(...) ...
    raise NotImplementedError("wire your provider here (Parts 3-6)")

def validate(image_png: bytes, brief: str) -> tuple[bool, str]:
    """VLM check: does the image match the brief? Illustrative."""
    # Send image + rubric to a vision model (03.6 mechanics); expect JSON verdict.
    raise NotImplementedError("wire a VLM check here")

def post_process(png_bytes: bytes, max_edge: int = 1600) -> bytes:
    """Resize/optimise — Pillow version (illustrative):
        from PIL import Image; from io import BytesIO
        im = Image.open(BytesIO(png_bytes)).convert("RGB")
        im.thumbnail((max_edge, max_edge))
        buf = BytesIO(); im.save(buf, "JPEG", quality=88, optimize=True)
        return buf.getvalue()
    """
    return png_bytes  # placeholder

def store(asset: Generated, out_dir: Path) -> Path:
    """Content-addressed storage + provenance sidecar (pure local, runnable)."""
    digest = hashlib.sha256(asset.png_bytes).hexdigest()[:16]
    img_path = out_dir / f"{digest}.png"
    img_path.write_bytes(asset.png_bytes)
    meta = {
        "sha256": hashlib.sha256(asset.png_bytes).hexdigest(),
        "model": asset.model,
        "prompt": asset.prompt,
        "revised_prompt": asset.revised_prompt,
        "cost_usd": asset.cost_usd,
        "latency_s": asset.latency_s,
        "provenance": asset.provenance,   # e.g. {"c2pa": "embedded", "synthid": True}
        "prompt_version": "imggen-v3",    # link 04.10 versioning
    }
    (out_dir / f"{digest}.json").write_text(json.dumps(meta, indent=2))
    return img_path

The design rules:

  • Bounded retries: generate → validate loops at most 2–3 attempts, then escalate quality tier or route to a human — a retry loop on a $0.10/image model with no cap is a cost incident (10.2).
  • Validation is a rubric, not a vibe: give the VLM a checklist ("subject present? text legible and correct? brand colours? no extra fingers?") and ask for JSON — 03.4 owns structured output; reuse it.
  • Store provenance with the asset: model ID, exact prompt and revised prompt, seed/params, cost, timestamp, and which watermark/credentials the provider embeds. When a user asks "is this AI?", you answer from this file, not memory.
  • Content-addressed filenames (sha256 prefix) make dedup and cache-busting free.

9.2 Validate with a vision model#

The validator is a VLM call (03.6 owns sending images): send the generated image plus a rubric, get a verdict. Sketch:

python
# s9_2_vlm_validate.py — illustrative (needs a vision model + key)
def vlm_verdict(image_png: bytes, brief: str, rubric: list[str]) -> dict:
    """Ask a VLM: for each rubric item, pass/fail + one-line reason."""
    # client.responses.create(model="gpt-6.1-terra",
    #   input=[{"type":"input_text","text": rubric_prompt},
    #          {"type":"input_image","image_url": f"data:image/png;base64,{b64}"}],
    #   text={"format": {...json schema...}})
    ...

What belongs in the rubric for your use case: subject correctness, text-in-image accuracy (quote the expected string), count of items, brand colours/logos, absence of artifacts (extra limbs, melted text), composition/aspect match. What doesn't: artistic merit — that's human or preference-eval territory (Module 10A).

9.3 Post-process with Pillow and a keyless version#

Pillow is the right tool in production: Image.open → thumbnail/resize → convert("RGB") → save(..., optimize=True), plus ImageOps.exif_transpose, format conversion, and stripping metadata. Two production notes: strip EXIF/GPS from user-supplied references before sending them anywhere (09.1 covers the privacy mechanics), and always re-encode before serving — provider PNGs are large; a 1600px JPEG q88 is typically 10× smaller.

For the keyless path, here's the same job in pure stdlib — parse a PPM, thumbnail it, write a real PNG (zlib is stdlib). This runs today, no packages:

python
# s9_3_ppm_png.py — pure stdlib, ran; real output below
import struct, zlib

def read_ppm(path):
    data = open(path, "rb").read()
    tokens, i = [], 0
    while len(tokens) < 4:
        while data[i:i+1].isspace(): i += 1
        if data[i:i+1] == b"#":
            while data[i:i+1] != b"\n": i += 1
            continue
        j = i
        while not data[j:j+1].isspace(): j += 1
        tokens.append(data[i:j]); i = j
    i += 1
    magic, w, h = tokens[0], int(tokens[1]), int(tokens[2])
    assert magic == b"P6" and int(tokens[3]) == 255
    px = data[i:i + w*h*3]
    return w, h, px

def write_png(path, w, h, rgb):
    def chunk(tag, payload):
        return (struct.pack(">I", len(payload)) + tag + payload
                + struct.pack(">I", zlib.crc32(tag + payload)))
    raw = b"".join(b"\x00" + rgb[y*w*3:(y+1)*w*3] for y in range(h))
    png = (b"\x89PNG\r\n\x1a\n"
           + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
           + chunk(b"IDAT", zlib.compress(raw, 9))
           + chunk(b"IEND", b""))
    open(path, "wb").write(png)

def thumbnail(w, h, px, max_edge):
    scale = min(1.0, max_edge / max(w, h))
    nw, nh = max(1, round(w*scale)), max(1, round(h*scale))
    out = bytearray(nw*nh*3)
    for y in range(nh):
        for x in range(nw):
            sx, sy = min(w-1, int(x/scale)), min(h-1, int(y/scale))
            o, s = (y*nw+x)*3, (sy*w+sx)*3
            out[o:o+3] = px[s:s+3]
    return nw, nh, bytes(out)

# 8x6 test "photo": sky/ground bands + a bright square
w, h = 8, 6
px = bytearray(w*h*3)
for y in range(h):
    for x in range(w):
        o = (y*w+x)*3
        if 2 <= x < 6 and 1 <= y < 5: px[o:o+3] = bytes((240, 200, 60))
        elif y < 3:                  px[o:o+3] = bytes((60, 120, 220))
        else:                        px[o:o+3] = bytes((90, 160, 70))
open("test.ppm", "wb").write(f"P6\n{w} {h}\n255\n".encode() + bytes(px))

W, H, P = read_ppm("test.ppm")
print(f"read {W}x{H} PPM, {len(P)} bytes of RGB")
nw, nh, thumb = thumbnail(W, H, P, max_edge=4)
write_png("thumb.png", nw, nh, thumb)
print(f"wrote thumb.png: {nw}x{nh}")
Output2 lines
read 8x6 PPM, 144 bytes of RGB
wrote thumb.png: 4x3

Part 10: Cost and latency#

Deep-dive

10.1 Cost arithmetic#

Two pricing shapes meet in this lesson:

Per-image (specialists, some OpenRouter endpoints): cost = n_images × unit_price (+ input/reference surcharges). Dead simple.

Per-token (OpenAI GPT Image, Gemini Nano Banana): cost = (image_in_tokens × in_rate + image_out_tokens × out_rate + text_tokens × text_rate) / 1e6. The unknown is image_out_tokens, which scales with resolution tier × quality. Worked example (illustrative parameters):

python
# s10_1_cost_calc.py — pure Python, ran; prices are parameters, not constants
from dataclasses import dataclass

@dataclass(frozen=True)
class ImagePrice:
    """USD per 1M tokens. Fill from the provider's pricing page."""
    image_in: float
    image_out: float
    text_in: float = 0.0
    cached_image_in: float = 0.0

# OpenAI gpt-image-2.5/2.6 standard tier (Nov 2026)
OPENAI_GPT_IMAGE = ImagePrice(image_in=8.0, image_out=30.0, text_in=5.0, cached_image_in=2.0)
# Gemini gemini-3.1-flash-image image output only (text billed separately)
GEMINI_NB2 = ImagePrice(image_in=0.5, image_out=60.0)

def cost_per_image(price: ImagePrice, out_tokens: int,
                   in_tokens: int = 0, text_tokens: int = 0,
                   cached_in: int = 0) -> float:
    uncached_in = max(0, in_tokens - cached_in)
    return (uncached_in * price.image_in
            + cached_in * price.cached_image_in
            + out_tokens * price.image_out
            + text_tokens * price.text_in) / 1_000_000

# Illustrative token counts (verify on your own calls via usage):
#   OpenAI 1024x1024 high ~ a few thousand out tokens; Gemini 1K = 1,120, 2K = 1,680, 4K = 2,520-3,780
for label, p, out_tok, in_tok in [
    ("OpenAI 1K high (est 4k out tok)", OPENAI_GPT_IMAGE, 4000, 0),
    ("OpenAI edit +1 ref img (est 1.2k in tok)", OPENAI_GPT_IMAGE, 4000, 1200),
    ("Gemini NB2 1K", GEMINI_NB2, 1120, 0),
    ("Gemini NB2 4K", GEMINI_NB2, 2520, 0),
]:
    c = cost_per_image(p, out_tok, in_tok)
    print(f"{label:38s} ${c:.4f}/image")
print(f"{'10k images, OpenAI high':38s} ${cost_per_image(OPENAI_GPT_IMAGE, 4000)*10000:,.0f}")
Output5 lines
OpenAI 1K high (est 4k out tok)          $0.1200/image
OpenAI edit +1 ref img (est 1.2k in tok) $0.1296/image
Gemini NB2 1K                            $0.0672/image
Gemini NB2 4K                            $0.1512/image
10k images, OpenAI high                  $1,200

10.2 Hidden costs#

Cost Where it hides
Retries A failed quality:"max" 4K render retried 3× costs 3×; validation-loop retries multiply generation calls
Partial images +100 output tokens each on OpenAI
Reference images Image input tokens on edits (OpenAI $8/MTok); up to 14 refs on Gemini billed as input
The orchestrator Responses-tool calls bill the mainline text model too
Validation VLM calls Every generate→validate loop adds a vision-model call (~1–2k image input tokens)
Storage/CDN Generated PNGs are 1–5 MB; 10k images ≈ tens of GB — lifecycle rules matter (03.7, 09.10)
Moderation low Cheaper refusals? No — it changes filtering strictness, not price; don't conflate

10.3 Cost caps per user#

Per-user image budgets are a product requirement, not a nicety: quota counters keyed by user ID, hard caps before the provider call (estimate worst-case cost first), and safety_identifier/equivalent on every call so abuse is attributable. Link 03.7 Part 12 for the budget-guard pattern — same shape, image units.

10.4 Latency budgets#

Stage Typical Notes
Generate (1K, medium) 3–15 s Provider- and quality-dependent
Generate (4K, max/xhigh) 30–120 s OpenAI warns up to ~2 min for complex prompts
Edit with refs +input processing Roughly generate + overhead
Validate (VLM) 2–5 s Small compared to generation
Post-process <1 s Pillow resize/encode
Interactive total ~5–30 s acceptable Show partials/progress; async beyond that
Batch/async jobs minutes BFL-style poll/webhook; OpenAI/Gemini Batch APIs for offline volume (OpenAI batch covers 2.5-and-earlier image models — not 2.6)

Design rule: for user-facing generation, stream partials where offered (OpenAI, OpenRouter SSE) or show a progress state; for anything >30 s expected, make it a job (submit → poll/webhook → notify) — the BFL pattern in 6.2 is the template.


Part 11: Safety, ethics and provenance#

Deep-dive

11.1 Content policies and moderation errors#

Every major provider moderates prompts and outputs — OpenAI's moderation param (auto/low), Google's Prohibited Use Policy enforced platform-side, specialists varying from built-in filters to "you implement it". The engineering surface:

  • moderation_blocked is a distinct outcome (3.6): error.type="image_generation_user_error", code="moderation_blocked", with moderation_details.moderation_stage (input/output/unknown) and coarse categories. Handle it as a user-correctable outcome — show a specific, kind message ("that prompt touched a restricted category; try describing the scene differently") — not a generic 500.
  • moderation: "low" relaxes filtering on OpenAI — use only when your product legitimately needs edgier content and you've built your own safety layer (Module 12). It does not remove output filtering entirely.
  • Pre-filter prompts yourself for user-facing products: a cheap text-model check before spending image tokens is cheaper than a blocked render (12 owns the defence patterns).

11.2 Deepfakes, likeness and children#

  • Real-person likeness: generating a recognizable real person without consent is the classic deepfake harm — and a policy violation on every major provider. Reference-image workflows make this easier to do accidentally: a customer's photo used as "style reference" can leak identity. Rules: never generate identifiable real people without documented consent; prefer illustrations/avatars; for try-on/style features, disclose and get consent.
  • Children: stricter rules everywhere — no photorealistic minors, period. Build age-appropriate defaults into product design, not just prompts.
  • Deception: images that could be mistaken for real events/people need disclosure — see 11.4 and your jurisdiction's rules.

The honest state of play (as of November 2026): image models trained on scraped imagery face ongoing litigation; providers' terms grant you usage rights to outputs with varying scopes (check each provider's terms — commercial use is generally allowed on paid tiers, restricted on free tiers). Practical rules:

  • Don't generate in the style of living artists by name unless the provider's terms allow it — "in the style of Studio Ghibli" prompts are both a policy and an ethics grey zone.
  • Trademarks: models will happily render "Nike" or "Disney" — you own the legal exposure. Don't ship generated logos/characters resembling protected marks.
  • Outputs aren't copyright-free guarantees either — provenance (below) is how platforms and courts increasingly trace origin.

11.4 Provenance: credentials and watermarks#

Two different signals, often confused:

Signal What it is Who embeds it Survives
C2PA Content Credentials Signed metadata manifest (issuer, trainedAlgorithmicMedia source type, actions) OpenAI (Conforming Generator Product since 2024; C2PA + SynthID on API images) File-level: stripped by re-encoding/screenshots unless re-signed
SynthID Invisible watermark in the pixels Google (all Gemini images), OpenAI (since ~May 2026, alongside C2PA) Some transforms: crops/filters/recompression degrade but often don't remove

Verified specifics: OpenAI's Content Provenance API (POST /v1/content_provenance_checks, which checks images for C2PA and SynthID signals and audio for SynthID) verifies whether a file carries supported OpenAI signals — build it into your trust-and-safety review flow. Google's SynthID has public verification tooling. OpenAI's help-centre article on provenance signals says API outputs are covered except for models slated for imminent deprecation, naming gpt-image-1 and gpt-image-1.5 (read the current page before promising coverage for a specific model). Stability, BFL, Ideogram and most specialists document no provenance — if provenance matters for your product, prefer OpenAI/Gemini routes or implement your own (sign outputs with C2PA yourself — the spec is open).

Practical pattern: store provenance: {"c2pa": "embedded", "synthid": true, "provider": "openai"} in your asset metadata (9.1) and disclose AI-generation to end users where required or expected.

11.5 Disclosure and abuse prevention#

For user-facing generation ("users can make images in your app"):

  • Disclose: label AI-generated content visibly or via metadata — several jurisdictions now require it for realistic synthetic media; platforms (app stores, social) increasingly demand it.
  • Abuse surface: unauthenticated generation endpoints are spam/fraud farms. Require auth, per-user quotas, safety_identifier-equivalent logging, prompt+output moderation, and rate limits — the same wrapper discipline as 03.8 plus Module 12's injection/abuse patterns.
  • Never expose raw provider keys client-side; generate server-side and serve processed assets (09.10 owns the architecture).

Part 12: Operations#

Deep-dive

12.1 Async jobs: polling vs webhooks#

Three latency profiles exist:

  • Synchronous-ish (OpenAI Images API, Gemini Interactions/generate_content, Stability, Ideogram sync): call blocks for seconds-to-a-minute. Works for interactive use with generous timeouts; risky behind short proxy timeouts — raise them or stream.
  • Submit → poll (BFL, Ideogram async, OpenAI/Gemini Batch APIs): submit returns an ID/polling_url; poll until Ready/completed. Simple, robust, no inbound connectivity needed. BFL's signed result URL is valid for only 10 minutes — download on Ready.
  • Submit → webhook (BFL optional, Ideogram webhook_url, OpenRouter Batch per 03.9): provider POSTs you on completion. Best for scale; you must verify signatures and handle retries/idempotency (03.9 Part 13 has the webhook-verification pattern).

Choose polling for scripts/internal tools; webhooks for user-facing async at volume; batch APIs (03.9) for offline bulk generation at 50% off where the model supports batch — on OpenAI that means gpt-image-2, gpt-image-2.5-* and earlier; gpt-image-2.6-* is not batch-eligible as of November 2026, and the 1.5/1-mini/chatgpt-image-latest rows are leaving on 1 December 2026 anyway. Check the model page's endpoint table.

12.2 Storage, caching, CDN#

  • Store originals content-addressed (sha256) in object storage; serve resized derivatives via CDN. Generated PNGs run 1–5 MB — always post-process before serving (9.3).
  • Cache by prompt+params hash for repeated identical requests (thumbnails, placeholders); cache validation verdicts too.
  • Lifecycle rules: delete or tier originals per retention policy — generated assets are your storage bill forever.

12.3 Quality control#

  • Sample human review: auto-approve low-risk asset classes, queue the rest — set the sampling rate by risk.
  • Regression fixtures: keep a fixed set of (brief → expected traits) and re-run on model upgrades — providers change models silently (02.9, 8.2); pin dated snapshots where offered (-2026-09-08 style) for reproducibility.
  • Metrics: cost per accepted image, validation pass rate, latency p50/p95, moderation-block rate — feed Module 10A's evals.

12.4 Fallbacks#

Provider-agnostic design pays off here: keep a generate() interface with per-provider adapters (the 03.11 pattern). Fallback chains: primary model → cheaper model → different provider → cached placeholder + "try again". Quality differs across providers — a fallback that silently changes aesthetic is a product decision, so make it explicit config, not hidden retry logic.

12.5 Decision table#

You need... Reach for... Why
Fast drafts, cheap iteration gpt-image-2.5-flare low/medium, or Gemini NB 2 Lite Speed + price
Editing precision, masks, markup gpt-image-2.6-sunburst or 2.5-sunburst Best edit controls
Conversational "make it bluer" editing Gemini NB 2.1 or OpenAI Responses tool Multi-turn context
Brand-consistent campaigns Gemini NB Pro or reference-heavy OpenAI edits Character/style refs
Text inside images Ideogram 4.x; NB Pro; gpt-image high Specialist wins
Cheapest per image at volume Stability Core/Flash, BFL klein; batch tiers on batch-supported models (not gpt-image-2.6-*) Per-image pricing + batch where supported
SVG/vector output Recraft, gpt-image-2.6 output_format="svg" Rare capability
Everything through one key OpenRouter Image API Normalized params + discovery
Anthropic-only shop Claude orchestrates → Gemini/OpenAI renders No Claude image gen
Self-host / data residency diffusers, BFL EU endpoint, cloud GPUs Control vs ops burden

The ways image generation actually fails in production — symptom first, then cause and fix. API-level errors are in 3.6; this table is about output failures and the operational ones that follow.

Failure Symptom Likely cause Fix
Garbled or misspelled text in image A sign reads "OPEN 24 HOURS" as "0PEN 240URS" Text-in-image is the hardest capability; one-shot prompts rarely nail it Two-step: generate/approve the string first, then the image (7.3); quote exact text; keep strings short; Ideogram or NB Pro for hard cases; VLM-verify before shipping (9.2)
Wrong object count "Three apples" renders five Counting isn't a grammar the model reliably follows State counts early and explicitly; simplify the composition; raise quality/complexity; accept and hand-fix for hero assets
Character drift across a series Thumbnail 4's mascot has a different hat Each call re-rolls identity; prompts alone don't lock it Reference-image edits off the approved hero (7.5); Gemini character refs; render brand marks deterministically in post
moderation_blocked API error, not a bad image Prompt or output hit the safety filter Not a blind retry — read moderation_details.moderation_stage/categories, fix the prompt or regenerate differently (3.6, 11.1)
Mask ignored / edit leaks outside the region The background changed when only the product should move Masks are prompt-based hints, not hard constraints (8.2) Restate what must stay fixed; dilate the mask; verify with a pixel diff or VLM; try markup or reference images instead
Runaway retry costs Bill 5× the estimate on a "simple" feature Uncapped generate→validate→retry loops on per-token pricing Hard attempt caps (2–3), escalate quality tier or route to human review, per-user budgets (9.1, 10.2, 10.3)
Wrong aspect ratio / cropped subject Hero shot loses the head after resizing Canvas chosen after generation; cropping throws away composition Plan the canvas first (7.6); generate at the target ratio; composite text and graphics in post
Provenance stripped in post C2PA credentials gone after your Pillow re-encode Re-encoding removes file-level metadata Keep the provider original plus a provenance sidecar; SynthID survives pixels better than C2PA survives re-encoding (11.4)
Silent model change Same prompt, different aesthetic after a provider update Providers ship new snapshots without announcement Pin dated snapshots where offered; keep regression fixtures and re-run them on upgrades (12.3)
Deprecated-model failures gpt-image-1.5 calls start returning errors Model shut down — 1.5/1-mini/chatgpt-image-latest leave on 1 December 2026 Track shutdown_date via GET /v1/models; migrate to the 2.6 pair (1.2)
GIF/SVG request rejected invalid_request_error on output_format Wrong endpoint (SVG is generations-only), missing preview access, or n>1 on SVG Check 3.8; GIF needs preview access; SVG needs n=1 and no streaming

Common misconceptions#

Misconception Reality
"Claude can generate images if you ask nicely." No — Anthropic's API returns text only; Claude writes SVG/HTML code that renders as an image, which is not generation. Route to Gemini/OpenAI/specialists (1.2).
"Imagen is Google's image API." Imagen is shut down in the Gemini API; Nano Banana models replaced it. Older tutorials are stale (4.1).
"Midjourney has an API you can buy." No official public API exists (Nov 2026); third-party "APIs" violate ToS. Web product or enterprise application only (6.4).
"gpt-image-1 is the current OpenAI image model." Shut down 23 Oct 2026; use gpt-image-2.5-* or gpt-image-2.6-* (3.1).
"Quality high always costs the same per image." Per-token pricing means cost varies with size × quality × model; read usage, not tables (10.1).
"A mask guarantees only that region changes." GPT Image masks are prompt-based hints; the model re-renders everything — specify what stays fixed and verify (8.2).
"Partial images are free previews." Each costs +100 image-output tokens on OpenAI (3.5).
"C2PA and SynthID are the same thing." C2PA = signed metadata (strippable); SynthID = watermark in pixels (survives some transforms). OpenAI embeds both; Google embeds SynthID (11.4).
"moderation: low removes safety filtering." It relaxes filtering but does not switch it off, so output filtering still applies, and your own duty of care doesn't change (11.1).
"Retries fix a bad image." A garbled-text or wrong-count failure is prompt/model-bound; bound retries and escalate quality or route to review (9.1).
"Seeds make generations reproducible." Seeds (where supported) give similarity, not identity — and OpenAI/Gemini don't document seeds for their APIs (7.5).

Key takeaways#

  • Two big providers, one shape: OpenAI (GPT Image 2.5/2.6 via Image API or Responses tool) and Google (Nano Banana 2.1/Pro/Lite via Interactions or generate_content) cover most needs; Anthropic does no image generation; OpenRouter's Image API normalizes many vendors behind /api/v1/images.
  • Ask the catalogue, don't guess: OpenRouter's /images/models + per-endpoint records give authoritative supported_parameters and pricing[] — build a capability registry like 03.11's.
  • Price per accepted image: per-token billing (OpenAI, Gemini) hides cost in size×quality×refs; partials, retries, validation calls and orchestrator tokens all add up — track usage/cost per request.
  • Editing is conditioning: masks, markup, references and conversation context all feed the same generative process; multi-turn editing beats re-prompting for consistency.
  • Pipeline, not endpoint: generate → VLM-validate (bounded retries) → Pillow post-process → store with provenance metadata is the production shape.
  • Provenance is real now: OpenAI embeds C2PA+SynthID, Google SynthID; specialists mostly don't — store what you can verify and disclose AI-generation to users.
  • Safety is your job too: moderation errors are typed outcomes to handle gracefully; likeness, children, copyright and abuse prevention are product requirements, not afterthoughts.

Terms introduced in this lesson#

Term One-line definition
Text-to-image (T2I) model A generative model that produces an image from a text prompt
Image editing / image-to-image Generating a new image conditioned on one or more input images plus a prompt
GPT Image family OpenAI's image models: the current gpt-image-2.6-* pair and the -2.5-* pair, plus older gpt-image-2, -1.5 and -1-mini, which are on the deprecation list
Nano Banana Google's consumer name for its Gemini image-generation models
Image API (OpenAI) POST /v1/images/generations and /v1/images/edits — direct single-shot calls
image_generation tool The Responses API built-in tool letting a mainline model generate/edit images in conversation
image_generation_call The Responses output item carrying a generated image's base64 result and revised_prompt
Partial image A progressive low-quality render streamed mid-generation (+100 tokens each on OpenAI)
revised_prompt The prompt the image model actually used after the orchestrating model rewrote it
Mask / inpainting An alpha-channel image marking the region to edit; transparent areas get regenerated
Markup-guided edit Editing steered by a transparent annotation overlay (circles/arrows) instead of a mask
Reference images Input images conditioning style/content/identity (up to 16 OpenAI, 14 Gemini)
image_config / ImageConfig Gemini's generate_content config for aspect_ratio + image_size
response_format (image) Gemini Interactions' output spec: {"type":"image","aspect_ratio","image_size"}
SynthID Google's invisible pixel watermark on all Gemini-generated images
C2PA Content Credentials Signed provenance metadata manifest embedded in media files
Content Provenance API OpenAI's POST /v1/content_provenance_checks for verifying C2PA/SynthID signals
Dedicated Image API (OpenRouter) POST /api/v1/images + /api/v1/images/models discovery — normalized multi-vendor image generation
supported_parameters OpenRouter's typed capability descriptors (enum/range/boolean) per model/endpoint
Polling URL / webhook Async job patterns: poll a status URL or receive a signed POST on completion
Per-image vs per-token pricing The two billing shapes: fixed unit price vs token-metered output
Diffusion model Iterative denoising generative architecture behind most specialist image models
Semantic negative prompt Expressing exclusions positively ("empty street") since most APIs lack negative_prompt
complexity GPT Image 2.6's planning-effort parameter (low/medium/high, default high), independent of quality and free
prompt_rewriter OpenAI's internal prompt-rewrite step (visible as revised_prompt); barred from markup/SVG/GIF combos — not a settable Images-API field
svg authoring object svg.model + svg.reasoning.effort on gpt-image-2.6: selects the model and reasoning effort that writes SVG output from a reference image
frame_count / frame_duration_ms GIF-only parameters on gpt-image-2.6 (2–16 frames, default 9; ≥20 ms per frame, default 200)

All terms are also collected in the glossary.


Exercises#

  1. Keyless post-processing (9.3): extend s9_3_ppm_png.py to (a) crop a region before thumbnailing, (b) convert the PNG output to a PPM again, and (c) compute the compression ratio vs the raw PPM. What does that tell you about why providers' PNGs are large?
  2. Cost model (10.1): add a batch_discount parameter and a validation_calls counter to cost_per_image; compute the true cost of "generate → validate → 1 retry" for 1,000 images on OpenAI high vs Gemini NB 2 Lite. Which assumptions move the result most?
  3. Discovery-driven client (5.2): write can_generate(model_entry, params) that validates a request dict against an OpenRouter supported_parameters map — reject image_size on a model whose params only list resolution, allow seed only where it's a boolean descriptor.
  4. Prompt scaffold (7.5): write a build_series_prompt(base, variant) function that locks subject/style/lighting clauses and swaps only the headline slot; generate 5 variant prompts for a thumbnail series and diff them.
  5. Mask builder (8.2): with Pillow, write box_mask(w, h, x, y, bw, bh, dilation) returning an RGBA PNG where the box interior is transparent; verify the alpha channel visually.
  6. Error handling (3.6): write handle_image_error(exc) that inspects an OpenAI BadRequestError for error.code == "moderation_blocked", extracts moderation_details, and returns a user-facing hint per moderation_stage — unit-test it with a fabricated exception body.
  7. Provider bake-off (12.5): pick 5 prompts from the gallery in 7.7; for each provider you can access, generate at the cheapest quality tier and score against a 5-item rubric. Record cost/image from usage/cost fields — this is your Module 10A eval seed.
  8. Provenance audit (11.4): take one generated image per provider you used; check for C2PA (exiftool/c2pa readers) and SynthID; record findings in a table — which signals survived your post-processing?
Hints for the exercises
  1. The writer in s9_3_ppm_png.py only emits filter type 0, so reading its own PNG back needs just zlib.decompress and a loop that skips one filter byte per scanline. Photographic PNGs from providers are large because lossless compression cannot discard the noise-like detail in real renders; a flat test image compresses far better than a generated photograph.
  2. Cost of one accepted image is (1 + retry_rate) × (generate + validation_call), so with one retry on every image, cost_per_image doubles before validation is added. The assumptions that move the result most are the output-token estimate (4,000 for OpenAI is a guess) and the retry rate; measure both from usage.
  3. Loop over the request keys: reject a key that is absent from supported_parameters; for enum check the value is in values; for range check min <= value <= max; for boolean accept only True or False.
  4. Keep SCAFFOLD = "{subject}, {style}, {lighting}" fixed and format only headline. A line-by-line diff of the five prompts should differ only in the headline slot.
  5. Start with Image.new("RGBA", (w, h), (0, 0, 0, 255)) (opaque, keep) and paste a fully transparent rectangle (x - d, y - d, x + bw + d, y + bh + d) for the editable region; clamp the dilated box to the image.
  6. Read exc.body["error"] (or exc.response.json()), compare code to "moderation_blocked", then map moderation_stage: input means "reword the request", output means "try a different description", anything else a generic retry-later message. Build the fabricated body as a plain dict.
  7. Use the same rubric for every provider (subject, text legibility, count, brand colours, artefacts) and write the cost from the response (usage or OpenRouter's usage.cost), not from the pricing table.
  8. Expect C2PA to disappear after any Pillow re-save and SynthID to survive mild resizing; the table should record the original file and the processed file separately.

Check yourself#

  1. Name the two OpenAI APIs for image generation and when you'd pick each.
  2. What happened to gpt-image-1 and DALL·E on OpenAI, and when?
  3. Which Gemini models form the Nano Banana family today, and which is recommended for new projects?
  4. Why is Imagen absent from current Gemini docs?
  5. Does Anthropic offer image generation? Cite the basis for your answer.
  6. How do you discover which parameters an OpenRouter image model accepts?
  7. What's the difference between OpenRouter's resolution and size parameters?
  8. Why might quality: "low" cost 10× less than quality: "max" on the same model?
  9. What does partial_images: 2 cost beyond the final image on OpenAI?
  10. List three things that make GPT Image edits expensive beyond the base generation.
  11. What are the constraints on an OpenAI edit mask (format, size, semantics)?
  12. How is markup-guided editing different from mask editing, and what can't you combine it with?
  13. Why is multi-turn editing more consistent than re-prompting from scratch?
  14. What does revised_prompt tell you, and why does it matter for logging?
  15. Name two ways Gemini images carry provenance that Stability/BFL images don't.
  16. What's the difference between C2PA Content Credentials and SynthID?
  17. What should a moderation_blocked error trigger in your code — and what shouldn't it trigger?
  18. Sketch the four-stage production pipeline and what each stage is responsible for.

Further resources#


← 09.2 — Document Understanding with Vision Models | Module 09 overview | 09.4 — Speech-to-Text →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close