Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

feat(openai): the image report carries the response's x-ratelimit-* headers — extra.rate_limit

Soohong Kim6676fed8821a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 53d84c7..a421dc4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
- **Fix: a poll xAI answers 429 or 5xx asks the same request again — the clip is bought once.** `video`, `video-extend` and `video-edit` ended the run on any non-2xx poll, after xAI had accepted the request and may bill it, and the line read `(HTTP 429)` — what `video-set`, and any caller that backs off on a refused submission, answers by submitting the clip again: a second clip paid for, the first never published. A poll answered `429`, `500`, `502`, `503` or `504` is now asked again on the same `request_id`, after a wait that doubles from 8 s up to 60 s while the polls are refused and goes back to 4 s on an answer; a stderr note says each, the status in plain digits. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`) still bounds the whole poll: no wait runs past it, a pending poll's last wait included, and one last poll is asked at it. A refused POST is still never sent again, and a `400`, `401` or `404` poll still ends the run with its status.
- **Output change: a generation the poll timeout cut short is unfinished, named by its `request_id`.** Polls still pending or still refused at the timeout end the run with a line that names `request_id=<id>`, says the generation may still finish and be billed, and carries no `(HTTP <n>)` — that marks a refused submission, which a caller may send again unbilled. The pending line keeps its front (`still 'pending' after N polls — poll timeout;`). With `--report` the run leaves a `sprite-gen-video-unfinished` report there (`verb`, `auth_source`, `model`, `request_id`, `out`, `polls`, `polls_refused`, `last_poll`, `elapsed_seconds`) and prints nothing on stdout; Python callers catch `GenerationUnfinished`, a `SystemExit`. The success report gains `polls_refused`, how many of its `polls` xAI answered 429 or 5xx (docs/video.md, An unfinished generation).
- **`tests/gen/test_video.py`** scripts the polls: each of the five statuses refused twice, then pending, then done, is asked on the one request with waits 8, 16, 4 and published with `polls_refused` 2; polls refused until a 300 s timeout wait 8, 16, 32, 60 × 4 and 4, ask a ninth poll at the timeout and end unfinished with no `(HTTP n)` and no `HTTP 429` on stderr; a pending timeout names the request; a 400, 401 or 404 poll ends at once; a refused POST is sent once; the CLI leaves the unfinished report and an empty stdout. The 500-poll case of the failure table is a 404 now, the status that still ends a run.
+- **Output change: an `openai` image report carries the response's rate-limit headers — `extra.rate_limit`.** The provider dropped the response headers, so what the account may spend per minute and has left could not be read off real traffic. `extra.rate_limit` now holds every `x-ratelimit-*` header the response carried, names lower-cased and values as sent, and `{}` when none came (docs/gen.md). `openai_provider.http_image` returns the response headers as a third value.
+- **`tests/gen/test_openai_provider.py`** answers with headers: the report holds exactly the `x-ratelimit-*` ones among others of any case, and `{}` for a response without any.
## v2.44.0 - A filmed ghost in a loop delivered as cut is given way, or named a take to film again; restoration reads the ghost; the RIFE lane runs every real-RIFE test
diff --git a/docs/gen.md b/docs/gen.md
index 8137aaa..a0eae18 100644
--- a/docs/gen.md
+++ b/docs/gen.md
@@ -174,9 +174,13 @@ covers the body, exactly as codex `image_gen` does — downstream extraction tre
`alpha ≤ 16` as transparent, so this is usable as-is).
Image reports include `extra.auth_source`, `extra.transport: "openai-api"`,
-`extra.endpoint`, `extra.quality`, `extra.size`, `extra.background` and, when the
+`extra.endpoint`, `extra.quality`, `extra.size`, `extra.background`, when the
API returns it, `extra.usage` (token counts only — what the call cost, never what it
-contained).
+contained), and `extra.rate_limit`: every `x-ratelimit-*` header the response carried,
+names lower-cased and values as sent (`{"x-ratelimit-remaining-requests": "49", …}`),
+`{}` when none came. OpenAI's rate-limits guide names request, token and project-token
+limits there and lists images per minute among the limits without naming a header for
+it, so whatever the images endpoints send is what the report holds.
API contract: [OpenAI Images](https://developers.openai.com/api/images/) (field names
and enums confirmed there 2026-09-20).
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
index 3152821..0d01201 100644
--- a/sprite_gen/gen/openai_provider.py
+++ b/sprite_gen/gen/openai_provider.py
@@ -94,6 +94,12 @@ _REFERENCE_MIMES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp
# drawn image was blocked. Only these documented values reach the line.
MODERATION_STAGES = ("input", "output", "unknown")
+# The account's limits and what is left of them ride on the response as `x-ratelimit-*`
+# headers (rate-limits guide, 2026-10-10: requests, tokens and project tokens — limit,
+# remaining, reset). It lists images per minute among the limits but names no header for it
+# and no endpoint that sends them, so the report keeps every `x-ratelimit-*` that came.
+RATE_LIMIT_HEADER_PREFIX = "x-ratelimit-"
+
def resolve_credential(env: dict[str, str] | None = None) -> str:
"""Return the OpenAI API key, or fail loud naming the variable that is missing."""
@@ -207,8 +213,8 @@ def _multipart_request(fields: dict[str, str], refs: list[Path]) -> tuple[bytes,
return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
-def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout: float) -> tuple[int, Any]:
- """POST an images request and return (status, parsed JSON).
+def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout: float) -> tuple[int, Any, Any]:
+ """POST an images request and return (status, parsed JSON, response headers).
A transport error is terminal: the server may already have accepted and billed
the request, so it is never retried here.
@@ -220,21 +226,27 @@ def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout:
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
raw = response.read().decode("utf-8")
- return response.status, (json.loads(raw) if raw else {})
+ return response.status, (json.loads(raw) if raw else {}), response.headers
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
raise SystemExit("openai-gen: response was not valid JSON") from exc
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8", "replace")
try:
- return exc.code, json.loads(raw)
+ return exc.code, json.loads(raw), exc.headers
except json.JSONDecodeError:
- return exc.code, refusal.RawBody(raw)
+ return exc.code, refusal.RawBody(raw), exc.headers
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise SystemExit(
"openai-gen: request failed or timed out; no automatic retry (the server may have accepted it)"
) from exc
+def rate_limit_headers(headers: Any) -> dict[str, str]:
+ """The response's `x-ratelimit-*` headers, names lower-cased and values as sent; {} when none came."""
+ return {name.lower(): value for name, value in headers.items()
+ if name.lower().startswith(RATE_LIMIT_HEADER_PREFIX)}
+
+
def _refusal(reply: Any) -> refusal.Refusal:
error = reply.get("error") if isinstance(reply, dict) else None
moderation = error.get("moderation_details") if isinstance(error, dict) else None
@@ -265,9 +277,9 @@ class OpenAIProvider:
from . import facing_vision as vision
token = resolve_credential()
announce_api_billing(self.name, AUTH_ENV, " (facing vision check).")
- status, reply = http_image(API_BASE + "/responses", token,
- json.dumps(vision.request_body(path, vision.OPENAI_MODEL)).encode("utf-8"),
- "application/json", timeout=GEN_TIMEOUT_SECONDS)
+ status, reply, _headers = http_image(API_BASE + "/responses", token,
+ json.dumps(vision.request_body(path, vision.OPENAI_MODEL)).encode("utf-8"),
+ "application/json", timeout=GEN_TIMEOUT_SECONDS)
text, metadata = vision.response_text(status, reply)
return text, {**metadata, "auth_source": AUTH_SOURCE_API_KEY, "transport": "openai-api"}
@@ -287,7 +299,7 @@ class OpenAIProvider:
f" (model={fields['model']}, quality={fields['quality']}, size={fields['size']}).",
)
started = time.monotonic()
- status, reply = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)
+ status, reply, headers = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)
# The provider's code (and the moderation stage) go in front, format-checked;
# the body the provider sent goes last, as received, with keys and URL
# query strings masked (refusal.said).
@@ -320,5 +332,6 @@ class OpenAIProvider:
"background": fields["background"],
# Token counts only — what the call cost, never what it contained.
**({"usage": usage} if isinstance(usage, dict) else {}),
+ "rate_limit": rate_limit_headers(headers),
},
)
diff --git a/tests/gen/test_facing.py b/tests/gen/test_facing.py
index af84866..89c1b8e 100644
--- a/tests/gen/test_facing.py
+++ b/tests/gen/test_facing.py
@@ -184,7 +184,7 @@ def test_rest_vision_uses_same_provider_credential_once(monkeypatch, tmp_path, p
monkeypatch.setattr(openai_provider, "resolve_credential", lambda: "synthetic")
def http(url, token, data, content_type, **kw):
seen.append((url, token, json.loads(data)))
- return 200, vision_response()
+ return 200, vision_response(), {}
monkeypatch.setattr(openai_provider, "http_image", http)
backend = openai_provider.OpenAIProvider()
else:
@@ -209,7 +209,7 @@ def test_rest_rejection_is_unknown_without_retry(monkeypatch, tmp_path):
monkeypatch.setattr(openai_provider, "resolve_credential", lambda: "synthetic")
def http(*a, **kw):
calls.append(1)
- return 403, {"error": "sensitive"}
+ return 403, {"error": "sensitive"}, {}
monkeypatch.setattr(openai_provider, "http_image", http)
report = facing.inspect(openai_provider.OpenAIProvider(), FIXTURES / "left.png", tmp_path)
assert len(calls) == 1 and report["direction"] == "unknown"