Sub topic 12
Scaling up with batches and APIs
This chapter assumes you can already write a prompt from a creative brief, iterate on it one change at a time, and export files for each channel. Basic Python helps for the code, but the ideas apply to any scripting language.
Most campaigns don't need automation. Once you need dozens of variants, such as ten products in four scenes each, or the same hero image in several seasonal palettes, clicking through a web interface becomes slow and error-prone. Batches and APIs let you generate by script. The trade-off is that you also lose the human eye you had on every single image, so the review step matters more.
When to automate
Automate when the work is repetitive and the brief is stable. Don't automate while you are still discovering what works.
- Good fit: product catalogs, localized variants, seasonal refreshes, A/B test sets, and resizing pipelines.
- Poor fit: a single hero image, a new visual style, or anything that needs heavy back-and-forth editing.
A practical rule: finish the iteration workflow by hand first. Once one prompt reliably gives approved results, turn it into a template and scale it.
How API generation works
Most image services expose the same basic pattern, even though the field names differ.
- You send a request with a prompt and options such as size, number of images, and sometimes a seed.
- The service either returns the image directly (synchronous) or returns a job ID that you poll until the image is ready (asynchronous).
- You download or decode the result and save it.
Some providers also offer a batch endpoint. You submit many requests at once, and results come back later, often at a lower price per image. This suits overnight jobs but not live iteration.
Check your provider's documentation for the exact parameters. Names, limits, and supported options change often, and not every tool supports every option. Seeds are a common example: some tools honor them, and others ignore them.
Build jobs from structured fields
The first code example in this tutorial kept the brief as fields and assembled the prompt from them. That structure is what makes batching safe. You change one field at a time, such as the scene, and everything else stays fixed. A job is then a small record: the assembled prompt, a seed, and an ID.
Make the job ID a hash of the inputs. The same inputs always give the same ID, so a rerun can skip work it has already finished.
A resilient batch script
The script below uses only the Python standard library. The generate_image function is a stand-in that returns placeholder bytes and randomly simulates rate-limit errors. Replace its body with a call to your provider's SDK or HTTP API, and keep the contract: return image bytes, and raise TransientError for rate limits (HTTP 429) and temporary server errors (5xx).
import hashlib
import json
import random
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
OUT_DIR = Path("batch_out")
MAX_WORKERS = 3 # stay under your provider's rate limit
MAX_RETRIES = 4
MAX_IMAGES = 20 # hard cap per run to protect your budget
STYLE = "clean product photography, soft natural light, shallow depth of field"
AVOID = "text, logos, people"
PRODUCT = "a stainless steel water bottle"
SCENES = [
"on a flat rock beside a mountain lake",
"on a wooden table in a sunlit kitchen",
"in a gym bag next to running shoes",
]
class TransientError(Exception):
"""Rate limit or temporary server error. Safe to retry."""
def generate_image(prompt, seed):
"""Replace this body with a real API call that returns image bytes."""
if random.random() < 0.2:
raise TransientError("simulated rate limit")
return f"placeholder for seed {seed}: {prompt}".encode("utf-8")
def make_job(scene, seed):
prompt = f"{PRODUCT} {scene}. {STYLE}. Do not include: {AVOID}."
job_id = hashlib.sha1(f"{seed}|{prompt}".encode("utf-8")).hexdigest()[:10]
return {"id": job_id, "prompt": prompt, "seed": seed}
def run_job(job):
path = OUT_DIR / f"{job['id']}.png"
if path.exists():
return {**job, "status": "skipped", "file": path.name}
for attempt in range(MAX_RETRIES):
try:
path.write_bytes(generate_image(job["prompt"], job["seed"]))
return {**job, "status": "ok", "file": path.name}
except TransientError:
time.sleep(2 ** attempt + random.random()) # exponential backoff
return {**job, "status": "failed", "file": ""}
def main():
OUT_DIR.mkdir(exist_ok=True)
jobs = [make_job(scene, seed) for scene in SCENES for seed in (1, 2, 3)]
jobs = jobs[:MAX_IMAGES]
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool:
results = list(pool.map(run_job, jobs))
(OUT_DIR / "manifest.json").write_text(json.dumps(results, indent=2))
failed = [r["id"] for r in results if r["status"] == "failed"]
print(f"{len(results)} jobs, {len(failed)} failed: {failed}")
main()The script has five safeguards, and each one answers a failure you will meet in real use:
- A worker limit keeps you under the provider's rate limit. Too many parallel requests produce 429 errors.
- Exponential backoff waits 1, 2, 4, then 8 seconds (plus a little random jitter) between retries, so a struggling service isn't hammered.
- Skipping existing files makes reruns safe. If the script crashes at job 14, you rerun it and only the missing jobs execute.
- A hard cap (
MAX_IMAGES) stops a bug in your loops from creating thousands of paid generations. - A manifest records what was requested and what came back.
What to record in the manifest
You can't review or reproduce a batch you can't trace. Save at least these fields for every image.
| Field | Why it matters |
|---|---|
| Job ID | Links the file to its request and lets reruns skip finished work |
| Full prompt text | Lets you reproduce or tweak the result |
| Seed and settings | Needed to regenerate a near-identical image when the tool supports seeds |
| Tool and model name | Models update, and the same prompt can look different later |
| Date and status | Shows which jobs failed or were skipped |
| Review decision | Records approval, rejection, and the reason |
The manifest also supports the legal and disclosure work covered later in this tutorial, because it documents how each image was made.
Cost, limits, and quotas
Automation makes spending easy to lose track of. Plan for these points before you run a large batch.
- Test with a tiny batch. Run three jobs, look at them, and only then scale up.
- Estimate cost first. Multiply the number of jobs by the per-image price, then add retries and the extra variants you will reject.
- Know your limits. Providers cap requests per minute and sometimes images per day. Read the quota page before you choose a worker count.
- Expect rejections. A content filter may refuse a prompt. Treat that as a failed job to log, not a reason to retry forever.
Automation does not replace review
A batch of 60 images will contain defects, such as extra fingers, garbled text on a label, a bottle with two handles, or a drifting color palette. The fix is not a smarter script. It is a review step designed for volume:
- Build a contact sheet or a simple folder view so you can scan many images at once.
- Check each image against a fixed checklist: anatomy and object shape, stray text, brand colors, and excluded elements.
- Record the decision in the manifest.
- Only approved images go on to resizing and export.
When the same defect appears in many images, fix the template or the exclusions and rerun only the affected jobs. The same cause usually produces the same defect everywhere.
Common errors
- Retrying everything. Retry only transient errors. A rejected prompt or an invalid parameter will fail every time.
- No idempotence. Without stable IDs, a rerun regenerates and pays for every image again.
- Assuming seeds guarantee identical output. Seed behavior depends on the tool and model version. Treat a seed as a way to get similar results, not a guarantee.
- Skipping the manifest. Weeks later, nobody can say which prompt produced the winning image.
- Resizing before review. Review first so you don't spend time exporting images you will reject.
Exercise
Your batch script crashes after finishing 14 of 30 jobs. You fix the bug and run it again. Which two design choices in the script above keep you from paying for the 14 finished images twice?
Show answer
The job ID is a hash of the seed and prompt, so the same job always maps to the same filename. Before calling the API, run_job checks whether that file already exists and skips the job if it does. Together, these make the rerun generate only the 16 missing images.
Exercise
The provider returns HTTP 429 for some requests when you run 10 workers. Name two changes that reduce the errors, and explain why you would not simply retry immediately in a tight loop.
Show answer
Lower the worker count, for example to 3, and add exponential backoff with random jitter between retries. An immediate retry loop sends even more requests while the service is already refusing them, which keeps you over the rate limit and can lengthen the block.
Exercise
A batch of 40 images shows the same defect in 12 of them: a garbled word on the bottle label. Should you fix them one at a time in an editor, or change something upstream? Give your reasoning.
Show answer
Change something upstream first. A repeated defect usually comes from the shared template, so add text to the exclusions or remove label detail from the prompt, then regenerate only the affected jobs. Brand text can be added afterwards in post-processing. Fixing 12 images by hand costs more and leaves the cause in place for the next batch.