This guide was prepared with AI assistance using the linked documentation. Code examples are illustrative; verify them against your environment and current API documentation before use.
Who this is for: Python developers moving an image-generation script away from DALL·E 3, or building a small workflow that saves generated assets and can reuse them on later runs.
What you'll build: a command-line script that asks a GPT Image model for a PNG, stores it in a local folder, and records the request settings as JSON. The cache key includes the model, prompt, size, quality, and format, so changing one of those settings produces a different file.
Before you start: DALL·E 3 was retired on May 12, 2026, according to the OpenAI Images API reference. This page retains the original DALL·E 3 topic for people maintaining older examples, but the runnable code uses a GPT Image model. Availability, supported settings, pricing, and model names can change; check the current documentation before deploying it.
The short version
Use the Image API when you want a single generation request and a file you can handle yourself. With GPT Image models, the response contains base64-encoded image data. Decode it, write the bytes in binary mode, and use a filename derived from the settings that matter to you. Store structured metadata with a JSON serializer rather than building JSON by inserting strings by hand.
The following guide includes setup, a complete script, a walkthrough, testing ideas, security decisions, and troubleshooting. The code is a single-process starter for a trusted local workspace. A production service needs additional controls for concurrency, abuse, durable storage, and access permissions.
What changed from DALL·E 3?
Many older snippets call dall-e-3 and ask for a URL or pass response_format="b64_json". The current API reference marks both DALL·E image models as retired. It also identifies response_format and the old style parameter as legacy parameters that GPT Image models don't support. GPT Image responses contain base64 data; describe the visual style in the prompt instead of copying the old style argument.
This is a migration, not a one-word model substitution. Model capabilities, supported sizes, output options, and quality levels can differ. Review the image generation guide and Python API reference for the model you choose. The examples below use gpt-image-2.5-flare, which the reference lists as a supported model when this guide was reviewed. Your account must have access to the chosen model.
OpenAI's guide notes that some organizations may need API organization verification before using GPT Image models. If a request fails because of access, check your organization and project settings before rewriting your script. ChatGPT subscription access and API access are separate questions; check the account you actually use for the API.
Choose the right interface
The Images API fits a straightforward request: submit a prompt, receive image data, and save it. It also offers an edits endpoint for supported models and input types. That's the route this tutorial uses because a script that processes one prompt at a time doesn't need a conversational state machine.
The Responses API offers an image-generation tool for conversations that combine language and images, including workflows that refine a result over multiple turns. It can be useful when the surrounding application must interpret a request, discuss a change, and then generate or edit. Its request and response structure differs from the Images API. Don't paste the client.images.generate call below into a Responses request and expect the same response shape. See the Responses image-generation guide for that approach.
Neither interface saves the output to your laptop for you. Your application still owns file naming, storage access, backups, and what happens when saving fails. That responsibility is small for a personal experiment and becomes a significant design choice when multiple users submit requests.
Prerequisites and cost
You'll need Python, an OpenAI API key, access to the selected image model, and permission to write to a local folder. You'll also need a network connection for the API request. The code uses the official Python SDK and the Python standard library. It doesn't need an image library for the basic save step.
Image generation incurs API charges. Check the current API pricing page and your project's limits before running repeated requests. The actual cost depends on the model and request; don't treat a budget estimate as a billing guarantee. Start with one image at low quality while checking that your environment works, then compare the settings you need for publication.
Create a working directory and a virtual environment. On Windows PowerShell:
mkdir image-workshop
Set-Location image-workshop
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install openaiOn macOS or Linux, activate the environment with source .venv/bin/activate. If your system uses python3, substitute it for python. If PowerShell blocks the activation script, consult your organization's execution policy; you can also invoke the environment's Python executable directly without changing that policy.
Keep a dependency lock or a pinned version in a real project. An unpinned install is convenient for a quick demonstration, but it can change under you. Record the SDK version alongside your application's own release so you can repeat tests after an upgrade.
Set the API key without putting it in your script
The SDK reads OPENAI_API_KEY from the environment by default. In PowerShell, set it for the current process using a value from your approved secret manager or another secure mechanism:
$env:OPENAI_API_KEY = Read-Host -Prompt 'OpenAI API key'For production, prefer a secret manager or the hosting platform's protected environment variables. Never commit a key, embed it in browser JavaScript, paste it into a public issue, or include it in an article screenshot. A key exposed to an untrusted party can be used until it is revoked or otherwise restricted. Follow your provider's credential guidance and rotate a key if you suspect exposure.
The Read-Host example is intentionally simple for a local session; its input may be visible on screen. Use your organization's secure entry method if others can see your display or terminal. Setting an environment variable does not itself create a new key or configure API access.
A small working example: generate, cache, and save
Save the following as generate_image.py. The script uses one output directory and creates a PNG plus a metadata file. Its cache behavior is deliberate: when the same request is repeated, it reuses the saved PNG; --refresh requests a new image and replaces the local file for that request. A repeated prompt does not guarantee the same pixels when you regenerate.
import argparse
import base64
import hashlib
import json
import os
import tempfile
from pathlib import Path
from openai import OpenAI
MODEL = "gpt-image-2.5-flare"
SIZE = "1024x1024"
QUALITY = "low"
OUTPUT_FORMAT = "png"
OUTPUT_DIR = Path("generated-images")
def write_atomically(path: Path, contents: bytes) -> None:
"""Replace a file only after its full contents have been written."""
temporary_name = None
try:
with tempfile.NamedTemporaryFile(
mode="wb", dir=path.parent, delete=False
) as temporary:
temporary_name = temporary.name
temporary.write(contents)
os.replace(temporary_name, path)
finally:
if temporary_name and os.path.exists(temporary_name):
os.unlink(temporary_name)
def generate(prompt: str, refresh: bool = False) -> Path:
request = {
"model": MODEL,
"prompt": prompt,
"size": SIZE,
"quality": QUALITY,
"output_format": OUTPUT_FORMAT,
"n": 1,
}
# Canonical JSON keeps cache keys stable when dictionary order changes.
request_json = json.dumps(
request, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
digest = hashlib.sha256(request_json.encode("utf-8")).hexdigest()
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
image_path = OUTPUT_DIR / f"{digest}.png"
metadata_path = OUTPUT_DIR / f"{digest}.json"
if image_path.is_file() and not refresh:
print("Using cached image:", image_path)
return image_path
response = OpenAI().images.generate(**request)
if not response.data or not response.data[0].b64_json:
raise RuntimeError("The API response did not contain image data")
image_bytes = base64.b64decode(response.data[0].b64_json, validate=True)
if not image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
raise ValueError("The response did not have a PNG signature")
metadata = {
"request": request,
"cache_key_sha256": digest,
"image_file": image_path.name,
}
metadata_bytes = (json.dumps(metadata, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
write_atomically(image_path, image_bytes)
write_atomically(metadata_path, metadata_bytes)
print("Saved image:", image_path)
return image_path
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("prompt", help="Description of the image")
parser.add_argument("--refresh", action="store_true", help="Generate again")
args = parser.parse_args()
if not args.prompt.strip():
parser.error("prompt must not be empty")
generate(args.prompt, refresh=args.refresh)Run it from the working directory:
python generate_image.py "A lime green ceramic mug on a dark desk, soft side lighting"Open the PNG in generated-images and check the image visually. Run the same command again to exercise the local cache. The second invocation should print Using cached image and should not need a generation request. To request a different image with the same settings, add --refresh:
python generate_image.py "A lime green ceramic mug on a dark desk, soft side lighting" --refreshThe filename is intentionally a long digest, not a human-readable prompt. This avoids putting prompt text directly into paths and sidesteps characters that are invalid in filenames. The JSON sidecar, however, contains the full prompt. Treat that folder as private when the prompt contains sensitive information.
The code checks the PNG signature and valid base64, but that is not a complete image-integrity or malware scan. For assets received from untrusted sources or processed by a service, use an appropriate decoder, resource limits, and a security review. Also note that the PNG and JSON files are replaced independently: a crash between writes can leave a new image with old metadata. The section on production storage explains how to make the pair consistent.
How the cache key works
Imagine generating a square image and then changing the script to request a landscape image. A cache keyed only by prompt would still find the old square file. The script instead serializes the complete request settings that determine this example's cache identity and hashes those bytes. A change to size, quality, model, output_format, n, or the prompt therefore leads to a different path.
The sort_keys=True option makes dictionary ordering predictable, and compact separators make the serialized form consistent for this Python implementation. The use of ensure_ascii=False preserves the prompt's Unicode text in the serialized form before it is encoded as UTF-8. A different implementation must agree on the same serialization if it needs to calculate identical keys.
This hash identifies the request as the script understands it. It does not prove that the generated image is unique, that the model's behavior never changes, or that a later generation will reproduce the same image. Model aliases can change over time. If repeatability matters, record an available model snapshot and the generation date, and keep the actual output. Verify supported snapshots in the current model documentation rather than inventing a model identifier.
The key also includes the raw prompt through its digest. A digest is not encryption: someone who can guess a prompt can calculate its hash and compare it. Don't rely on a hashed filename to hide sensitive prompts. In a shared system, prefer random asset identifiers exposed to clients and store request metadata behind appropriate access controls.
Why JSON serialization matters
Prompts often contain quotation marks, newlines, backslashes, or non-English text. Building metadata with a line such as '{"prompt": "' + prompt + '"}' breaks as soon as the prompt contains a quote. Worse, manually constructed output can appear to work for simple prompts and fail only after it is used in a batch.
json.dumps escapes special characters correctly and produces valid JSON for supported Python values. ensure_ascii=False keeps Unicode readable in the sidecar; writing UTF-8 bytes makes the encoding explicit. If another program consumes the metadata, it should parse the file with a JSON parser and validate the fields it needs. Don't execute values from metadata as code or shell commands.
For example, this prompt should remain one string in the sidecar, even though it contains quotes:
A notebook labeled "ideas" beside a glass of waterYou can inspect the sidecar with a text editor, or validate it with Python's standard JSON tool:
python -m json.tool generated-images\YOUR_DIGEST.jsonReplace YOUR_DIGEST.json with the actual file name. A parser check confirms the file is syntactically valid JSON; it doesn't confirm the image visually matches the prompt or that the metadata is suitable for public disclosure.
Choosing dimensions, quality, and format
Start with the dimensions required by the place where the asset will appear. A square image is useful for a square card; a landscape hero may need a wider composition and safe space around its subject. Requesting the right aspect ratio reduces the chance that a later crop cuts off the important part of the image.
The current guide lists 1024x1024, 1536x1024, and 1024x1536 among recommended dimensions. Some newer models also accept custom dimensions subject to their documented constraints. Consult the specific model and API reference: don't assume that every model supports every size or that limits will remain unchanged.
The example uses quality="low" to make it easier to iterate. Compare a higher setting for a final asset where detail matters. Quality, dimensions, prompt length, model, and output choices can affect latency or cost. Measure those tradeoffs for your own workload and check current pricing rather than copying a fixed cost from an old tutorial.
PNG is a useful default when you want lossless raster output or a transparent background. JPEG can be useful for photographs where a smaller transfer is more important than transparency. WebP is another option where your publishing pipeline and browsers support it. Use the documented output_format option and name the file with the matching extension; writing WebP bytes to a .png file creates a misleading artifact.
If you request a transparent background, check model support and use a compatible format. The current OpenAI reference specifies PNG or WebP for supported transparent output. Inspect the actual result on both light and dark backgrounds; an image with transparency may still have unwanted edges or shadows around its subject.
Prompts that are easier to evaluate
An effective prompt gives the model a useful job and gives you a way to judge the result. Begin with the subject, setting, and composition. Add lighting, a palette, and any constraint required by the intended placement. If the image belongs beside an article, state the concept it should communicate and leave room for surrounding page elements.
Here is a starting point for an editorial hero:
Create a wide editorial illustration for a developer article about image caching.
Show a small stack of dark storage trays and one lime-green image tile moving
into the top tray. Use a restrained black, charcoal, and lime palette, soft
directional light, and generous negative space. No logos and no readable text.You can change one instruction at a time to see what influences the output. If the image is too busy, reduce the number of objects before adding a long list of negatives. If the subject is cropped, specify where it should sit and how much margin is required. If the result needs exact lettering, consider adding the text in your normal design tool instead of relying on generated text.
Don't put confidential customer details, access tokens, or real personal information into a prompt simply because an image would be convenient. Review your organization's data handling rules and the provider's current data policies first. A local output folder doesn't make the API request itself local: the prompt still travels to the API provider.
Avoid accidental duplicate charges
Caching can prevent a local rerun from making the same request again. It cannot guarantee that an interrupted network request was never processed. If the client times out after the server has started processing, the client may not know whether generation completed. Retrying blindly can create another paid request. Check current SDK retry behavior, API status, and your usage records when diagnosing this case.
For a scheduled job, log a request identifier when available, the cache key, the attempt time, and the final state. Don't log the API key, raw base64 image, or sensitive prompt text. Make the failure visible to an operator instead of silently retrying forever. A bounded retry policy can help with temporary problems, but it must be designed with cost and duplicate processing in mind.
The example's --refresh flag intentionally overwrites the local image for that request key. If you need an audit trail or multiple candidates, give each generation its own immutable asset ID and store its request key separately. A cache entry can then point to a chosen asset without erasing earlier outputs. Decide how long the originals should be retained and who is allowed to remove them.
Handle failures by category
An authentication error usually means the key, project, or permissions need attention. A missing model or access error can indicate a retired model name, unavailable account access, or a request sent to the wrong project. Verify the current model list and account configuration before changing the prompt.
A validation error can point to an unsupported size, output format, or parameter combination. Read the response message without exposing credentials, then compare each parameter with the reference for the selected model. Legacy fields such as DALL·E's style and response_format should not be carried into a GPT Image request.
Rate limits and temporary service problems deserve a bounded retry plan. Use exponential backoff with jitter where appropriate and respect any retry instructions returned by the service. The OpenAI SDK may already retry some failures; check the installed SDK's behavior so that your application-level retries don't multiply the number of attempts unexpectedly. Don't retry a malformed request or a policy rejection as though it were a transient network problem.
A disk error is a separate failure from image generation. Check that the output directory exists, that the process has write permission, and that there is enough space. The example writes to a temporary file in the destination directory and then replaces the target, reducing the chance of leaving a partially written target. It does not guarantee durable storage after power loss and doesn't make the image and metadata update one transaction.
If your application shows these errors to users, write messages that explain the next action without exposing provider responses, file paths, tokens, or internal account details. Keep a more specific, access-controlled operational record for the person responsible for troubleshooting.
A practical verification checklist
Before using a generated asset, check the output itself and the workflow that produced it:
- Open the file in an image viewer and confirm it isn't empty or visibly corrupted.
- Confirm the dimensions and format with an image inspection tool; don't infer them solely from the filename.
- Review hands, objects, lettering, logos, and details that could mislead the reader.
- Check the crop at desktop and mobile sizes, including the area behind headings or buttons.
- Confirm that the saved sidecar parses and describes the request you intended to make.
- Re-run without
--refreshand verify that the cached path is reused. - Change one setting such as size and verify that the cache key changes.
- Test a prompt containing quotes and non-English characters to check JSON handling.
- Keep one known-safe test prompt for future SDK or model upgrades.
- Confirm that the output and metadata are stored with the intended permissions and retention period.
The sample is designed to be exercised locally. If you adapt it for a team, add automated tests with a mocked API response so tests don't spend money or depend on a live provider. Reserve a small, explicitly budgeted live smoke test for checking actual access and response behavior. Record which checks used mocks and which made real requests.
Test without sending an API request
A useful unit test checks your own code, not the visual skill of a remote model. Replace the client with a fake response containing a small known PNG, run the save function in a temporary directory, and assert that a file and parseable metadata were written. Then run it again with the same settings and assert that the fake client wasn't called a second time.
Other tests should cover a missing data list, malformed base64, a non-PNG payload, and an unwritable directory. If you test --refresh, assert that the client is invoked again and that the new content replaces the old image. These tests establish how your wrapper behaves; they don't prove that a real request is authorized or that the model's images are suitable for publication.
The simple example keeps configuration as module constants to make the basic flow visible. For a larger application, pass a configuration object and an API client into your function. That makes it straightforward to substitute the fake client in a test without changing environment variables or calling the network. Keep the same explicit cache identity when you refactor.
Include a regression test for the original cache problem. Generate a key for a square image, generate another key for a landscape image using the same prompt, and assert they differ. Add a test that changes quality, model, and format individually. If you later introduce a background or compression parameter, add it to both the request and the key before shipping the new option.
Concurrency: when two jobs request the same image
The code checks for an existing file and then sends a request. Two processes can both observe that the file is absent and both call the API. Atomic file replacement prevents a reader from seeing a half-written target, but it does not prevent duplicate generation or make the sidecar and PNG update together. It also doesn't coordinate work across different machines.
For a multi-worker service, use a shared coordination mechanism with an expiration and clear failure recovery. A common design stores a unique request key in a database, records a job state, and lets one worker claim the job. The details depend on your database and queue. An owner that crashes must not leave every future request blocked forever; handle lease expiration, retries, and operator intervention explicitly.
Store each generated image under a unique immutable asset ID, then commit the asset record and its metadata in a way your application can recover. Object storage and a database don't generally share a transaction, so design for partial failure: write the object, verify it, record the database state, and reconcile abandoned objects or incomplete records. Use your provider's documented guarantees rather than assuming an upload and database insert happen atomically.
The local script is appropriate for one person running one request at a time. If that boundary matches your use, keep the implementation small. If users or scheduled workers can run concurrently, treat the coordination work as part of the feature, not as an optional optimization.
Privacy, retention, and ownership of the output
The sidecar contains the complete prompt, which may reveal a product plan, client name, or unpublished idea. The image itself can also contain sensitive material. Decide whether you need full prompts at all. A private application may store only the settings required for operations and an internal identifier that points to a separately protected record.
Apply file permissions that match your environment. A developer laptop, a shared build machine, and a public object-storage bucket have very different exposure. If the folder is inside a repository, add generated files and secrets to the appropriate ignore rules before you commit. Review your Git status and any CI artifact uploads; an ignored file can still be copied into a deployment by another build step.
Set a retention period and a deletion procedure. For production systems, include backups, derived thumbnails, CDN copies, metadata, and logs in that plan. Access and deletion requirements depend on your use case and applicable rules, so involve the person responsible for data handling instead of treating a tutorial as legal advice.
Generated assets may be subject to your provider's terms, your customer contracts, and rights associated with any supplied reference material. Review current terms and obtain permission for input images you don't own. Avoid presenting a generated image as a real photograph of an event, person, or product when that distinction matters to the audience.
Preparing images for a website
The original output is a source asset, not necessarily the file you should send to every visitor. Export appropriately sized variants, use a format supported by your site, and compare visual quality at the actual display size. A large source image scaled down by CSS still transfers the larger file unless your delivery pipeline supplies an appropriate variant.
Write alternative text that explains the image's role. For a meaningful diagram, describe the relationship the reader needs to understand; for a purely decorative background, an empty alt may be appropriate. Don't put a list of search keywords in the alt text. If a chart or diagram contains information needed to use the page, provide that information in nearby text as well.
Reserve the image's space in the layout with known dimensions or an aspect ratio to reduce layout movement while it loads. For a page's main visible image, decide loading priority based on how the page renders and test the result. For lower-page images, lazy loading may help avoid unnecessary early downloads. Your framework's image component or CDN may handle some of these choices; consult its current documentation.
Use a filename that helps your editorial team understand the asset, but don't expose a private cache key or sensitive prompt if you don't need to. You can keep the generated source under its digest locally and publish an approved derivative with a descriptive name. Maintain a mapping if you need to trace the published file back to the source.
Migrating an existing DALL·E 3 project
Start by finding calls that specify dall-e-3, response_format, and style. Inventory every consumer of the response: some applications expect a URL, while others decode base64 or store metadata. A model upgrade is incomplete if the request works but downstream code still expects a field that isn't present.
Next, choose a currently supported GPT Image model, check account access, and compare the settings your product requires. Replace legacy parameters with supported ones, then update the response handling for base64 data. Revisit your size and quality defaults; don't assume the old choices map directly to the new model.
Run a small set of representative prompts. Include the difficult examples your users actually submit, subject to your data policy, and evaluate them against a written rubric. For example: correct subject, useful framing, text accuracy where relevant, visual consistency, and suitability for the intended channel. Record failures and ask a human reviewer to inspect borderline outputs.
Finally, update tests, monitoring, documentation, and budget estimates. If the old system cached by prompt alone, consider whether existing cache entries can still be used safely. A versioned namespace such as image-cache-v2 can separate old and new assumptions. Keep legacy files until you know they are no longer referenced, and avoid deleting a production cache as part of an unreviewed migration.
Frequently asked questions
Can I still use a DALL·E 3 Python example?
Treat it as historical reference. The current Images API reference says dall-e-3 was retired on May 12, 2026. Update the model and request fields using current documentation, and review the response handling and tests rather than assuming the old request will work unchanged.
Does a cached prompt produce the same image every time?
The example returns the same saved file when its local cache entry exists. That is reuse of an existing asset. If you generate again using --refresh, the API may produce a different image even for the same prompt and settings. Keep the image itself when you need the exact asset later.
Why is my PNG file present but my JSON sidecar missing?
The script writes the image and metadata as two separate operations. A crash or permission error between them can leave only one updated file. Check the error, verify the image, and regenerate or reconstruct metadata only if you can establish the request settings. For a service, use a state record and a recovery process that detects incomplete assets.
Can I save a WebP or JPEG instead?
Supported GPT Image models can return formats including PNG, WebP, and JPEG. Check the model's current documentation and change both output_format and the filename extension. The example's PNG signature check must also be replaced with validation appropriate for the chosen format. Include any output compression setting in the cache key when you add it to the request.
Why did the API reject a valid-looking size?
The permitted dimensions depend on the model, and custom sizes can have edge, aspect-ratio, and pixel-count constraints. Compare the exact model and requested dimensions with the live API reference. A size that worked with a retired model may not be supported by its replacement.
Should I put the API call in browser JavaScript?
Keep your secret API key on a server or another trusted environment. Browser code is delivered to visitors, so a key embedded there can be extracted. A web app should call your authenticated backend, which validates and limits requests before calling the provider. That backend also needs spending controls and abuse protection.
Will a 4,000-word tutorial rank first for this topic?
No length can guarantee a search position. Google's guidance on helpful content says there is no preferred word count. The useful goal is to answer the reader's question accurately, make the steps reproducible, and maintain the page when the API changes.
Sources and maintenance
- OpenAI Images API: Python
images.generatereference — model availability, request fields, response data, and legacy parameter notes. - OpenAI image generation guide — generation, editing, image formats, and model-specific options.
- OpenAI Responses API image-generation tool — conversational image workflows and tool behavior.
- OpenAI API pricing — current pricing and billing details.
- Google Search guidance on helpful content — reader-focused content and word-count guidance.
Review the cited provider pages before changing the sample's model, sizes, or endpoint. This article describes a starter workflow and its limits; it does not claim that the sample has been tested against every account, SDK version, or deployment environment.
