This older article and its examples have not yet been reviewed against current APIs. Check the latest documentation before using the code or treating any example as a measured result.
An image generator can return a result in seconds. Keeping that result usable takes a little more work: save the bytes, choose a filename, and record the settings that produced it.
Save and name the image
For models and endpoints that support it, one option is to request base64 image data, decode it, and write the bytes to disk. Check the current documentation for the model and response format you plan to use.
A repeated prompt does not necessarily produce the same image.
The example below builds a filename from a shortened prompt and a hash. If the file already exists, it returns that path instead of creating another image. This makes reruns convenient when you want to reuse the existing asset.
Handle failures and record settings
Retry transient failures with backoff. Do not retry a content-policy rejection as though it were a network error: report it so the problem is visible.
Keep the prompt and relevant generation settings with the asset. A saved image is much easier to revisit when you know the model, size, and quality settings used to create it.
import base64, hashlib, pathlib, re
from openai import OpenAI
client = OpenAI()
def slugify(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:48]
def generate(prompt: str, out_dir: str = "assets", size="1024x1024"):
digest = hashlib.sha1(prompt.encode()).hexdigest()[:8]
path = pathlib.Path(out_dir) / f"{slugify(prompt)}-{digest}.png"
if path.exists():
return path # idempotent rerun
res = client.images.generate(
model="dall-e-3", prompt=prompt,
size=size, quality="hd", n=1,
response_format="b64_json",
)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(base64.b64decode(res.data[0].b64_json))
(path.with_suffix(".json")).write_text(
f'{{"prompt": "{prompt}", "size": "{size}"}}', encoding="utf-8"
)
return pathKeep the prompt and relevant generation settings with the asset. A saved image is much easier to revisit when you know the model, size, and quality settings used to create it.