import time, random, httpx
def submit_with_retry(payload, max_attempts=5):
for attempt in range(max_attempts):
try:
r = httpx.post(f"{HOST}/v1/midjourney/generations/imagine",
json=payload,
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=30)
data = r.json()
if r.status_code == 200 and data["code"] in (1, 200):
return data
if data["code"] in (4, 24):
raise ValueError(data["description"]) # リトライ不可
if data["code"] == 3 and "task" in data["description"]:
raise ValueError(data["description"]) # task_id が存在しない
# その他(9 / 429 / 5xx)はリトライ可
except httpx.RequestError:
pass
time.sleep((4 ** attempt) + random.uniform(0, 1)) # 1s / 4s / 16s ...
raise RuntimeError(f"最大リトライ回数に到達 {max_attempts}")