Skip to content

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

refactor(gen): the HTTP providers' names openai, xai, anthropic and elevenlabs written once in gen.address and read by name in its registry, retry's tables, capabilities and every address and retry call

Soohong Kim8b9b52661f18
diff --git a/sprite_gen/audio/provider.py b/sprite_gen/audio/provider.py
index 2b4e55b..5846358 100644
--- a/sprite_gen/audio/provider.py
+++ b/sprite_gen/audio/provider.py
@@ -57,7 +57,7 @@ def _code(body):
def generate(document):
key = credential()
- req = Request(address.url('elevenlabs', f"/{document['endpoint']}?output_format={document['output_format']}"),
+ req = Request(address.url(address.ELEVENLABS, f"/{document['endpoint']}?output_format={document['output_format']}"),
data=json.dumps(document['body']).encode(),
headers={'xi-api-key': key, 'Content-Type': 'application/json'}, method='POST')
@@ -77,12 +77,12 @@ def generate(document):
announce_api_billing('elevenlabs', AUTH_ENV, f" ({document['endpoint']}; the audio is cached, so the same "
"request is not bought twice).")
- status, body, headers, asks = retry.ask(send, provider='elevenlabs', who='ElevenLabs', label='sound', kind=_code)
+ status, body, headers, asks = retry.ask(send, provider=address.ELEVENLABS, who='ElevenLabs', label='sound', kind=_code)
if not 200 <= status < 300:
raise ValueError(f'ElevenLabs refused sound (HTTP {status}, {_code(body) or "unclassified"}); {retry.tail(asks)}')
if not isinstance(body, bytes) or not body:
raise ValueError('ElevenLabs returned no audio; request outcome unresolved')
- meta = {'provider': 'elevenlabs', 'auth_source': AUTH_ENV, 'model': document['body']['model_id'], 'asks': asks}
+ meta = {'provider': address.ELEVENLABS, 'auth_source': AUTH_ENV, 'model': document['body']['model_id'], 'asks': asks}
# Only documented, constrained metadata; provider prose never enters a report or log.
for header, field in (('request-id', 'request_id'), ('song-id', 'song_id')):
value = headers.get(header, '')
diff --git a/sprite_gen/gen/address.py b/sprite_gen/gen/address.py
index 4412703..7ba8149 100644
--- a/sprite_gen/gen/address.py
+++ b/sprite_gen/gen/address.py
@@ -34,11 +34,16 @@ class Provider:
default: str # the documented API root, version path included
+# The four providers' names, each written once: the keys every caller and every table of them (`retry`,
+# `workflow.capabilities`) names a provider by. A host, not an image provider: `OPENAI` is the API sprite-gen calls,
+# `base.PROVIDER_OPENAI` the image provider that calls it, two names that happen to be spelled alike.
+OPENAI, XAI, ANTHROPIC, ELEVENLABS = "openai", "xai", "anthropic", "elevenlabs"
+
PROVIDERS = {provider.name: provider for provider in (
- Provider("openai", "SPRITE_GEN_OPENAI_BASE_URL", "https://api.openai.com/v1"),
- Provider("xai", "SPRITE_GEN_XAI_BASE_URL", "https://api.x.ai/v1"),
- Provider("anthropic", "SPRITE_GEN_ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"),
- Provider("elevenlabs", "SPRITE_GEN_ELEVENLABS_BASE_URL", "https://api.elevenlabs.io/v1"),
+ Provider(OPENAI, "SPRITE_GEN_OPENAI_BASE_URL", "https://api.openai.com/v1"),
+ Provider(XAI, "SPRITE_GEN_XAI_BASE_URL", "https://api.x.ai/v1"),
+ Provider(ANTHROPIC, "SPRITE_GEN_ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"),
+ Provider(ELEVENLABS, "SPRITE_GEN_ELEVENLABS_BASE_URL", "https://api.elevenlabs.io/v1"),
)}
FETCH_PATH = "/sprite-gen/fetch"
diff --git a/sprite_gen/gen/anthropic_api.py b/sprite_gen/gen/anthropic_api.py
index 3f4e6b6..e06d609 100644
--- a/sprite_gen/gen/anthropic_api.py
+++ b/sprite_gen/gen/anthropic_api.py
@@ -188,7 +188,7 @@ def _open(request_for: Callable[[], urllib.request.Request], token: str, *, time
raise _no_answer(exc) from exc
return response.status, response, response.headers
- status, answer, headers, _asks = retry.ask(send, provider="anthropic", who="claude", label=label, method=method,
+ status, answer, headers, _asks = retry.ask(send, provider=address.ANTHROPIC, who="claude", label=label, method=method,
sleep=sleep, kind=_error_type, deadline=deadline)
if 200 <= status < 300:
return answer
@@ -258,7 +258,7 @@ def stream_message(token: str, body: dict[str, Any], *, sleep: Sleep = time.slee
data = json.dumps({**body, "stream": True}).encode("utf-8")
timeout = READ_TIMEOUT_SECONDS if timeout is None else timeout
started = time.monotonic()
- response = _open(lambda: _request("POST", address.url("anthropic", "/messages"), token, data,
+ response = _open(lambda: _request("POST", address.url(address.ANTHROPIC, "/messages"), token, data,
accept="text/event-stream"),
token, timeout=timeout, sleep=sleep, label=label)
request_id = response.headers.get("request-id")
@@ -321,7 +321,7 @@ def submit_batch(token: str, requests: list[tuple[str, dict[str, Any]]], *, slee
label: str = "pixel-draw") -> dict[str, Any]:
"""Create one Message Batch of `(custom_id, params)` and return the batch object."""
body = {"requests": [{"custom_id": custom_id, "params": params} for custom_id, params in requests]}
- batch = _json_call("POST", address.url("anthropic", "/messages/batches"), token, body, sleep=sleep, label=label)
+ batch = _json_call("POST", address.url(address.ANTHROPIC, "/messages/batches"), token, body, sleep=sleep, label=label)
if not isinstance(batch, dict) or not isinstance(batch.get("id"), str):
raise ApiError("pixel-draw: the batch answer names no batch id")
return batch
@@ -330,7 +330,7 @@ def submit_batch(token: str, requests: list[tuple[str, dict[str, Any]]], *, slee
def get_batch(token: str, batch_id: str, *, sleep: Sleep = time.sleep, label: str = "pixel-draw",
deadline: float | None = None) -> dict[str, Any]:
"""The batch object; a refused read is asked again within `deadline` (the wait for the batch)."""
- batch = _json_call("GET", address.url("anthropic", f"/messages/batches/{batch_id}"), token, None, sleep=sleep,
+ batch = _json_call("GET", address.url(address.ANTHROPIC, f"/messages/batches/{batch_id}"), token, None, sleep=sleep,
label=label, deadline=deadline)
if not isinstance(batch, dict):
raise ApiError("pixel-draw: the batch status answer is not an object")
@@ -361,7 +361,7 @@ def batch_results(token: str, batch: dict[str, Any], *, sleep: Sleep = time.slee
if not isinstance(url, str) or not url:
raise ApiError(f"pixel-draw: batch {batch.get('id')} has ended but names no results_url")
# Anthropic's own host: through the Anthropic base when SPRITE_GEN_ANTHROPIC_BASE_URL is set (`address.fetched`).
- url = address.fetched("anthropic", url)
+ url = address.fetched(address.ANTHROPIC, url)
response = _open(lambda: _request("GET", url, token, None, accept="application/binary"),
token, timeout=120.0, sleep=sleep, label=label, method="GET", deadline=deadline)
try:
diff --git a/sprite_gen/gen/facing_vision.py b/sprite_gen/gen/facing_vision.py
index 2e71ce7..157d1a7 100644
--- a/sprite_gen/gen/facing_vision.py
+++ b/sprite_gen/gen/facing_vision.py
@@ -92,7 +92,7 @@ def grok_inspect(path: Path, *, credential=None, call=None, prompt: str = INSPEC
# The question's time limit is the transport's read timeout, from its first send: the waits before a
# refused one goes again count in it (`retry`), and each send reads only what is left of it.
send, deadline = call or xai.http_json, time.monotonic() + xai.HTTP_TIMEOUT_SECONDS
- status, reply, _sends = xai.post(lambda *a: send(*a, deadline=deadline), address.url("xai", "/responses"),
+ status, reply, _sends = xai.post(lambda *a: send(*a, deadline=deadline), address.url(address.XAI, "/responses"),
credential.token, request_body(path, GROK_MODEL, prompt=prompt, detail=detail),
who="grok", label=_tag(label), deadline=deadline)
text, metadata = response_text(status, reply, label=label)
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index 9bf45c2..c5d592e 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -150,7 +150,7 @@ class GrokProvider:
# refused request goes again count in it (`retry`), and each send reads only what is left of it.
deadline = started + GEN_TIMEOUT_SECONDS
status, reply, sends = xai.post(lambda *a: xai.http_json(*a, timeout=GEN_TIMEOUT_SECONDS, deadline=deadline),
- address.url("xai", endpoint), credential.token, body, who="grok", label="gen",
+ address.url(address.XAI, endpoint), credential.token, body, who="grok", label="gen",
deadline=deadline)
# The provider's code goes in front, format-checked; the body it sent goes
# last, as received, with keys and URL query strings masked (refusal.said).
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
index 332b929..94ede35 100644
--- a/sprite_gen/gen/openai_provider.py
+++ b/sprite_gen/gen/openai_provider.py
@@ -251,7 +251,7 @@ def _ask(url: str, token: str, data: bytes, content_type: str) -> tuple[int, Any
left of it."""
deadline = time.monotonic() + GEN_TIMEOUT_SECONDS
return retry.ask(lambda: http_image(url, token, data, content_type, timeout=GEN_TIMEOUT_SECONDS, deadline=deadline),
- provider="openai", who="openai", label="gen", kind=refusal.provider_code, deadline=deadline)
+ provider=address.OPENAI, who="openai", label="gen", kind=refusal.provider_code, deadline=deadline)
def rate_limit_headers(headers: Any) -> dict[str, str]:
@@ -299,7 +299,7 @@ class OpenAIProvider:
token = resolve_credential()
announce_api_billing(self.name, AUTH_ENV, f" ({label}).")
data = json.dumps(body).encode("utf-8")
- status, reply, _headers, _asks = _ask(address.url("openai", "/responses"), token, data, "application/json")
+ status, reply, _headers, _asks = _ask(address.url(address.OPENAI, "/responses"), token, data, "application/json")
text, metadata = vision.response_text(status, reply, label=label)
return text, {**metadata, "auth_source": AUTH_SOURCE_API_KEY, "transport": "openai-api"}
@@ -319,7 +319,7 @@ class OpenAIProvider:
f" (model={fields['model']}, quality={fields['quality']}, size={fields['size']}).",
)
started = time.monotonic()
- status, reply, headers, asks = _ask(address.url("openai", endpoint), token, data, content_type)
+ status, reply, headers, asks = _ask(address.url(address.OPENAI, endpoint), token, data, content_type)
# 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).
diff --git a/sprite_gen/gen/retry.py b/sprite_gen/gen/retry.py
index b8571cc..6c728cb 100644
--- a/sprite_gen/gen/retry.py
+++ b/sprite_gen/gen/retry.py
@@ -57,23 +57,25 @@ import sys
import time
from typing import Any, Callable
+from . import address
+
START_SECONDS = 4.0
MAX_SECONDS = 60.0
RETRY_AFTER_MAX_SECONDS = 120.0
ASKS_AGAIN = 2
UNTAKEN: dict[str, frozenset[int]] = {
- "anthropic": frozenset({429, 500, 529}),
- "openai": frozenset({429, 503}),
- "xai": frozenset({429}),
- "elevenlabs": frozenset({429}),
+ address.ANTHROPIC: frozenset({429, 500, 529}),
+ address.OPENAI: frozenset({429, 503}),
+ address.XAI: frozenset({429}),
+ address.ELEVENLABS: frozenset({429}),
}
ACT_FIRST: dict[str, frozenset[str]] = {
- "anthropic": frozenset({"enforced_spend_limit_reached"}),
- "openai": frozenset({"credit_balance_exhausted", "organization_spend_limit_exceeded",
+ address.ANTHROPIC: frozenset({"enforced_spend_limit_reached"}),
+ address.OPENAI: frozenset({"credit_balance_exhausted", "organization_spend_limit_exceeded",
"project_spend_limit_exceeded", "organization_usage_limit_exceeded", "insufficient_quota"}),
- "xai": frozenset(),
- "elevenlabs": frozenset(),
+ address.XAI: frozenset(),
+ address.ELEVENLABS: frozenset(),
}
GET_AGAIN = frozenset({429, 500, 502, 503, 504, 529})
@@ -110,7 +112,7 @@ def again_after(provider: str, method: str, status: int, body: Any, headers: Any
or None when it is not sent again (the rule in the module docstring)."""
# ElevenLabs documents only these two 429 codes as requests it could not process.
# https://elevenlabs.io/docs/help-center/technical/api-error-code-429 (2026-10-13).
- if provider == "elevenlabs" and method != "GET":
+ if provider == address.ELEVENLABS and method != "GET":
detail = body.get("detail") if isinstance(body, dict) else None
if not isinstance(detail, dict) or detail.get("status") not in ("system_busy", "too_many_concurrent_requests"):
return None
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 73a28c8..58e9a5e 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -199,7 +199,7 @@ def http_download(url: str, token: str, *, deadline: float | None = None) -> byt
that gets no answer it can read whole — the connection failed or timed out, the body broke on the way,
the deadline came — raises xai.TransportError, its words in `reason`. The clip is fetched through the xAI base
when SPRITE_GEN_XAI_BASE_URL is set (`address.fetched`), else from `url` itself."""
- request = urllib.request.Request(address.fetched("xai", url))
+ request = urllib.request.Request(address.fetched(address.XAI, url))
try:
try:
with urllib.request.urlopen(request, timeout=time_left(HTTP_TIMEOUT_SECONDS, deadline)) as response:
@@ -531,7 +531,7 @@ def _submit_poll_publish(
# some of the poll timeout, which counts from the first send.
started = time.monotonic()
timeout = POLL_TIMEOUT_SECONDS if poll_timeout is None else poll_timeout
- status, reply, _sends = post(call, address.url("xai", f"/videos/{endpoint}"), credential.token, body, who="xai", label=verb,
+ status, reply, _sends = post(call, address.url(address.XAI, f"/videos/{endpoint}"), credential.token, body, who="xai", label=verb,
sleep=sleep, deadline=started + timeout)
if status in (401, 403):
raise SystemExit(
@@ -601,7 +601,7 @@ def _poll_publish(
polls += 1
lost: str | None = None
try:
- http, poll = call("GET", address.url("xai", f"/videos/{request_id}"), credential.token, None, deadline=deadline)
+ http, poll = call("GET", address.url(address.XAI, f"/videos/{request_id}"), credential.token, None, deadline=deadline)
except TransportError as failed:
lost, http, poll = failed.reason, None, None
poll_status = poll.get("status") if isinstance(poll, dict) else None
diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.py
index 9f4f3da..db43fc4 100644
--- a/sprite_gen/gen/xai.py
+++ b/sprite_gen/gen/xai.py
@@ -20,7 +20,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable
-from . import refusal, retry
+from . import address, refusal, retry
from .base import LOGINS_ENV, env_api_key, logins_on
AUTH_ENV = "XAI_API_KEY"
@@ -153,7 +153,7 @@ def post(call: HttpCall, url: str, token: str, body: dict, *, who: str, label: s
"""POST `body` with `call` (as http_json), and again after a refusal `retry` sends again within `deadline`,
the call's time limit (which `call` reads by only when the caller hands it too): (status, answer, sends).
xAI documents 429 alone as a request not taken, and no retry-after, so http_json keeps no headers."""
- status, reply, _headers, sends = retry.ask(lambda: (*call("POST", url, token, body), None), provider="xai",
+ status, reply, _headers, sends = retry.ask(lambda: (*call("POST", url, token, body), None), provider=address.XAI,
who=who, label=label, sleep=sleep, kind=refusal.provider_code,
deadline=deadline)
return status, reply, sends
diff --git a/sprite_gen/workflow/capabilities.py b/sprite_gen/workflow/capabilities.py
index 9e47d19..bbd360d 100644
--- a/sprite_gen/workflow/capabilities.py
+++ b/sprite_gen/workflow/capabilities.py
@@ -27,22 +27,22 @@ KIND = "sprite-gen-capabilities"
# `base.logins_on`); `curation` reaches xAI by its reroll and in-between buttons (codex or grok); `video-set` makes
# each clip with `video` and checks a side view's facing on Grok.
PROVIDER_CALLS: dict[str, tuple[str, ...]] = {
- "gen": ("openai", "xai"),
- "gen-set": ("openai", "xai"),
- "logo": ("openai", "xai"),
- "pixel-draw": ("anthropic",),
- "sound": ("elevenlabs",),
- "curation": ("xai",),
- "video": ("xai",),
- "video-extend": ("xai",),
- "video-edit": ("xai",),
- "video-resume": ("xai",),
- "video-set": ("xai",),
+ "gen": (address.OPENAI, address.XAI),
+ "gen-set": (address.OPENAI, address.XAI),
+ "logo": (address.OPENAI, address.XAI),
+ "pixel-draw": (address.ANTHROPIC,),
+ "sound": (address.ELEVENLABS,),
+ "curation": (address.XAI,),
+ "video": (address.XAI,),
+ "video-extend": (address.XAI,),
+ "video-edit": (address.XAI,),
+ "video-resume": (address.XAI,),
+ "video-set": (address.XAI,),
}
# Verbs that call a provider and buy nothing: `video-resume` polls and downloads a clip an earlier run bought.
NO_PURCHASE = frozenset({"video-resume"})
-KEY_ENVS = {"openai": openai_provider.AUTH_ENV, "xai": xai.AUTH_ENV, "anthropic": anthropic_api.AUTH_ENV,
- "elevenlabs": sound_provider.AUTH_ENV}
+KEY_ENVS = {address.OPENAI: openai_provider.AUTH_ENV, address.XAI: xai.AUTH_ENV,
+ address.ANTHROPIC: anthropic_api.AUTH_ENV, address.ELEVENLABS: sound_provider.AUTH_ENV}
# Argument types by name; any other is its parsing function's name without `_` and `parse_` (`_parse_grid`: grid).
TYPES = {str: None, int: "int", float: "float"}