- A failed or timed-out request is not charged; when only some images of a request succeed, only those are charged.
- Send an
Idempotency-Key header when you retry: a request with the same key is never run twice or charged twice. - On a 429, wait and try again, doubling the wait each time.
- Ask for links with
response_format: "url". A link works for 72 hours, so copy the files to your own storage.
import asyncio
from openai import AsyncOpenAI, RateLimitError
client = AsyncOpenAI(base_url="https://api.cheapestimagen.com/v1", api_key="YOUR_KEY")
gate = asyncio.Semaphore(50) # the account limit on requests in progress
async def make(prompt: str, key: str):
async with gate:
for attempt in range(5):
try:
r = await client.images.generate(
model="nano-banana-2.1", prompt=prompt, size="1024x1024", response_format="url",
extra_headers={"Idempotency-Key": key}, # a retry never charges twice
)
return r.data[0].url
except RateLimitError:
await asyncio.sleep(2 ** attempt)
async def main(prompts):
return await asyncio.gather(*(make(p, f"job-{i}") for i, p in enumerate(prompts)))
The limits are set out in Rate limits and bulk generation and every error code in the errors guide. To run it in n8n, see Use with n8n.