- 失败、超时的请求不扣积分;一次请求里只成功了一部分,只扣成功的那几张。
- 重试时带上
Idempotency-Key 请求头:同一个键的请求不会被执行两次,也不会扣两次。 - 遇到 429 就等一会儿再试,间隔逐次加倍。
- 结果用
response_format: "url" 拿链接,链接保留 72 小时,请及时下载到自己的存储。
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)))
限制的完整说明见调用限制和批量生成,所有错误码见错误说明。在 n8n 里跑见 n8n 接入。
在国内接入、不确定怎么选服务商时,可以先看 API 接入指南,以及 API 中转的说明。