AI image budget guard in Python: stop when usage.cost passes a limit

Each Sume image response reports usage.cost in USD. Add it up in a loop and stop a bulk run at a cap you set, so a stuck prompt cannot drain credits.

4 min readSume
All posts

Stop a bulk image run by summing usage.cost from every response and breaking when the total passes your cap. Sume reports the amount billed for each generation in USD, and failed or cancelled generations are not billed, so the running total is a reliable ledger for one script (Image API docs, errors docs).

This is a client-side guard. It does not replace your plan's credits, but it keeps a loop that retries a hard prompt from spending more than you intended.

Which responses should I count?

Only what the API reports.

What to do with each result, read 2026-10-01
ResultBilled?Guard action
200 with imageYes, usage.costAdd to total
202 job envelopePendingPoll, then add the final cost
402 insufficient_creditsNoStop the run
429 queue_full or rate_limitedNoWait, then retry
503 provider_capacity_exceededNoTry later or another model

What does the guard look like?

It handles the sync 200 path and stops on 402.

import os
import requests

H = {"Authorization": f"Bearer {os.environ['SUME_API_KEY']}"}
CAP = 1.00
spent = 0.0

for prompt in ["red bicycle", "blue bicycle", "green bicycle"]:
    r = requests.post("https://api.sume.com/v1/images", headers=H, timeout=60,
        json={"model": "openai/gpt-image-2.5", "quality": "low",
              "prompt": prompt})
    if r.status_code == 402:
        print("out of credits")
        break
    if r.status_code == 200:
        spent += r.json()["usage"]["cost"]
    print(prompt, r.status_code, round(spent, 4))
    if spent >= CAP:
        print("cap reached")
        break

What about async jobs?

A 202 response has no final cost yet. Fetch the job result once result_ready is true and add the billed amount it reports then (the 202 envelope itself carries no usage.cost). Until then, count a worst-case estimate if your cap must be strict, remembering that auto quality reserves the max amount.

Choosing the cap

Set the cap from the job, not from your balance. Multiply the number of images you expect by the cost of one test image, then add a margin of 20 percent for retries. Run two or three images first and print usage.cost, so the margin is built on a real number from the live price rather than a guess.

Log each prompt with its cost to a file. When a run stops at the cap, you can see which prompts were the expensive ones and whether quality or size should come down for the next pass.

Limits

A cap checked after each call can overshoot by one image. With concurrent workers, share the total behind a lock. The guard sees only this script, not other keys on your account, so also watch the balance in the dashboard.

Sources

Related posts

More in Pricing

All Pricing posts

Written by Sume