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(gen): a refusal names the provider's code, and says when it was the content policy

Soohong Kimb255e5a40d71
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index b68e9b3..08857ab 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -17,7 +17,7 @@ from pathlib import Path
from PIL import Image, UnidentifiedImageError
-from . import xai
+from . import refusal, xai
from .base import (
GEN_TIMEOUT_SECONDS,
RESOLUTIONS,
@@ -143,16 +143,21 @@ class GrokProvider:
started = time.monotonic()
status, reply = xai.http_json("POST", xai.API_BASE + endpoint, credential.token,
body, timeout=GEN_TIMEOUT_SECONDS)
+ # Error bodies can include prompts, credentials or URLs; do not echo them.
+ # Only the provider's code leaves, format-checked. The REST image answer
+ # has no moderation field (docs.x.ai reference; a 2026-09-30 probe's items
+ # carried `b64_json` and `mime_type` only), so a code is all there is.
+ refused = refusal.read(self.name, reply) if status != 200 else None
if status in (401, 403):
remedy = (f"run `{xai.GROK_LOGIN_COMMAND}` to renew the login" if credential.source == xai.AUTH_SOURCE_GROK_LOGIN
else f"check {xai.AUTH_ENV}")
- raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}); {remedy}")
- # Error bodies can include prompts, credentials or URLs; do not echo them.
- # The one thing worth naming is the combination the docs scope to
+ raise SystemExit(f"grok-gen: credential {credential.source} rejected (HTTP {status}){refused.suffix()}; {remedy}")
+ # The one other thing worth naming is the combination the docs scope to
# grok-imagine-image-2.0, which another model is entitled to reject.
- if status != 200:
+ if refused is not None:
scoped = f" (sent with {priced}, documented for {DEFAULT_MODEL})" if priced and body["model"] != DEFAULT_MODEL else ""
- raise SystemExit(f"grok-gen: image request failed (HTTP {status}); no retry or provider fallback{scoped}")
+ raise SystemExit(f"grok-gen: {refused.reason('image request failed')} (HTTP {status}){refused.suffix()}; "
+ f"no retry or provider fallback{scoped}")
items = reply.get("data") if isinstance(reply, dict) else None
if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
raise SystemExit("grok-gen: expected exactly one image in the response; nothing published")
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
index caf0ea2..1f23e3e 100644
--- a/sprite_gen/gen/openai_provider.py
+++ b/sprite_gen/gen/openai_provider.py
@@ -39,6 +39,7 @@ from typing import Any
from PIL import Image, UnidentifiedImageError
+from . import refusal
from .base import (
GEN_TIMEOUT_SECONDS,
QUALITIES,
@@ -88,6 +89,11 @@ DEFAULT_SIZE = SIZES["1:1"]
_REFERENCE_MIMES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}
+# `error.moderation_details.moderation_stage` on a `moderation_blocked` answer
+# (image-generation guide, 2026-09-30): whether the prompt/input images or the
+# drawn image was blocked. Only these documented values reach the line.
+MODERATION_STAGES = ("input", "output", "unknown")
+
def resolve_credential(env: dict[str, str] | None = None) -> str:
"""Return the OpenAI API key, or fail loud naming the variable that is missing."""
@@ -229,6 +235,14 @@ def http_image(url: str, token: str, data: bytes, content_type: str, *, timeout:
) from exc
+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
+ stage = moderation.get("moderation_stage") if isinstance(moderation, dict) else None
+ details = (("moderation_stage", stage),) if stage in MODERATION_STAGES else ()
+ return refusal.read("openai", reply, details)
+
+
def _publish_image(item: dict, path: Path) -> None:
# gpt-image models always answer with inline base64 — no signed URL to follow
# and no bearer token to forward.
@@ -274,14 +288,19 @@ class OpenAIProvider:
)
started = time.monotonic()
status, reply = http_image(API_BASE + endpoint, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS)
+ # Error bodies can echo the prompt, a key or a signed URL; do not print them.
+ # Only the provider's code (and the moderation stage) leave, format-checked.
+ refused = _refusal(reply) if status != 200 else None
if status in (401, 403):
raise SystemExit(
- f"openai-gen: credential {AUTH_SOURCE_API_KEY} rejected (HTTP {status}); "
+ f"openai-gen: credential {AUTH_SOURCE_API_KEY} rejected (HTTP {status}){refused.suffix()}; "
f"check the key's value and that its project may call {fields['model']}"
)
- # Error bodies can echo the prompt, a key or a signed URL; do not print them.
- if status != 200:
- raise SystemExit(f"openai-gen: image request failed (HTTP {status}); no retry or provider fallback")
+ if refused is not None:
+ raise SystemExit(
+ f"openai-gen: {refused.reason('image request failed')} (HTTP {status}){refused.suffix()}; "
+ "no retry or provider fallback"
+ )
items = reply.get("data") if isinstance(reply, dict) else None
if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
raise SystemExit("openai-gen: expected exactly one image in the response; nothing published")
diff --git a/sprite_gen/gen/refusal.py b/sprite_gen/gen/refusal.py
new file mode 100644
index 0000000..c895c5c
--- /dev/null
+++ b/sprite_gen/gen/refusal.py
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: Apache-2.0
+"""What a provider refusal line may say about why the provider refused.
+
+Error bodies stay unprinted on the image paths: they can echo the prompt, a key or
+a signed URL. The one field worth carrying out is the provider's own machine code
+(`error.code`, which OpenAI's image guide calls the stable discriminator), and only
+when it looks like an identifier — anything else could be prose from the body.
+
+The line shape is a contract other programs read:
+
+ <verb>: <reason> (HTTP <n>) code=<code>[ key=value ...]<tail>
+
+`(HTTP <n>)` stays exactly that — callers find the provider status with
+`\\(HTTP (\\d{3})\\)` — and `code=` follows it after one space. When the code is
+one the provider documents as a content-policy block, `<reason>` is the fixed
+marker `CONTENT_POLICY`, so a caller can tell "change the request" from auth,
+quota or parameter errors without knowing any provider's vocabulary.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any
+
+CODE_PATTERN = re.compile(r"[A-Za-z0-9_.:-]{1,64}")
+
+CONTENT_POLICY = "refused by the provider's content policy"
+
+# Which provider codes are a content-policy block, per provider; the one table.
+# OpenAI images: `moderation_blocked` (developers.openai.com image-generation
+# guide, "Handling blocked requests", 2026-09-30). xAI has none: its documented
+# video failure code `invalid_argument` covers moderation and parameter errors
+# alike, so listing it would tell a caller with a bad parameter to change the
+# content. An xAI clip blocked by moderation is recognised by
+# `video.respect_moderation: false` instead (sprite_gen.gen.video).
+POLICY_CODES: dict[str, frozenset[str]] = {
+ "openai": frozenset({"moderation_blocked"}),
+ "grok": frozenset(),
+}
+
+
+def identifier(value: Any) -> str | None:
+ """`value` when it is a string shaped like a code, else None."""
+ return value if isinstance(value, str) and CODE_PATTERN.fullmatch(value) else None
+
+
+def provider_code(body: Any) -> str | None:
+ """The code of an error body: `error.code` when `error` is an object, else a top-level `code`.
+
+ OpenAI and a failed xAI video poll answer with an `error` object; xAI's
+ synchronous errors put `code` next to an `error` string.
+ """
+ if not isinstance(body, dict):
+ return None
+ error = body.get("error")
+ return identifier(error.get("code") if isinstance(error, dict) else body.get("code"))
+
+
+@dataclass(frozen=True)
+class Refusal:
+ code: str | None
+ policy: bool
+ details: tuple[tuple[str, str], ...] = ()
+
+ def reason(self, otherwise: str) -> str:
+ return CONTENT_POLICY if self.policy else otherwise
+
+ def suffix(self) -> str:
+ pairs = ((("code", self.code),) if self.code else ()) + self.details
+ return "".join(f" {key}={value}" for key, value in pairs)
+
+
+def read(provider: str, body: Any, details: tuple[tuple[str, str], ...] = ()) -> Refusal:
+ code = provider_code(body)
+ return Refusal(code=code, policy=code in POLICY_CODES[provider], details=details)
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 94812da..f937a0d 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -55,6 +55,7 @@ from pathlib import Path
from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text
+from . import refusal
from .base import announce_api_billing
from .facing import FACINGS, validate as validate_facing
from sprite_gen.video import facing as facing_mod
@@ -410,7 +411,10 @@ def _submit_poll_publish(
)
request_id = reply.get("request_id") if isinstance(reply, dict) else None
if status not in (200, 202) or not request_id:
- raise SystemExit(f"{verb}: generation request refused (HTTP {status}): {_error_detail(reply)}")
+ refused = refusal.read("grok", reply)
+ raise SystemExit(
+ f"{verb}: {refused.reason('generation request refused')} (HTTP {status}){refused.suffix()}: {_error_detail(reply)}"
+ )
deadline = time.monotonic() + (POLL_TIMEOUT_SECONDS if poll_timeout is None else poll_timeout)
polls = 0
@@ -425,13 +429,24 @@ def _submit_poll_publish(
if http in (200, 202) and poll_status in _DONE_STATUSES:
final = poll
video = poll.get("video") or {}
+ # docs.x.ai videos reference: `respect_moderation` is false (and the url
+ # empty) when the clip broke moderation rules — the one xAI signal that
+ # is a content-policy block and nothing else. No provider code exists.
+ if isinstance(video, dict) and video.get("respect_moderation") is False:
+ raise SystemExit(
+ f"{verb}: generation {request_id} {refusal.CONTENT_POLICY} (HTTP {http}) "
+ "respect_moderation=false; nothing was written"
+ )
video_url = video.get("url") if isinstance(video, dict) else None
duration_reported = video.get("duration") if isinstance(video, dict) else None
model_reported = poll.get("model")
break
if http not in (200, 202) or poll_status in _FAILED_STATUSES:
+ # A failed poll carries `error` as an object `{code, message}`.
+ refused = refusal.read("grok", poll)
raise SystemExit(
- f"{verb}: generation {request_id} ended with status={poll_status!r} (HTTP {http}): {_error_detail(poll)}"
+ f"{verb}: generation {request_id} {refused.reason(f'ended with status={poll_status!r}')} "
+ f"(HTTP {http}){refused.suffix()}: {_error_detail(poll)}"
)
if time.monotonic() >= deadline:
raise SystemExit(
diff --git a/tests/gen/test_grok_provider.py b/tests/gen/test_grok_provider.py
index b78e26b..f777112 100644
--- a/tests/gen/test_grok_provider.py
+++ b/tests/gen/test_grok_provider.py
@@ -311,3 +311,27 @@ def test_the_declared_subsets_are_the_servers_own_enums():
# one `--quality` / `--resolution` can actually pass in.
assert set(grok.SUPPORTED_QUALITIES) <= set(gen_base.QUALITIES)
assert set(grok.SUPPORTED_RESOLUTIONS) <= set(gen_base.RESOLUTIONS)
+
+
+# --- refusal lines: the provider code, never the body -----------------------------
+
[email protected]("body, suffix", [
+ ({"error": {"code": "invalid_argument", "message": "synthetic-secret"}}, " code=invalid_argument"),
+ ({"code": "invalid-argument", "error": "synthetic-secret"}, " code=invalid-argument"),
+ ({"error": "synthetic-secret"}, ""),
+ ({"code": "synthetic secret with spaces", "error": "synthetic-secret"}, ""),
+ # The policy table is per provider: OpenAI's code means nothing coming from xAI.
+ ({"error": {"code": "moderation_blocked"}}, " code=moderation_blocked"),
+])
+def test_a_refused_image_names_the_provider_code_only(tmp_path, api, body, suffix):
+ api.update(status=400, body=body)
+ with pytest.raises(SystemExit) as error:
+ gen.generate_image("grok", "x", tmp_path / "out.png")
+ assert str(error.value) == f"grok-gen: image request failed (HTTP 400){suffix}; no retry or provider fallback"
+
+
+def test_a_rejected_credential_names_the_code_too(tmp_path, api):
+ api.update(status=401, body={"code": "unauthenticated:bad-credentials", "error": "synthetic-secret"})
+ with pytest.raises(SystemExit) as error:
+ gen.generate_image("grok", "x", tmp_path / "out.png")
+ assert str(error.value) == "grok-gen: credential XAI_API_KEY rejected (HTTP 401) code=unauthenticated:bad-credentials; check XAI_API_KEY"
diff --git a/tests/gen/test_openai_provider.py b/tests/gen/test_openai_provider.py
index c5d37dc..b50810d 100644
--- a/tests/gen/test_openai_provider.py
+++ b/tests/gen/test_openai_provider.py
@@ -10,6 +10,7 @@ import base64
import io
import json
import os
+import re
import subprocess
import urllib.error
@@ -351,3 +352,62 @@ def test_a_grok_resolution_is_refused_rather_than_dropped(tmp_path, api):
assert "2k" in str(error.value)
assert api["calls"] == []
assert not (tmp_path / "out.png").exists()
+
+
+# --- refusal lines: the provider code, never the body -----------------------------
+
+HTTP_STATUS = re.compile(r"\(HTTP (\d{3})\)") # what a caller reads the status with
+
+
+def _refused(tmp_path, api, status, error):
+ api.update(status=status, body={"error": {"message": f"{KEY} synthetic prompt echo", **error}})
+ with pytest.raises(SystemExit) as refused:
+ gen.generate_image("openai", "x", tmp_path / "out.png")
+ message = str(refused.value)
+ assert KEY not in message and "prompt echo" not in message
+ assert HTTP_STATUS.search(message).group(1) == str(status)
+ assert len(api["calls"]) == 1
+ return message
+
+
[email protected]("details, stage", [
+ ({"moderation_details": {"moderation_stage": "output", "categories": ["other"]}}, " moderation_stage=output"),
+ ({"moderation_details": {"moderation_stage": "input"}}, " moderation_stage=input"),
+ ({"moderation_details": {"moderation_stage": "unknown"}}, " moderation_stage=unknown"),
+ ({}, ""),
+ ({"moderation_details": None}, ""),
+ ({"moderation_details": {"moderation_stage": "a sentence the body made up"}}, ""),
+])
+def test_a_content_policy_block_says_so_with_its_code(tmp_path, api, details, stage):
+ error = {"code": "moderation_blocked", "type": "image_generation_user_error", "param": None, **details}
+ assert _refused(tmp_path, api, 400, error) == (
+ f"openai-gen: refused by the provider's content policy (HTTP 400) code=moderation_blocked{stage}; "
+ "no retry or provider fallback"
+ )
+
+
+def test_another_code_keeps_the_plain_failure_and_names_the_code(tmp_path, api):
+ assert _refused(tmp_path, api, 400, {"code": "invalid_value", "param": "size"}) == (
+ "openai-gen: image request failed (HTTP 400) code=invalid_value; no retry or provider fallback"
+ )
+
+
[email protected]("error", [{}, {"code": None}, {"code": 400}, {"code": "has a space"},
+ {"code": "x" * 65}, {"code": ""}, {"code": "quote'd"}])
+def test_no_code_or_a_code_outside_the_format_leaves_the_line_as_it_was(tmp_path, api, error):
+ assert _refused(tmp_path, api, 400, error) == (
+ "openai-gen: image request failed (HTTP 400); no retry or provider fallback"
+ )
+
+
+def test_a_top_level_code_is_not_the_openai_error_code(tmp_path, api):
+ api.update(status=400, body={"code": "moderation_blocked", "error": {"message": "x"}})
+ with pytest.raises(SystemExit) as refused:
+ gen.generate_image("openai", "x", tmp_path / "out.png")
+ assert str(refused.value) == "openai-gen: image request failed (HTTP 400); no retry or provider fallback"
+
+
+def test_a_rejected_key_names_the_code_too(tmp_path, api):
+ assert _refused(tmp_path, api, 401, {"code": "invalid_api_key"}).startswith(
+ "openai-gen: credential OPENAI_API_KEY rejected (HTTP 401) code=invalid_api_key; check the key's value"
+ )
diff --git a/tests/gen/test_video.py b/tests/gen/test_video.py
index da0e4f2..fd23e5b 100644
--- a/tests/gen/test_video.py
+++ b/tests/gen/test_video.py
@@ -5,6 +5,7 @@ verified mp4 publishing, and loud failures. No network — the HTTP layer is a f
from __future__ import annotations
import json
+import re
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -427,3 +428,58 @@ def test_the_cli_announces_on_stderr_leaving_the_report_on_stdout(tmp_path: Path
assert len([line for line in captured.err.splitlines() if "per-call API charge" in line]) == 1
assert json.loads(captured.out)["auth_source"] == "XAI_API_KEY"
assert "console-key" not in captured.err + captured.out # the key itself is never printed
+
+
+# --- refusal lines: the provider code, and xAI's one content-policy signal ---------
+
+HTTP_STATUS = re.compile(r"\(HTTP (\d{3})\)") # what a caller reads the status with
+
+
+def _refused(tmp_path: Path, api: _FakeApi) -> tuple[str, Path]:
+ request = _request(tmp_path)
+ with pytest.raises(SystemExit) as refused:
+ video.generate_video(request, credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN), call=api.call, download=api.download, sleep=lambda s: None)
+ assert not request.out.exists() and not list(tmp_path.glob("*.part"))
+ assert api.downloads == []
+ return str(refused.value), request.out
+
+
+def test_a_moderated_clip_is_a_content_policy_refusal(tmp_path: Path) -> None:
+ api = _FakeApi(polls=[(200, {"status": "done", "video": {"url": "", "respect_moderation": False}})])
+ message, _ = _refused(tmp_path, api)
+ assert message == ("video: generation req-1 refused by the provider's content policy (HTTP 200) "
+ "respect_moderation=false; nothing was written")
+ assert HTTP_STATUS.search(message).group(1) == "200"
+
+
+def test_a_moderated_clip_is_refused_even_if_a_url_came_back(tmp_path: Path) -> None:
+ api = _FakeApi(polls=[(200, {"status": "done", "video": {"url": "https://vidgen.x.ai/v/1.mp4", "respect_moderation": False}})])
+ assert "refused by the provider's content policy" in _refused(tmp_path, api)[0]
+
+
+def test_a_clip_that_respects_moderation_publishes(tmp_path: Path) -> None:
+ api = _FakeApi(polls=[(200, {"status": "done", "video": {"url": "https://vidgen.x.ai/v/1.mp4", "duration": 6.0, "respect_moderation": True}})])
+ request = _request(tmp_path)
+ video.generate_video(request, credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN), call=api.call, download=api.download, sleep=lambda s: None)
+ assert request.out.read_bytes() == MP4
+
+
+def test_a_failed_poll_names_the_code_inside_its_error_object(tmp_path: Path) -> None:
+ """`invalid_argument` covers moderation and bad parameters alike, so it is a code, not a policy verdict."""
+ api = _FakeApi(polls=[(200, {"status": "failed", "error": {"code": "invalid_argument", "message": "synthetic"}})])
+ message, _ = _refused(tmp_path, api)
+ assert message.startswith("video: generation req-1 ended with status='failed' (HTTP 200) code=invalid_argument: ")
+ assert "content policy" not in message
+
+
[email protected](("post", "prefix"), [
+ ((400, {"code": "invalid-argument", "error": "synthetic"}), "video: generation request refused (HTTP 400) code=invalid-argument: "),
+ ((400, {"error": {"code": "invalid_argument", "message": "synthetic"}}), "video: generation request refused (HTTP 400) code=invalid_argument: "),
+ ((400, {"error": "synthetic"}), "video: generation request refused (HTTP 400): "),
+ ((400, {"code": "not a code", "error": "synthetic"}), "video: generation request refused (HTTP 400): "),
+ ((429, {"error": {"code": "x" * 65}}), "video: generation request refused (HTTP 429): "),
+])
+def test_a_refused_request_names_a_well_formed_code(tmp_path: Path, post, prefix) -> None:
+ message, _ = _refused(tmp_path, _FakeApi(post=post))
+ assert message.startswith(prefix)
+ assert HTTP_STATUS.search(message).group(1) == str(post[0])