Image generation
For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending
.mdto the page URL.
Overview
The API lets you generate and edit images from text prompts using gpt-image-2.5-sunburst and gpt-image-2.5-flare. Choose Sunburst for workflows where editing precision matters most, and Flare for fast, high-quality everyday image generation. You can access image generation capabilities through two APIs:
Image API
The Image API provides two endpoints, each with distinct capabilities:
- Generations: Generate images from scratch based on a text prompt
- Edits: Modify existing images using a new prompt, either partially or entirely
Responses API
The Responses API allows you to generate images as part of conversations or multi-step flows. It supports image generation as a built-in tool, and accepts image inputs and outputs within context.
Compared to the Image API, it adds:
- Multi-turn editing: Iteratively make high fidelity edits to images with prompting
- Flexible inputs: Accept image File IDs as input images, not just bytes
For mainline models that can call the image generation tool, refer to supported models.
Choosing the right API
- If you only need to generate or edit a single image from one prompt, the Image API is your best choice.
- If you want to build conversational, editable image experiences with GPT Image, go with the Responses API.
With the Image API, set model to gpt-image-2.5-sunburst or gpt-image-2.5-flare directly. With the Responses API, select a supported mainline model at the top level and specify gpt-image-2.5-sunburst or gpt-image-2.5-flare in the image generation tool's model field.
Both APIs let you customize output by adjusting quality, size, format, and compression.
To ensure these models are used responsibly, you may need to complete the API Organization Verification from your developer console before using GPT Image models.
Generate Images
You can use the image generation endpoint to create images based on text prompts, or the image generation tool in the Responses API to generate images as part of a conversation.
To learn more about customizing the output (size, quality, format, compression), refer to the customize image output section below.
You can set the n parameter to generate multiple images at once in a single request (by default, the API returns a single image).
Image API
Generate an image
import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI();
const prompt = `
A children's book drawing of a veterinarian using a stethoscope to
listen to the heartbeat of a baby otter.
`;
const result = await openai.images.generate({
model: "gpt-image-2.5-sunburst",
prompt,
});
// Save the image to a file
const image_base64 = result.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("otter.png", image_bytes);
from openai import OpenAI
import base64
client = OpenAI()
prompt = """
A children's book drawing of a veterinarian using a stethoscope to
listen to the heartbeat of a baby otter.
"""
result = client.images.generate(model="gpt-image-2.5-sunburst", prompt=prompt)
image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
# Save the image to a file
with open("otter.png", "wb") as f:
f.write(image_bytes)
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
result, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{
Model: openai.ImageModel("gpt-image-2.5-sunburst"),
Prompt: "A children's book drawing of a veterinarian using a stethoscope to " +
"listen to the heartbeat of a baby otter.",
})
if err != nil {
panic(err)
}
image, err := base64.StdEncoding.DecodeString(result.Data[0].B64JSON)
if err != nil {
panic(err)
}
if err := os.WriteFile("otter.png", image, 0o600); err != nil {
panic(err)
}
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.images.ImageGenerateParams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
var images =
client
.images()
.generate(
ImageGenerateParams.builder()
.model("gpt-image-2.5-sunburst")
.prompt("A watercolor robot reading in a library")
.build());
Files.write(
Path.of("generated-image.png"),
Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));
using OpenAI.Images;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-image-2.5-sunburst";
ImageClient client = new(model, key);
GeneratedImage image = await client.GenerateImageAsync(
"A children's book drawing of a veterinarian using a stethoscope to "
+ "listen to the heartbeat of a baby otter."
);
await File.WriteAllBytesAsync("otter.png", image.ImageBytes.ToArray());
require "base64"
require "openai"
client = OpenAI::Client.new
result = client.images.generate(
model: "gpt-image-2.5-sunburst",
prompt: "A watercolor robot reading in a library"
)
generated_image = result.data&.first or raise "No image returned"
File.binwrite(
"generated-image.png",
Base64.strict_decode64(generated_image.b64_json)
)
curl -X POST "https://api.openai.com/v1/images/generations" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-type: application/json" \
-d '{
"model": "gpt-image-2.5-sunburst",
"prompt": "A children'\''s book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter."
}' | jq -r '.data[0].b64_json' | base64 --decode > otter.png
openai images generate \
--model gpt-image-2.5-sunburst \
--prompt "A children's book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter." \
--raw-output \
--transform 'data.0.b64_json' | base64 --decode > otter.png
Responses API
Generate an image
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
input:
"Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
});
// Save the image to a file
const imageData = response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData.length > 0) {
const imageBase64 = imageData[0];
const fs = await import("fs");
fs.writeFileSync("otter.png", Buffer.from(imageBase64, "base64"));
}
from openai import OpenAI
import base64
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
# Save the image to a file
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
})
if err != nil {
panic(err)
}
saveFirstGeneratedImage(response, "otter.png")
}
func saveFirstGeneratedImage(response *responses.Response, filename string) {
for _, output := range response.Output {
if output.Type != "image_generation_call" {
continue
}
image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
return
}
panic("response did not include an image generation call")
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")
.addTool(Tool.ImageGeneration.builder().build())
.build();
var image =
client.responses().create(params).output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No image generation call returned"));
String encoded =
image.result().orElseThrow(() -> new IllegalStateException("No image returned"));
Files.write(Path.of("otter.png"), Base64.getDecoder().decode(encoded));
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.InputItems.Add(
ResponseItem.CreateUserMessageItem(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf."
)
);
options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
ResponseResult response = await client.CreateResponseAsync(options);
ImageGenerationCallResponseItem image = response
.OutputItems.OfType<ImageGenerationCallResponseItem>()
.FirstOrDefault()
?? throw new InvalidOperationException("No generated image was returned.");
await File.WriteAllBytesAsync("otter.png", image.ImageResultBytes.ToArray());
require "base64"
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
)
image_call = response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No image generation call returned"
end
encoded_image = image_call.result or raise "No image returned"
File.binwrite("otter.png", Base64.strict_decode64(encoded_image))
Multi-turn image generation
With the Responses API, you can build multi-turn conversations involving image generation either by providing image generation calls outputs within context (you can also just use the image ID), or by using the previous_response_id parameter.
This lets you iterate on images across multiple turns—refining prompts, applying new instructions, and evolving the visual output as the conversation progresses.
With the Responses API image generation tool, supported tool models can choose whether to generate a new image or edit one already in the conversation. The optional action parameter controls this behavior: keep action: "auto" to let the model decide, set action: "generate" to always create a new image, or set action: "edit" to force editing when an image is in context.
Force image creation with action
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
input:
"Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools: [
{ type: "image_generation", model: "gpt-image-2.5-sunburst", action: "generate" },
],
});
// Save the image to a file
const imageData = response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData.length > 0) {
const imageBase64 = imageData[0];
const fs = await import("fs");
fs.writeFileSync("otter.png", Buffer.from(imageBase64, "base64"));
}
from openai import OpenAI
import base64
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[
{"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}
],
)
# Save the image to a file
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst", Action: "generate"}}},
})
if err != nil {
panic(err)
}
for _, output := range response.Output {
if output.Type != "image_generation_call" {
continue
}
image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)
if err != nil {
panic(err)
}
if err := os.WriteFile("otter.png", image, 0o600); err != nil {
panic(err)
}
return
}
panic("response did not include an image generation call")
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Generate an image of a gray tabby cat hugging an otter with an orange scarf.")
.addTool(
Tool.ImageGeneration.builder().action(Tool.ImageGeneration.Action.GENERATE).build())
.build();
String imageResult =
client.responses().create(params).output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.flatMap(call -> call.result().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No generated image returned"));
Path output = Path.of(System.getenv().getOrDefault("OPENAI_EXAMPLE_OUTPUT_PATH", "otter.png"));
Files.write(output, Base64.getDecoder().decode(imageResult));
System.out.println(output);
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.InputItems.Add(
ResponseItem.CreateUserMessageItem(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf."
)
);
options.Tools.Add(
ResponseTool.CreateImageGenerationTool(
model: "gpt-image-2.5-sunburst",
action: ImageGenerationToolAction.Generate
)
);
ResponseResult response = await client.CreateResponseAsync(options);
ImageGenerationCallResponseItem image = response
.OutputItems.OfType<ImageGenerationCallResponseItem>()
.FirstOrDefault()
?? throw new InvalidOperationException("No generated image was returned.");
await File.WriteAllBytesAsync("otter.png", image.ImageResultBytes.ToArray());
require "base64"
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst", action: :generate}]
)
image_call = response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No image generation call returned"
end
encoded_image = image_call.result or raise "No image returned"
output_path = ENV.fetch("OPENAI_EXAMPLE_OUTPUT_PATH", "otter.png")
File.binwrite(output_path, Base64.decode64(encoded_image))
puts(output_path)
If you force edit without providing an image in context, the call will return an error. Leave action at auto to have the model decide when to generate or edit.
Using previous response ID
Multi-turn image generation
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
input:
"Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
});
const imageData = response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData.length > 0) {
const imageBase64 = imageData[0];
const fs = await import("fs");
fs.writeFileSync("cat_and_otter.png", Buffer.from(imageBase64, "base64"));
}
// Follow up
const response_fwup = await openai.responses.create({
model: "gpt-6-astra",
previous_response_id: response.id,
input: "Now make it look realistic",
tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
});
const imageData_fwup = response_fwup.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData_fwup.length > 0) {
const imageBase64 = imageData_fwup[0];
const fs = await import("fs");
fs.writeFileSync(
"cat_and_otter_realistic.png",
Buffer.from(imageBase64, "base64")
);
}
from openai import OpenAI
import base64
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("cat_and_otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
# Follow up
response_fwup = client.responses.create(
model="gpt-6-astra",
previous_response_id=response.id,
input="Now make it look realistic",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_data_fwup = [
output.result
for output in response_fwup.output
if output.type == "image_generation_call"
]
if image_data_fwup:
image_base64 = image_data_fwup[0]
with open("cat_and_otter_realistic.png", "wb") as f:
f.write(base64.b64decode(image_base64))
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
})
if err != nil {
panic(err)
}
saveFirstGeneratedImage(first, "cat_and_otter.png")
followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
PreviousResponseID: openai.String(first.ID),
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Now make it look realistic"),
},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
})
if err != nil {
panic(err)
}
saveFirstGeneratedImage(followUp, "cat_and_otter_realistic.png")
}
func saveFirstGeneratedImage(response *responses.Response, filename string) {
for _, output := range response.Output {
if output.Type != "image_generation_call" {
continue
}
image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
return
}
panic("response did not include an image generation call")
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
var first =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf.")
.addTool(Tool.ImageGeneration.builder().build())
.build());
var firstImage =
first.output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No image generation call returned"));
Files.write(
Path.of("cat_and_otter.png"),
Base64.getDecoder()
.decode(
firstImage
.result()
.orElseThrow(() -> new IllegalStateException("No image returned"))));
var second =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Now make it look realistic.")
.previousResponseId(first.id())
.addTool(Tool.ImageGeneration.builder().build())
.build());
var secondImage =
second.output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(
() -> new IllegalStateException("No follow-up image generation call returned"));
Files.write(
Path.of("cat_and_otter_realistic.png"),
Base64.getDecoder()
.decode(
secondImage
.result()
.orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
options.InputItems.Add(
ResponseItem.CreateUserMessageItem(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf."
)
);
ResponseResult first = await client.CreateResponseAsync(options);
ImageGenerationCallResponseItem initialImage = first
.OutputItems.OfType<ImageGenerationCallResponseItem>()
.First();
await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());
CreateResponseOptions followUp = new()
{
Model = "gpt-6-astra",
PreviousResponseId = first.Id,
};
followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));
ResponseResult second = await client.CreateResponseAsync(followUp);
ImageGenerationCallResponseItem updatedImage = second
.OutputItems.OfType<ImageGenerationCallResponseItem>()
.First();
await File.WriteAllBytesAsync(
"cat_and_otter_realistic.png",
updatedImage.ImageResultBytes.ToArray()
);
require "base64"
require "openai"
client = OpenAI::Client.new
first = client.responses.create(
model: "gpt-6-astra",
input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
)
first_image = first.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless first_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No image generation call returned"
end
encoded_image = first_image.result or raise "No image returned"
File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))
follow_up = client.responses.create(
model: "gpt-6-astra",
input: "Now make it look realistic.",
previous_response_id: first.id,
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
)
follow_up_image = follow_up.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless follow_up_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No follow-up image generation call returned"
end
encoded_image = follow_up_image.result or raise "No follow-up image returned"
File.binwrite("cat_and_otter_realistic.png", Base64.strict_decode64(encoded_image))
Using image ID
Multi-turn image generation
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
input:
"Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
});
const imageGenerationCalls = response.output.filter(
(output) => output.type === "image_generation_call"
);
const imageData = imageGenerationCalls.map((output) => output.result);
if (imageData.length > 0) {
const imageBase64 = imageData[0];
const fs = await import("fs");
fs.writeFileSync("cat_and_otter.png", Buffer.from(imageBase64, "base64"));
}
// Follow up
const response_fwup = await openai.responses.create({
model: "gpt-6-astra",
input: [
{
role: "user",
content: [{ type: "input_text", text: "Now make it look realistic" }],
},
{
type: "image_generation_call",
id: imageGenerationCalls[0].id,
},
],
tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
});
const imageData_fwup = response_fwup.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData_fwup.length > 0) {
const imageBase64 = imageData_fwup[0];
const fs = await import("fs");
fs.writeFileSync(
"cat_and_otter_realistic.png",
Buffer.from(imageBase64, "base64")
);
}
import openai
import base64
response = openai.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_generation_calls = [
output for output in response.output if output.type == "image_generation_call"
]
image_data = [output.result for output in image_generation_calls]
if image_data:
image_base64 = image_data[0]
with open("cat_and_otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
# Follow up
response_fwup = openai.responses.create(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": [{"type": "input_text", "text": "Now make it look realistic"}],
},
{
"type": "image_generation_call",
"id": image_generation_calls[0].id,
},
],
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_data_fwup = [
output.result
for output in response_fwup.output
if output.type == "image_generation_call"
]
if image_data_fwup:
image_base64 = image_data_fwup[0]
with open("cat_and_otter_realistic.png", "wb") as f:
f.write(base64.b64decode(image_base64))
package main
import (
"context"
"encoding/base64"
"encoding/json"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
first, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
})
if err != nil {
panic(err)
}
call := firstImageGenerationCall(first)
saveImage("cat_and_otter.png", call.Result)
input := outputAsInput(first.Output)
input = append(input, responses.ResponseInputItemParamOfMessage(
responses.ResponseInputMessageContentListParam{responses.ResponseInputContentParamOfInputText("Now make it look realistic")},
responses.EasyInputMessageRoleUser,
))
followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
})
if err != nil {
panic(err)
}
saveImage("cat_and_otter_realistic.png", firstImageGenerationCall(followUp).Result)
}
func firstImageGenerationCall(response *responses.Response) responses.ResponseOutputItemImageGenerationCall {
for _, output := range response.Output {
if output.Type == "image_generation_call" {
return output.AsImageGenerationCall()
}
}
panic("response did not include an image generation call")
}
func outputAsInput(output []responses.ResponseOutputItemUnion) []responses.ResponseInputItemUnionParam {
input := make([]responses.ResponseInputItemUnionParam, 0, len(output))
for _, item := range output {
var converted responses.ResponseInputItemUnion
if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {
panic(err)
}
input = append(input, converted.ToParam())
}
return input
}
func saveImage(filename, encoded string) {
image, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.Tool;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;
import java.util.Map;
var first =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf.")
.addTool(Tool.ImageGeneration.builder().build())
.build());
var firstImage =
first.output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No image generation call returned"));
Files.write(
Path.of("cat_and_otter.png"),
Base64.getDecoder()
.decode(
firstImage
.result()
.orElseThrow(() -> new IllegalStateException("No image returned"))));
var second =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Now make it look realistic.")
.build()),
JsonValue.from(
Map.of("type", "image_generation_call", "id", firstImage.id()))
.convert(ResponseInputItem.class)))
.addTool(Tool.ImageGeneration.builder().build())
.build());
var secondImage =
second.output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(
() -> new IllegalStateException("No follow-up image generation call returned"));
Files.write(
Path.of("cat_and_otter_realistic.png"),
Base64.getDecoder()
.decode(
secondImage
.result()
.orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
options.InputItems.Add(
ResponseItem.CreateUserMessageItem(
"Generate an image of a gray tabby cat hugging an otter with an orange scarf."
)
);
ResponseResult first = await client.CreateResponseAsync(options);
ImageGenerationCallResponseItem initialImage = first
.OutputItems.OfType<ImageGenerationCallResponseItem>()
.First();
await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());
CreateResponseOptions followUp = new() { Model = "gpt-6-astra" };
followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));
followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));
ResponseResult second = await client.CreateResponseAsync(followUp);
ImageGenerationCallResponseItem updatedImage = second
.OutputItems.OfType<ImageGenerationCallResponseItem>()
.First();
await File.WriteAllBytesAsync(
"cat_and_otter_realistic.png",
updatedImage.ImageResultBytes.ToArray()
);
require "base64"
require "openai"
client = OpenAI::Client.new
first = client.responses.create(
model: "gpt-6-astra",
input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
)
first_image = first.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless first_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No image generation call returned"
end
encoded_image = first_image.result or raise "No image returned"
File.binwrite("cat_and_otter.png", Base64.strict_decode64(encoded_image))
follow_up = client.responses.create(
model: "gpt-6-astra",
input: [
{
role: :user,
content: [{type: :input_text, text: "Now make it look realistic."}]
},
{type: :image_generation_call, id: first_image.id}
],
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
)
follow_up_image = follow_up.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless follow_up_image.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No follow-up image generation call returned"
end
encoded_image = follow_up_image.result or raise "No follow-up image returned"
File.binwrite("cat_and_otter_realistic.png", Base64.strict_decode64(encoded_image))
Result
| "Generate an image of gray tabby cat hugging an otter with an orange scarf" |
|
| "Now make it look realistic" |
|
Streaming
The Responses API and Image API support streaming image generation. You can stream partial images as the APIs generate them, providing a more interactive experience.
You can adjust the partial_images parameter to receive 0-3 partial images.
- If you set
partial_imagesto 0, you will only receive the final image. - For values larger than zero, you may not receive the full number of partial images you requested if the full image is generated more quickly.
Responses API
Stream an image
import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI();
function saveBase64Image(filename, imageBase64) {
const imageBuffer = Buffer.from(imageBase64, "base64");
fs.writeFileSync(filename, imageBuffer);
}
const stream = await openai.responses.create({
model: "gpt-6-astra",
input:
"Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
stream: true,
tools: [
{ type: "image_generation", model: "gpt-image-2.5-sunburst", partial_images: 2 },
],
});
for await (const event of stream) {
if (event.type === "response.image_generation_call.partial_image") {
const idx = event.partial_image_index;
saveBase64Image(`river-partial-${idx}.png`, event.partial_image_b64);
} else if (event.type === "response.completed") {
const imageData = event.response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData.length > 0) {
saveBase64Image("river-final.png", imageData[0]);
}
}
}
from openai import OpenAI
import base64
client = OpenAI()
def save_base64_image(filename, image_base64):
image_bytes = base64.b64decode(image_base64)
with open(filename, "wb") as f:
f.write(image_bytes)
stream = client.responses.create(
model="gpt-6-astra",
input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
stream=True,
tools=[
{"type": "image_generation", "model": "gpt-image-2.5-sunburst", "partial_images": 2}
],
)
for event in stream:
if event.type == "response.image_generation_call.partial_image":
idx = event.partial_image_index
save_base64_image(f"river-partial-{idx}.png", event.partial_image_b64)
elif event.type == "response.completed":
image_data = [
output.result
for output in event.response.output
if output.type == "image_generation_call"
]
if image_data:
save_base64_image("river-final.png", image_data[0])
package main
import (
"context"
"encoding/base64"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{
OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),
},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst", PartialImages: openai.Int(2)}}},
})
for stream.Next() {
event := stream.Current()
if event.Type == "response.image_generation_call.partial_image" {
partial := event.AsResponseImageGenerationCallPartialImage()
saveImage(fmt.Sprintf("river-partial-%d.png", partial.PartialImageIndex), partial.PartialImageB64)
}
if event.Type == "response.completed" {
for _, output := range event.AsResponseCompleted().Response.Output {
if output.Type == "image_generation_call" {
saveImage("river-final.png", output.AsImageGenerationCall().Result)
}
}
}
}
if err := stream.Err(); err != nil {
panic(err)
}
}
func saveImage(filename, encoded string) {
image, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
import com.openai.models.responses.Tool;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Generate an image of a river made of white owl feathers.")
.addTool(Tool.ImageGeneration.builder().partialImages(2).build())
.build();
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
var events = stream.stream().iterator();
while (events.hasNext()) {
ResponseStreamEvent event = events.next();
if (event.imageGenerationCallPartialImage().isPresent()) {
var partial = event.imageGenerationCallPartialImage().orElseThrow();
Files.write(
Path.of("river-partial-" + partial.partialImageIndex() + ".png"),
Base64.getDecoder().decode(partial.partialImageB64()));
}
if (event.completed().isPresent()) {
var image =
event.completed().orElseThrow().response().output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No generated image returned"));
Files.write(
Path.of("river-final.png"),
Base64.getDecoder()
.decode(
image
.result()
.orElseThrow(
() -> new IllegalStateException("No final image returned"))));
}
}
}
require "base64"
require "openai"
client = OpenAI::Client.new
stream = client.responses.stream(
model: "gpt-6-astra",
input: "Generate an image of a river made of white owl feathers.",
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst", partial_images: 2}]
)
stream.each do |event|
case event
when OpenAI::Models::Responses::ResponseImageGenCallPartialImageEvent
image = Base64.strict_decode64(event.partial_image_b64)
File.binwrite("river-partial-#{event.partial_image_index}.png", image)
when OpenAI::Models::Responses::ResponseCompletedEvent
image_call = event.response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
next unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
File.binwrite(
"river-final.png",
Base64.strict_decode64(image_call.result)
)
end
end
Image API
Stream an image
import fs from "fs";
import OpenAI from "openai";
const openai = new OpenAI();
const prompt =
"Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape";
const stream = await openai.images.generate({
prompt: prompt,
model: "gpt-image-2.5-sunburst",
stream: true,
partial_images: 2,
});
for await (const event of stream) {
if (event.type === "image_generation.partial_image") {
const idx = event.partial_image_index;
const imageBase64 = event.b64_json;
const imageBuffer = Buffer.from(imageBase64, "base64");
fs.writeFileSync(`river${idx}.png`, imageBuffer);
}
}
from openai import OpenAI
import base64
client = OpenAI()
stream = client.images.generate(
prompt="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
model="gpt-image-2.5-sunburst",
stream=True,
partial_images=2,
)
for event in stream:
if event.type == "image_generation.partial_image":
idx = event.partial_image_index
image_base64 = event.b64_json
image_bytes = base64.b64decode(image_base64)
with open(f"river{idx}.png", "wb") as f:
f.write(image_bytes)
package main
import (
"context"
"encoding/base64"
"fmt"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
stream := client.Images.GenerateStreaming(context.Background(), openai.ImageGenerateParams{
Model: openai.ImageModel("gpt-image-2.5-sunburst"),
Prompt: "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
PartialImages: openai.Int(2),
})
for stream.Next() {
event := stream.Current()
if event.Type != "image_generation.partial_image" {
continue
}
partial := event.AsImageGenerationPartialImage()
saveImage(fmt.Sprintf("river%d.png", partial.PartialImageIndex), partial.B64JSON)
}
if err := stream.Err(); err != nil {
panic(err)
}
}
func saveImage(filename, encoded string) {
image, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
}
require "base64"
require "openai"
client = OpenAI::Client.new
stream = client.images.generate_stream_raw(
model: "gpt-image-2.5-sunburst",
prompt: "A river made of white owl feathers in a winter landscape",
partial_images: 2
)
stream.each do |event|
next unless event.is_a?(OpenAI::Models::ImageGenPartialImageEvent)
image = Base64.strict_decode64(event.b64_json)
File.binwrite("river#{event.partial_image_index}.png", image)
end
Result
| Partial 1 | Partial 2 | Final image |
|---|---|---|
![]() |
![]() |
![]() |
Prompt: Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape
Revised prompt
When using the image generation tool in the Responses API, the mainline model (for example, gpt-5.5) will automatically revise your prompt for improved performance.
You can access the revised prompt in the revised_prompt field of the image generation call:
Revised prompt response
{
"id": "ig_123",
"type": "image_generation_call",
"status": "completed",
"revised_prompt": "A gray tabby cat hugging an otter. The otter is wearing an orange scarf. Both animals are cute and friendly, depicted in a warm, heartwarming style.",
"result": "..."
}
Edit Images
The image edits endpoint lets you:
- Edit existing images
- Generate new images using other images as a reference
- Edit parts of an image by uploading an image and mask that identifies the areas to replace
Create a new image using image references
You can use one or more images as a reference to generate a new image.
In this example, we'll use 4 input images to generate a new image of a gift basket containing the items in the reference images.
Responses API
With the Responses API, you can provide input images in 3 different ways:
- By providing a fully qualified URL
- By providing an image as a Base64-encoded data URL
- By providing a file ID (created with the Files API)
Create a File
Create a File
import fs from "fs";
import OpenAI from "openai";
const openai = new OpenAI();
async function createFile(filePath) {
const fileContent = fs.createReadStream(filePath);
const result = await openai.files.create({
file: fileContent,
purpose: "vision",
});
return result.id;
}
from openai import OpenAI
client = OpenAI()
def create_file(file_path):
with open(file_path, "rb") as file_content:
result = client.files.create(
file=file_content,
purpose="vision",
)
return result.id
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
file, err := os.Open("image.png")
if err != nil {
panic(err)
}
defer file.Close()
uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{
File: file,
Purpose: openai.FilePurposeVision,
})
if err != nil {
panic(err)
}
fmt.Println(uploaded.ID)
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FilePurpose;
import java.nio.file.Path;
var file =
client
.files()
.create(
FileCreateParams.builder()
.file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))
.purpose(FilePurpose.VISION)
.build());
System.out.println(file.id());
require "openai"
require "pathname"
client = OpenAI::Client.new
file = client.files.create(
file: Pathname("image.png"),
purpose: OpenAI::Models::FilePurpose::VISION
)
puts(file.id)
Create a base64 encoded image
Create a base64 encoded image
import fs from "fs";
function encodeImage(filePath) {
const base64Image = fs.readFileSync(filePath, "base64");
return base64Image;
}
import base64
def encode_image(file_path):
with open(file_path, "rb") as f:
base64_image = base64.b64encode(f.read()).decode("utf-8")
return base64_image
package main
import (
"encoding/base64"
"fmt"
"os"
)
func main() {
image, err := os.ReadFile("image.png")
if err != nil {
panic(err)
}
fmt.Println(base64.StdEncoding.EncodeToString(image))
}
require "base64"
image = File.binread("image.png")
puts(Base64.strict_encode64(image))
Edit an image
import fs from "fs";
import OpenAI from "openai";
const openai = new OpenAI();
function encodeImage(filePath) {
return fs.readFileSync(filePath, "base64");
}
async function createFile(filePath) {
const result = await openai.files.create({
file: fs.createReadStream(filePath),
purpose: "vision",
});
return result.id;
}
const prompt = `Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.`;
const base64Image1 = encodeImage("fixtures/body-lotion.png");
const base64Image2 = encodeImage("fixtures/soap.png");
const fileId1 = await createFile("fixtures/bath-bomb.png");
const fileId2 = await createFile("fixtures/incense-kit.png");
const response = await openai.responses.create({
model: "gpt-6-astra",
input: [
{
role: "user",
content: [
{ type: "input_text", text: prompt },
{
type: "input_image",
image_url: `data:image/png;base64,${base64Image1}`,
detail: "auto",
},
{
type: "input_image",
image_url: `data:image/png;base64,${base64Image2}`,
detail: "auto",
},
{
type: "input_image",
file_id: fileId1,
detail: "auto",
},
{
type: "input_image",
file_id: fileId2,
detail: "auto",
},
],
},
],
tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
});
const imageData = response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData.length > 0) {
const imageBase64 = imageData[0];
fs.writeFileSync("gift-basket.png", Buffer.from(imageBase64, "base64"));
} else {
console.log(response.output_text);
}
from openai import OpenAI
import base64
client = OpenAI()
def encode_image(file_path):
with open(file_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
def create_file(file_path):
with open(file_path, "rb") as file_content:
result = client.files.create(file=file_content, purpose="vision")
return result.id
prompt = """Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures."""
base64_image1 = encode_image("body-lotion.png")
base64_image2 = encode_image("soap.png")
file_id1 = create_file("bath-bomb.png")
file_id2 = create_file("incense-kit.png")
response = client.responses.create(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{
"type": "input_image",
"image_url": f"data:image/png;base64,{base64_image1}",
},
{
"type": "input_image",
"image_url": f"data:image/png;base64,{base64_image2}",
},
{
"type": "input_image",
"file_id": file_id1,
},
{
"type": "input_image",
"file_id": file_id2,
},
],
}
],
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_generation_calls = [
output for output in response.output if output.type == "image_generation_call"
]
image_data = [output.result for output in image_generation_calls]
if image_data:
image_base64 = image_data[0]
with open("gift-basket.png", "wb") as f:
f.write(base64.b64decode(image_base64))
else:
print(response.output_text)
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
bathBombID := uploadImage(client, "bath-bomb.png")
incenseKitID := uploadImage(client, "incense-kit.png")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(
responses.ResponseInputMessageContentListParam{
responses.ResponseInputContentParamOfInputText("Generate a photorealistic image of a gift basket on a white background labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures."),
{OfInputImage: &responses.ResponseInputImageParam{ImageURL: openai.String(dataURL("body-lotion.png")), Detail: responses.ResponseInputImageDetailAuto}},
{OfInputImage: &responses.ResponseInputImageParam{ImageURL: openai.String(dataURL("soap.png")), Detail: responses.ResponseInputImageDetailAuto}},
{OfInputImage: &responses.ResponseInputImageParam{FileID: openai.String(bathBombID), Detail: responses.ResponseInputImageDetailAuto}},
{OfInputImage: &responses.ResponseInputImageParam{FileID: openai.String(incenseKitID), Detail: responses.ResponseInputImageDetailAuto}},
},
responses.EasyInputMessageRoleUser,
),
}},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
})
if err != nil {
panic(err)
}
saveFirstGeneratedImage(response, "gift-basket.png")
}
func uploadImage(client openai.Client, filename string) string {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{File: file, Purpose: openai.FilePurposeVision})
if err != nil {
panic(err)
}
return uploaded.ID
}
func dataURL(filename string) string {
image, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(image)
}
func saveFirstGeneratedImage(response *responses.Response, filename string) {
for _, output := range response.Output {
if output.Type != "image_generation_call" {
continue
}
image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
return
}
panic("response did not include an image generation call")
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FilePurpose;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.Tool;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;
Path lotionImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"));
Path soapImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_2"));
Path bathBombImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_3"));
Path incenseImage = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_4"));
String lotionBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(lotionImage));
String soapBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(soapImage));
var firstFile =
client
.files()
.create(
FileCreateParams.builder().file(bathBombImage).purpose(FilePurpose.VISION).build());
var secondFile =
client
.files()
.create(
FileCreateParams.builder().file(incenseImage).purpose(FilePurpose.VISION).build());
String prompt =
"""
Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.
""";
var input =
ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent(prompt)
.addContent(
ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.imageUrl("data:image/png;base64," + lotionBase64)
.build())
.addContent(
ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.imageUrl("data:image/png;base64," + soapBase64)
.build())
.addContent(
ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.fileId(firstFile.id())
.build())
.addContent(
ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.fileId(secondFile.id())
.build())
.build());
var response =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(List.of(input))
.addTool(Tool.ImageGeneration.builder().build())
.build());
var image =
response.output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No image generation call returned"));
Files.write(
Path.of("gift-basket.png"),
Base64.getDecoder()
.decode(
image.result().orElseThrow(() -> new IllegalStateException("No image returned"))));
require "base64"
require "openai"
require "pathname"
client = OpenAI::Client.new
base64_images = ["body-lotion.png", "soap.png"].map do |path|
Base64.strict_encode64(File.binread(path))
end
file_ids = [
client.files.create(file: Pathname("bath-bomb.png"), purpose: :vision).id,
client.files.create(file: Pathname("incense-kit.png"), purpose: :vision).id
]
prompt = <<~PROMPT
Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.
PROMPT
response = client.responses.create(
model: "gpt-6-astra",
input: [{
role: :user,
content: [
{type: :input_text, text: prompt},
*base64_images.map do |image|
{type: :input_image, image_url: "data:image/png;base64,#{image}"}
end,
*file_ids.map do |file_id|
{type: :input_image, file_id: file_id}
end
]
}],
tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
)
image_call = response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No image generation call returned"
end
File.binwrite("gift-basket.png", Base64.strict_decode64(image_call.result))
Image API
Edit an image
import fs from "fs";
import OpenAI, { toFile } from "openai";
const client = new OpenAI();
const prompt = `
Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.
`;
const imageFiles = [
"fixtures/bath-bomb.png",
"fixtures/body-lotion.png",
"fixtures/incense-kit.png",
"fixtures/soap.png",
];
const images = await Promise.all(
imageFiles.map(
async (file) =>
await toFile(fs.createReadStream(file), null, {
type: "image/png",
})
)
);
const response = await client.images.edit({
model: "gpt-image-2.5-sunburst",
image: images,
prompt,
});
// Save the image to a file
const image_base64 = response.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("basket.png", image_bytes);
import base64
from openai import OpenAI
client = OpenAI()
prompt = """
Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.
"""
result = client.images.edit(
model="gpt-image-2.5-sunburst",
image=[
open("body-lotion.png", "rb"),
open("bath-bomb.png", "rb"),
open("incense-kit.png", "rb"),
open("soap.png", "rb"),
],
prompt=prompt,
)
image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
# Save the image to a file
with open("gift-basket.png", "wb") as f:
f.write(image_bytes)
package main
import (
"context"
"encoding/base64"
"io"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
files, closeFiles := openImages(
"bath-bomb.png",
"body-lotion.png",
"incense-kit.png",
"soap.png",
)
defer closeFiles()
response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{
Model: openai.ImageModel("gpt-image-2.5-sunburst"),
Image: openai.ImageEditParamsImageUnion{OfFileArray: files},
Prompt: "Generate a photorealistic image of a gift basket on a white background " +
"labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures.",
})
if err != nil {
panic(err)
}
saveImage("basket.png", response.Data[0].B64JSON)
}
func openImages(names ...string) ([]io.Reader, func()) {
images := make([]io.Reader, 0, len(names))
files := make([]*os.File, 0, len(names))
for _, name := range names {
file, err := os.Open(name)
if err != nil {
closeFiles(files)
panic(err)
}
images = append(images, openai.File(file, name, "image/png"))
files = append(files, file)
}
return images, func() { closeFiles(files) }
}
func closeFiles(files []*os.File) {
for _, file := range files {
if err := file.Close(); err != nil {
panic(err)
}
}
}
func saveImage(filename, encoded string) {
image, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.MultipartField;
import com.openai.models.images.ImageEditParams;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;
Path lotion = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH"));
Path soap = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_2"));
Path bathBomb = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_3"));
Path incense = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_PATH_4"));
try (InputStream lotionImage = Files.newInputStream(lotion);
InputStream bathBombImage = Files.newInputStream(bathBomb);
InputStream incenseImage = Files.newInputStream(incense);
InputStream soapImage = Files.newInputStream(soap)) {
var images =
client
.images()
.edit(
ImageEditParams.builder()
.model("gpt-image-2.5-sunburst")
.image(
MultipartField.<ImageEditParams.Image>builder()
.value(
ImageEditParams.Image.ofInputStreams(
List.of(lotionImage, bathBombImage, incenseImage, soapImage)))
.contentType("image/png")
.filename("gift-basket-reference.png")
.build())
.prompt(
"""
Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.
""")
.build());
Files.write(
Path.of("gift-basket.png"),
Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));
}
require "base64"
require "openai"
require "pathname"
client = OpenAI::Client.new
images = %w[body-lotion.png bath-bomb.png incense-kit.png soap.png].map do |path|
Pathname(path)
end
result = client.images.edit(
image: images,
model: "gpt-image-2.5-sunburst",
prompt: <<~PROMPT
Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures.
PROMPT
)
generated_image = result.data&.first or raise "No image returned"
File.binwrite("gift-basket.png", Base64.strict_decode64(generated_image.b64_json))
curl -s -D >(grep -i x-request-id >&2) \
-o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \
-X POST "https://api.openai.com/v1/images/edits" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F "model=gpt-image-2.5-sunburst" \
-F "image[]=@body-lotion.png" \
-F "image[]=@bath-bomb.png" \
-F "image[]=@incense-kit.png" \
-F "image[]=@soap.png" \
-F 'prompt=Generate a photorealistic image of a gift basket on a white background labeled "Relax & Unwind" with a ribbon and handwriting-like font, containing all the items in the reference pictures'
openai images edit \
--model gpt-image-2.5-sunburst \
--image body-lotion.png \
--image bath-bomb.png \
--image incense-kit.png \
--image soap.png \
--prompt 'Generate a photorealistic image of a gift basket on a white background labeled "Relax & Unwind" with a ribbon and handwriting-like font, containing all the items in the reference pictures' \
--raw-output \
--transform 'data.0.b64_json' | base64 --decode > gift-basket.png
Edit an image using a mask
You can provide a mask to indicate which part of the image should be edited.
When using a mask with GPT Image, additional instructions are sent to the model to help guide the editing process accordingly.
Masking with GPT Image is entirely prompt-based. The model uses the mask as guidance, but may not follow its exact shape with complete precision.
If you provide multiple input images, the mask will be applied to the first image.
Responses API
Edit an image with a mask
import fs from "fs";
import OpenAI from "openai";
const openai = new OpenAI();
async function createFile(filePath) {
const result = await openai.files.create({
file: fs.createReadStream(filePath),
purpose: "vision",
});
return result.id;
}
const fileId = await createFile("fixtures/sunlit_lounge.png");
const maskId = await createFile("fixtures/mask.png");
const response = await openai.responses.create({
model: "gpt-6-astra",
input: [
{
role: "user",
content: [
{
type: "input_text",
text: "generate an image of the same sunlit indoor lounge area with a pool but the pool should contain a flamingo",
},
{
type: "input_image",
file_id: fileId,
detail: "auto",
},
],
},
],
tools: [
{
type: "image_generation",
model: "gpt-image-2.5-sunburst",
quality: "high",
input_image_mask: {
file_id: maskId,
},
},
],
});
const imageData = response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);
if (imageData.length > 0) {
const imageBase64 = imageData[0];
fs.writeFileSync("lounge.png", Buffer.from(imageBase64, "base64"));
}
from openai import OpenAI
import base64
client = OpenAI()
def create_file(file_path):
with open(file_path, "rb") as file_content:
result = client.files.create(file=file_content, purpose="vision")
return result.id
fileId = create_file("sunlit_lounge.png")
maskId = create_file("mask.png")
response = client.responses.create(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "generate an image of the same sunlit indoor lounge area with a pool but the pool should contain a flamingo",
},
{
"type": "input_image",
"file_id": fileId,
},
],
},
],
tools=[
{
"type": "image_generation",
"model": "gpt-image-2.5-sunburst",
"quality": "high",
"input_image_mask": {
"file_id": maskId,
},
},
],
)
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("lounge.png", "wb") as f:
f.write(base64.b64decode(image_base64))
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
imageID := uploadImage(client, "sunlit_lounge.png")
maskID := uploadImage(client, "mask.png")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage(
responses.ResponseInputMessageContentListParam{
responses.ResponseInputContentParamOfInputText("Generate an image of the same sunlit indoor lounge area with a pool, but the pool should contain a flamingo."),
{OfInputImage: &responses.ResponseInputImageParam{FileID: openai.String(imageID), Detail: responses.ResponseInputImageDetailAuto}},
},
responses.EasyInputMessageRoleUser,
),
}},
Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{
Model: "gpt-image-2.5-sunburst",
Quality: "high",
InputImageMask: responses.ToolImageGenerationInputImageMaskParam{FileID: openai.String(maskID)},
}}},
})
if err != nil {
panic(err)
}
saveFirstGeneratedImage(response, "lounge.png")
}
func uploadImage(client openai.Client, filename string) string {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{File: file, Purpose: openai.FilePurposeVision})
if err != nil {
panic(err)
}
return uploaded.ID
}
func saveFirstGeneratedImage(response *responses.Response, filename string) {
for _, output := range response.Output {
if output.Type != "image_generation_call" {
continue
}
image, err := base64.StdEncoding.DecodeString(output.AsImageGenerationCall().Result)
if err != nil {
panic(err)
}
if err := os.WriteFile(filename, image, 0o600); err != nil {
panic(err)
}
return
}
panic("response did not include an image generation call")
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FilePurpose;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputImage;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.Tool;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.List;
var image =
client
.files()
.create(
FileCreateParams.builder()
.file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))
.purpose(FilePurpose.VISION)
.build());
var mask =
client
.files()
.create(
FileCreateParams.builder()
.file(Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_MASK_PATH")))
.purpose(FilePurpose.VISION)
.build());
var response =
client
.responses()
.create(
ResponseCreateParams.builder()
.model("gpt-6-astra")
.inputOfResponse(
List.of(
ResponseInputItem.ofMessage(
ResponseInputItem.Message.builder()
.role(ResponseInputItem.Message.Role.USER)
.addInputTextContent("Add a flamingo to the pool.")
.addContent(
ResponseInputImage.builder()
.detail(ResponseInputImage.Detail.AUTO)
.fileId(image.id())
.build())
.build())))
.addTool(
Tool.ImageGeneration.builder()
.inputImageMask(
Tool.ImageGeneration.InputImageMask.builder()
.fileId(mask.id())
.build())
.build())
.build());
String imageResult =
response.output().stream()
.flatMap(item -> item.imageGenerationCall().stream())
.flatMap(call -> call.result().stream())
.findFirst()
.orElseThrow(() -> new IllegalStateException("No generated image returned"));
Files.write(Path.of("lounge.png"), Base64.getDecoder().decode(imageResult));
require "base64"
require "openai"
require "pathname"
client = OpenAI::Client.new
image = client.files.create(file: Pathname("sunlit_lounge.png"), purpose: :vision)
mask = client.files.create(file: Pathname("mask.png"), purpose: :vision)
response = client.responses.create(
model: "gpt-6-astra",
input: [{
role: :user,
content: [
{type: :input_text, text: "Add a flamingo to the pool."},
{type: :input_image, file_id: image.id}
]
}],
tools: [{
type: :image_generation, model: "gpt-image-2.5-sunburst",
input_image_mask: {file_id: mask.id}
}]
)
image_call = response.output.find do |item|
item.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
end
unless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall)
raise "No image generation call returned"
end
File.binwrite("lounge.png", Base64.strict_decode64(image_call.result))
Image API
Edit an image with a mask
import fs from "fs";
import OpenAI, { toFile } from "openai";
const client = new OpenAI();
const rsp = await client.images.edit({
model: "gpt-image-2.5-sunburst",
image: await toFile(fs.createReadStream("fixtures/sunlit_lounge.png"), null, {
type: "image/png",
}),
mask: await toFile(fs.createReadStream("fixtures/mask.png"), null, {
type: "image/png",
}),
prompt: "A sunlit indoor lounge area with a pool containing a flamingo",
});
// Save the image to a file
const image_base64 = rsp.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("lounge.png", image_bytes);
from openai import OpenAI
import base64
client = OpenAI()
result = client.images.edit(
model="gpt-image-2.5-sunburst",
image=open("sunlit_lounge.png", "rb"),
mask=open("mask.png", "rb"),
prompt="A sunlit indoor lounge area with a pool containing a flamingo",
)
image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
# Save the image to a file
with open("composition.png", "wb") as f:
f.write(image_bytes)
package main
import (
"context"
"encoding/base64"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
image, err := os.Open("sunlit_lounge.png")
if err != nil {
panic(err)
}
defer image.Close()
mask, err := os.Open("mask.png")
if err != nil {
panic(err)
}
defer mask.Close()
response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{
Model: openai.ImageModel("gpt-image-2.5-sunburst"),
Image: openai.ImageEditParamsImageUnion{OfFile: openai.File(image, "sunlit_lounge.png", "image/png")},
Mask: openai.File(mask, "mask.png", "image/png"),
Prompt: "A sunlit indoor lounge area with a pool containing a flamingo",
})
if err != nil {
panic(err)
}
result, err := base64.StdEncoding.DecodeString(response.Data[0].B64JSON)
if err != nil {
panic(err)
}
if err := os.WriteFile("lounge.png", result, 0o600); err != nil {
panic(err)
}
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.MultipartField;
import com.openai.models.images.ImageEditParams;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
Path imagePath = Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH"));
Path maskPath = Path.of(System.getenv("OPENAI_EXAMPLE_IMAGE_MASK_PATH"));
try (InputStream image = Files.newInputStream(imagePath);
InputStream mask = Files.newInputStream(maskPath)) {
var images =
client
.images()
.edit(
ImageEditParams.builder()
.model("gpt-image-2.5-sunburst")
.image(
MultipartField.<ImageEditParams.Image>builder()
.value(ImageEditParams.Image.ofInputStream(image))
.contentType("image/png")
.filename(imagePath.getFileName().toString())
.build())
.prompt("A sunlit indoor lounge area with a pool containing a flamingo")
.mask(
MultipartField.<InputStream>builder()
.value(mask)
.contentType("image/png")
.filename(maskPath.getFileName().toString())
.build())
.build());
Files.write(
Path.of("lounge.png"),
Base64.getDecoder().decode(images.data().orElseThrow().get(0).b64Json().orElseThrow()));
}
require "openai"
require "pathname"
require "base64"
client = OpenAI::Client.new
image = Pathname("sunlit_lounge.png")
mask = Pathname("mask.png")
result = client.images.edit(
image: image,
mask: mask,
model: "gpt-image-2.5-sunburst",
prompt: "A sunlit indoor lounge area with a pool containing a flamingo"
)
generated_image = result.data&.first or raise "No image returned"
File.binwrite("lounge.png", Base64.strict_decode64(generated_image.b64_json))
curl -s -D >(grep -i x-request-id >&2) \
-o >(jq -r '.data[0].b64_json' | base64 --decode > lounge.png) \
-X POST "https://api.openai.com/v1/images/edits" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F "model=gpt-image-2.5-sunburst" \
-F "mask=@mask.png" \
-F "image[]=@sunlit_lounge.png" \
-F 'prompt=A sunlit indoor lounge area with a pool containing a flamingo'
openai images edit \
--model gpt-image-2.5-sunburst \
--image sunlit_lounge.png \
--mask mask.png \
--prompt "A sunlit indoor lounge area with a pool containing a flamingo" \
--raw-output \
--transform 'data.0.b64_json' | base64 --decode > out.png
| Image | Mask | Output |
|---|---|---|
![]() |
![]() |
![]() |
Prompt: a sunlit indoor lounge area with a pool containing a flamingo
Mask requirements
The image to edit and mask must be of the same format and size (less than 50MB in size).
The mask image must also contain an alpha channel. If you're using an image editing tool to create the mask, make sure to save the mask with an alpha channel.
You can modify a black and white image programmatically to add an alpha channel.
Add an alpha channel to a black and white mask
from PIL import Image
from io import BytesIO
# 1. Load your black & white mask as a grayscale image
mask = Image.open("mask.png").convert("L")
# 2. Convert it to RGBA so it has space for an alpha channel
mask_rgba = mask.convert("RGBA")
# 3. Then use the mask itself to fill that alpha channel
mask_rgba.putalpha(mask)
# 4. Convert the mask into bytes
buf = BytesIO()
mask_rgba.save(buf, format="PNG")
mask_bytes = buf.getvalue()
# 5. Save the resulting file
img_path_mask_alpha = "mask_alpha.png"
with open(img_path_mask_alpha, "wb") as f:
f.write(mask_bytes)
package main
import (
"image"
"image/color"
"image/png"
"os"
)
func main() {
file, err := os.Open("mask.png")
if err != nil {
panic(err)
}
defer file.Close()
mask, _, err := image.Decode(file)
if err != nil {
panic(err)
}
bounds := mask.Bounds()
withAlpha := image.NewNRGBA(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
gray := color.GrayModel.Convert(mask.At(x, y)).(color.Gray)
withAlpha.SetNRGBA(x, y, color.NRGBA{R: gray.Y, G: gray.Y, B: gray.Y, A: gray.Y})
}
}
output, err := os.Create("mask_alpha.png")
if err != nil {
panic(err)
}
if err := png.Encode(output, withAlpha); err != nil {
panic(err)
}
if err := output.Close(); err != nil {
panic(err)
}
}
Customize Image Output
You can configure the following output options:
- Size: Image dimensions (for example,
1024x1024,1024x1536) - Quality: Rendering quality (for example,
low,medium,high) - Format: File output format
- Compression: Compression level (0-100%) for JPEG and WebP formats
- Background: Transparent, opaque, or automatic
size, quality, and background support the auto option, where the model will automatically select the best option based on the prompt.
Size and quality options
gpt-image-2.5-sunburst and gpt-image-2.5-flare add xhigh and max quality settings. Both default to auto. Earlier GPT Image models support quality settings up to high.
| Setting | Options |
|---|---|
| Recommended sizes | 1024x1024 (square), 1536x1024 (landscape), 1024x1536 (portrait) |
| Quality | low, medium, high, xhigh, max, auto |
Both models also support custom dimensions as WIDTHxHEIGHT strings, such as 1536x864. Width and height must be multiples of 16, the aspect ratio must be between 1:3 and 3:1, and neither edge may exceed 3840 pixels. The total pixel count must be between 655,360 and 8,294,400 (4K). Resolutions above 2560x1440 are experimental.
For transparent backgrounds with either model, set background: "transparent" and use output_format: "png" or "webp".
Use quality: "low" for quick drafts. For final assets, compare higher quality settings to find the right balance of detail, latency, and cost.
Output format
The Image API returns base64-encoded image data.
The default format is png, but you can also request jpeg or webp.
If using jpeg or webp, you can also specify the output_compression parameter to control the compression level (0-100%). For example, output_compression=50 will compress the image by 50%.
Using jpeg is faster than png, so you should prioritize this format if
latency is a concern.
Limitations
GPT Image models are powerful and versatile image generation models, but they still have some limitations to be aware of:
- Latency: Complex prompts may take up to 2 minutes to process.
- Text Rendering: Although significantly improved, the model can still struggle with precise text placement and clarity.
- Consistency: While capable of producing consistent imagery, the model may occasionally struggle to maintain visual consistency for recurring characters or brand elements across multiple generations.
- Composition Control: Despite improved instruction following, the model may have difficulty placing elements precisely in structured or layout-sensitive compositions.
Content Moderation
All prompts and generated images are filtered in accordance with our content policy.
For image generation using GPT Image models, you can control moderation strictness with the moderation parameter. This parameter supports two values:
auto(default): Standard filtering that seeks to limit creating certain categories of potentially age-inappropriate content.low: Less restrictive filtering.
Handling blocked requests and other errors
Handle image generation failures the same way you handle other API errors: check the HTTP status or SDK exception type, log the request ID, and refer to the error codes guide for authentication, quota, rate-limit, and server failures. Retry transient rate-limit and server failures with backoff. Don't automatically retry quota errors or image generation user errors that require changing the request.
Some image generation failures are user-correctable and may return error.type = "image_generation_user_error". Don't automatically retry these errors without modifying the prompt or input images. For programmatic handling, use error.code as the stable discriminator.
When error.code = "moderation_blocked", the error may also include an optional error.moderation_details object:
{
"error": {
"type": "image_generation_user_error",
"code": "moderation_blocked",
"moderation_details": {
"moderation_stage": "input",
"categories": ["harassment"]
}
}
}
The moderation_details object provides coarse debugging context without exposing internal classifier labels or scores.
moderation_stage can be:
input: The block came from the prompt or request inputs.output: The block came from a generated image or downstream output moderation stage.unknown: A rare fallback when provenance is hard to determine.
categories contains coarse public labels. For example, you might see values like harassment, self-harm, sexual, or violence.
For most apps, keep the primary end-user message generic. Use moderation_details for developer logs, support workflows, analytics, and light remediation hints.
Handle moderation-blocked image generation errors
import OpenAI from "openai";
const openai = new OpenAI();
try {
// The same error handling pattern applies to image generation requests,
// image edits, and Responses API tool calls that generate images.
await openai.images.generate({
model: "gpt-image-2.5-sunburst",
prompt: "Create a poster humiliating my coworker with insulting captions",
});
} catch (error) {
if (error?.code !== "moderation_blocked") {
throw error;
}
const moderationDetails = error.error?.moderation_details;
const categories = moderationDetails?.categories ?? [];
const stage = moderationDetails?.moderation_stage;
let hint =
"This request could not be completed because it did not meet safety requirements.";
if (categories.includes("harassment")) {
hint =
"Try removing abusive or targeting language and focus on neutral visual details instead.";
} else if (stage === "input") {
hint =
"Try revising the prompt or input images and submit the request again.";
} else if (stage === "output") {
hint =
"The generated result was blocked by a safety check. Try changing the prompt and generating again.";
}
console.error("Image generation blocked", {
request_id: error?.requestID,
code: error?.code,
moderation_details: moderationDetails,
});
console.log(hint);
}
import openai
from openai import OpenAI
client = OpenAI()
try:
# The same error handling pattern applies to image generation requests,
# image edits, and Responses API tool calls that generate images.
client.images.generate(
model="gpt-image-2.5-sunburst",
prompt="Create a poster humiliating my coworker with insulting captions",
)
except openai.BadRequestError as error:
if error.code != "moderation_blocked":
raise
error_body = error.body if isinstance(error.body, dict) else {}
moderation_details = error_body.get("moderation_details") or {}
categories = moderation_details.get("categories") or []
stage = moderation_details.get("moderation_stage")
hint = "This request could not be completed because it did not meet safety requirements."
if "harassment" in categories:
hint = "Try removing abusive or targeting language and focus on neutral visual details instead."
elif stage == "input":
hint = "Try revising the prompt or input images and submit the request again."
elif stage == "output":
hint = "The generated result was blocked by a safety check. Try changing the prompt and generating again."
print(
"Image generation blocked",
{
"request_id": error.request_id,
"code": error.code,
"moderation_details": moderation_details,
},
)
print(hint)
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
_, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{
Model: openai.ImageModel("gpt-image-2.5-sunburst"),
Prompt: "Create a poster humiliating my coworker with insulting captions",
})
if err == nil {
return
}
var apiError *openai.Error
if !errors.As(err, &apiError) || apiError.Code != "moderation_blocked" {
panic(err)
}
var body struct {
ModerationDetails struct {
Categories []string `json:"categories"`
ModerationStage string `json:"moderation_stage"`
} `json:"moderation_details"`
}
if err := json.Unmarshal([]byte(apiError.RawJSON()), &body); err != nil {
panic(err)
}
hint := "This request could not be completed because it did not meet safety requirements."
if slices.Contains(body.ModerationDetails.Categories, "harassment") {
hint = "Try removing abusive or targeting language and focus on neutral visual details instead."
} else if body.ModerationDetails.ModerationStage == "input" {
hint = "Try revising the prompt or input images and submit the request again."
} else if body.ModerationDetails.ModerationStage == "output" {
hint = "The generated result was blocked by a safety check. Try changing the prompt and generating again."
}
fmt.Printf("Image generation blocked (%s): %s\n", apiError.Code, hint)
}
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.errors.BadRequestException;
import com.openai.models.images.ImageGenerateParams;
import java.util.List;
import java.util.Map;
try {
var images =
client
.images()
.generate(
ImageGenerateParams.builder()
.model("gpt-image-2.5-sunburst")
.prompt("Create a poster humiliating my coworker with insulting captions")
.build());
System.out.println(images.data().orElseThrow().get(0).b64Json().orElseThrow());
} catch (BadRequestException error) {
if (!error.code().orElse("").equals("moderation_blocked")) {
throw error;
}
Map<?, ?> body = error.body().convert(Map.class);
Object detailsValue = body.get("moderation_details");
Map<?, ?> details = detailsValue instanceof Map<?, ?> values ? values : Map.of();
Object categories = details.get("categories");
Object stage = details.get("moderation_stage");
String hint = "This request did not meet safety requirements.";
if (categories instanceof List<?> values && values.contains("harassment")) {
hint = "Remove abusive or targeting language and focus on neutral visual details.";
} else if ("input".equals(stage)) {
hint = "Revise the prompt or input images, then submit the request again.";
} else if ("output".equals(stage)) {
hint = "Change the prompt and generate again; the generated result was blocked.";
}
System.err.println("Image generation blocked (" + error.code().orElseThrow() + "): " + hint);
}
require "openai"
client = OpenAI::Client.new
begin
client.images.generate(
model: "gpt-image-2.5-sunburst",
prompt: "Create a poster humiliating my coworker with insulting captions"
)
rescue OpenAI::Errors::BadRequestError => error
raise unless error.code == "moderation_blocked"
body = Hash.try_convert(error.body) || {}
moderation_details = body[:moderation_details] || body["moderation_details"] || {}
categories = moderation_details[:categories] || moderation_details["categories"] || []
stage = moderation_details[:moderation_stage] || moderation_details["moderation_stage"]
hint = "This request did not meet safety requirements."
if categories.include?("harassment")
hint = "Remove abusive or targeting language and focus on neutral visual details."
elsif stage == "input"
hint = "Revise the prompt or input images, then submit the request again."
elsif stage == "output"
hint = "Change the prompt and generate again; the generated result was blocked."
end
warn("Image generation blocked (#{error.code}): #{hint}")
end
Supported models
When using image generation in the Responses API, gpt-5 and newer models should support the image generation tool. Check the model detail page for your model to confirm if your desired model can use the image generation tool.
Cost and latency
GPT Image 2.5 costs
Responses API requests include the mainline model's token usage in addition to image generation costs.
Both GPT Image 2.5 models use the same token rates: $8 per million image input tokens, $2 per million cached image input tokens, $30 per million image output tokens, $5 per million text input tokens, and $1.25 per million cached text input tokens. See pricing.
Use the response's usage to measure token consumption for your prompts, sizes, and quality settings. Equal token rates don't mean equal cost per image: token consumption can differ by model and quality setting. For older-model pricing examples, see Earlier GPT Image models.
GPT Image 2.5 and GPT Image 2 output tokens
Select a model, quality, and size to estimate output tokens and image output cost.
For gpt-image-2.5-sunburst and gpt-image-2.5-flare, the quality options are low, medium, high, xhigh, and max.
For gpt-image-2, the options are low, medium, and high.
The models can use different token counts for the same quality setting and share the same price per image output token.
Use explicit quality and size values for this estimate; auto depends on the generated image.
<GptImageTokenCalculator client:load outputPricePerMillion={Number( pricing.latest.subsections .find((section) => section.price_type === "Image tokens") ?.items.find((item) => item.name === "gpt-image-2")?.values.main.output )} />
Partial images cost
If you want to stream image generation using the partial_images parameter, each partial image will incur an additional 100 image output tokens.
Earlier GPT Image models
The details below apply to earlier models, not Sunburst or Flare. For new integrations, use one of the GPT Image 2.5 models described above.
GPT Image 2 settings and input fidelity
gpt-image-2 accepts any resolution in the size parameter when it satisfies the constraints below. Square images are typically fastest to generate.
| Popular sizes |
|
| Size constraints |
|
| Quality options |
|
Image input fidelity
The input_fidelity parameter controls how strongly a model preserves details from input images during edits and reference-image workflows. For gpt-image-2, omit this parameter; the API doesn't allow changing it because the model processes every image input at high fidelity automatically.
Because gpt-image-2 always processes image inputs at high fidelity, image
input tokens can be higher for edit requests that include reference images. To
understand the cost implications, refer to the vision
costs
section.
Older-model pricing examples
Models prior to gpt-image-2
GPT Image models prior to gpt-image-2 generate images by first producing specialized image tokens. Both latency and eventual cost are proportional to the number of tokens required to render an image—larger image sizes and higher quality settings result in more tokens.
The number of tokens generated depends on image dimensions and quality:
| Quality | Square (1024×1024) | Portrait (1024×1536) | Landscape (1536×1024) |
|---|---|---|---|
| Low | 272 tokens | 408 tokens | 400 tokens |
| Medium | 1056 tokens | 1584 tokens | 1568 tokens |
| High | 4160 tokens | 6240 tokens | 6208 tokens |
Note that you will also need to account for input tokens: text tokens for the prompt and image tokens for the input images if editing images.
Because gpt-image-2 always processes image inputs at high fidelity, edit requests that include reference images can use more input tokens.
Refer to the pricing page for current text and image token prices, and use the Calculating costs section below to estimate request costs.
The final cost is the sum of:
- input text tokens
- input image tokens if using the edits endpoint
- image output tokens
Calculating costs
Use the pricing calculator below to estimate request costs for GPT Image models.
gpt-image-2 supports thousands of valid resolutions; the table below lists the
same sizes used for previous GPT Image models for comparison. For GPT Image 1.5,
GPT Image 1, and GPT Image 1 Mini, the legacy per-image output pricing table is
also listed below. You should still account for text and image input tokens when
estimating the total cost of a request.
A larger non-square resolution can sometimes produce fewer output tokens than a smaller or square resolution at the same quality setting.
| Model | Quality | 1024 x 1024 | 1024 x 1536 | 1536 x 1024 |
|---|---|---|---|---|
|
GPT Image 2
Additional sizes available
|
guides/image-generation.md +237 −191
4 4
5## Overview5## Overview
6 6
77The OpenAI API lets you generate and edit images from text prompts using GPT Image models, including our latest, `gpt-image-2`. You can access image generation capabilities through two APIs:The API lets you generate and edit images from text prompts using `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare`. Choose Sunburst for workflows where editing precision matters most, and Flare for fast, high-quality everyday image generation. You can access image generation capabilities through two APIs:
8 8
9### Image API9### Image API
10 10
1111Starting with `gpt-image-1` and later models, the [Image API](https://developers.openai.com/api/reference/resources/images) provides two endpoints, each with distinct capabilities:The [Image API](https://developers.openai.com/api/reference/resources/images) provides two endpoints, each with distinct capabilities:
12 12
13- **Generations**: [Generate images](#generate-images) from scratch based on a text prompt13- **Generations**: [Generate images](#generate-images) from scratch based on a text prompt
14- **Edits**: [Modify existing images](#edit-images) using a new prompt, either partially or entirely14- **Edits**: [Modify existing images](#edit-images) using a new prompt, either partially or entirely
22- **Multi-turn editing**: Iteratively make high fidelity edits to images with prompting22- **Multi-turn editing**: Iteratively make high fidelity edits to images with prompting
23- **Flexible inputs**: Accept image [File](https://developers.openai.com/api/reference/resources/files) IDs as input images, not just bytes23- **Flexible inputs**: Accept image [File](https://developers.openai.com/api/reference/resources/files) IDs as input images, not just bytes
24 24
2525The Responses API image generation tool uses its own GPT Image model selection. For details on mainline models that support calling this tool, refer to the [supported models](#supported-models) below.For mainline models that can call the image generation tool, refer to [supported models](#supported-models).
26 26
27### Choosing the right API27### Choosing the right API
28 28
29- If you only need to generate or edit a single image from one prompt, the Image API is your best choice.29- If you only need to generate or edit a single image from one prompt, the Image API is your best choice.
30- If you want to build conversational, editable image experiences with GPT Image, go with the Responses API.30- If you want to build conversational, editable image experiences with GPT Image, go with the Responses API.
31 31
3232With the Image API, you choose a GPT Image model directly. With the Responses API, you choose a mainline model that supports the image generation tool; the tool handles GPT Image model selection. Responses API requests include the mainline model's token usage in addition to image generation costs.With the Image API, set `model` to `gpt-image-2.5-sunburst` or `gpt-image-2.5-flare` directly. With the Responses API, select a supported mainline model at the top level and specify `gpt-image-2.5-sunburst` or `gpt-image-2.5-flare` in the image generation tool's `model` field.
33 33
3434Both APIs let you [customize output](#customize-image-output) by adjusting quality, size, format, and compression. Transparent backgrounds depend on model support.Both APIs let you [customize output](#customize-image-output) by adjusting quality, size, format, and compression.
35
36This guide focuses on GPT Image.
37 35
38To ensure these models are used responsibly, you may need to complete the [API36To ensure these models are used responsibly, you may need to complete the [API
39 Organization37 Organization
40 Verification](https://help.openai.com/en/articles/10910291-api-organization-verification)38 Verification](https://help.openai.com/en/articles/10910291-api-organization-verification)
41 from your [developer39 from your [developer
42 console](https://platform.openai.com/settings/organization/general) before40 console](https://platform.openai.com/settings/organization/general) before
4341 using GPT Image models, including `gpt-image-2`, `gpt-image-1.5`, using GPT Image models.
44 `gpt-image-1`, and `gpt-image-1-mini`.
45 42
46<div43<div
47 className="not-prose"44 className="not-prose"
48 style={{ float: "right", margin: "10px 0 10px 10px" }}45 style={{ float: "right", margin: "10px 0 10px 10px" }}
49>46>
5047 <img src="https://cdn.openai.com/API/docs/images/mug.png" <img src="https://developers.openai.com/images/image-25-article/mug.png"
51 alt="A beige coffee mug on a wooden table"48 alt="A beige coffee mug on a wooden table"
52 style={{ height: "180px", width: "auto", borderRadius: "8px" }}49 style={{ height: "180px", width: "auto", borderRadius: "8px" }}
53 />50 />
79`;76`;
80 77
81const result = await openai.images.generate({78const result = await openai.images.generate({
8279 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
83 prompt,80 prompt,
84});81});
85 82
100listen to the heartbeat of a baby otter.97listen to the heartbeat of a baby otter.
101"""98"""
102 99
103100result = client.images.generate(model="gpt-image-2", prompt=prompt)result = client.images.generate(model="gpt-image-2.5-sunburst", prompt=prompt)
104 101
105image_base64 = result.data[0].b64_json102image_base64 = result.data[0].b64_json
106image_bytes = base64.b64decode(image_base64)103image_bytes = base64.b64decode(image_base64)
124func main() {121func main() {
125 client := openai.NewClient()122 client := openai.NewClient()
126 result, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{123 result, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{
127124 Model: openai.ImageModel("gpt-image-2"), Model: openai.ImageModel("gpt-image-2.5-sunburst"),
128 Prompt: "A children's book drawing of a veterinarian using a stethoscope to " +125 Prompt: "A children's book drawing of a veterinarian using a stethoscope to " +
129 "listen to the heartbeat of a baby otter.",126 "listen to the heartbeat of a baby otter.",
130 })127 })
155 .images()152 .images()
156 .generate(153 .generate(
157 ImageGenerateParams.builder()154 ImageGenerateParams.builder()
158155 .model("gpt-image-2") .model("gpt-image-2.5-sunburst")
159 .prompt("A watercolor robot reading in a library")156 .prompt("A watercolor robot reading in a library")
160 .build());157 .build());
161 158
168using OpenAI.Images;165using OpenAI.Images;
169 166
170string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;167string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
171168string model = "gpt-image-2";string model = "gpt-image-2.5-sunburst";
172ImageClient client = new(model, key);169ImageClient client = new(model, key);
173 170
174GeneratedImage image = await client.GenerateImageAsync(171GeneratedImage image = await client.GenerateImageAsync(
185 182
186client = OpenAI::Client.new183client = OpenAI::Client.new
187result = client.images.generate(184result = client.images.generate(
188185 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
189 prompt: "A watercolor robot reading in a library"186 prompt: "A watercolor robot reading in a library"
190)187)
191generated_image = result.data&.first or raise "No image returned"188generated_image = result.data&.first or raise "No image returned"
200 -H "Authorization: Bearer $OPENAI_API_KEY" \197 -H "Authorization: Bearer $OPENAI_API_KEY" \
201 -H "Content-type: application/json" \198 -H "Content-type: application/json" \
202 -d '{199 -d '{
203200 "model": "gpt-image-2", "model": "gpt-image-2.5-sunburst",
204 "prompt": "A children'\''s book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter."201 "prompt": "A children'\''s book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter."
205 }' | jq -r '.data[0].b64_json' | base64 --decode > otter.png202 }' | jq -r '.data[0].b64_json' | base64 --decode > otter.png
206```203```
207 204
208```bash205```bash
209openai images generate \206openai images generate \
210207 --model gpt-image-2 \ --model gpt-image-2.5-sunburst \
211 --prompt "A children's book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter." \208 --prompt "A children's book drawing of a veterinarian using a stethoscope to listen to the heartbeat of a baby otter." \
212 --raw-output \209 --raw-output \
213 --transform 'data.0.b64_json' | base64 --decode > otter.png210 --transform 'data.0.b64_json' | base64 --decode > otter.png
230 model: "gpt-6-astra",227 model: "gpt-6-astra",
231 input:228 input:
232 "Generate an image of gray tabby cat hugging an otter with an orange scarf",229 "Generate an image of gray tabby cat hugging an otter with an orange scarf",
233230 tools: [{ type: "image_generation" }], tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
234});231});
235 232
236// Save the image to a file233// Save the image to a file
254response = client.responses.create(251response = client.responses.create(
255 model="gpt-6-astra",252 model="gpt-6-astra",
256 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",253 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
257254 tools=[{"type": "image_generation"}], tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
258)255)
259 256
260# Save the image to a file257# Save the image to a file
289 Input: responses.ResponseNewParamsInputUnion{286 Input: responses.ResponseNewParamsInputUnion{
290 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),287 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
291 },288 },
292289 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
293 })290 })
294 if err != nil {291 if err != nil {
295 panic(err)292 panic(err)
354 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."351 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."
355 )352 )
356);353);
357354options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2"));options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
358 355
359ResponseResult response = await client.CreateResponseAsync(options);356ResponseResult response = await client.CreateResponseAsync(options);
360ImageGenerationCallResponseItem image = response357ImageGenerationCallResponseItem image = response
372response = client.responses.create(369response = client.responses.create(
373 model: "gpt-6-astra",370 model: "gpt-6-astra",
374 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",371 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
375372 tools: [{type: :image_generation}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
376)373)
377 374
378image_call = response.output.find do |item|375image_call = response.output.find do |item|
405 model: "gpt-6-astra",402 model: "gpt-6-astra",
406 input:403 input:
407 "Generate an image of gray tabby cat hugging an otter with an orange scarf",404 "Generate an image of gray tabby cat hugging an otter with an orange scarf",
408405 tools: [{ type: "image_generation", action: "generate" }], tools: [
406 { type: "image_generation", model: "gpt-image-2.5-sunburst", action: "generate" },
407 ],
409});408});
410 409
411// Save the image to a file410// Save the image to a file
429response = client.responses.create(428response = client.responses.create(
430 model="gpt-6-astra",429 model="gpt-6-astra",
431 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",430 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
432431 tools=[{"type": "image_generation", "action": "generate"}], tools=[
432 {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}
433 ],
433)434)
434 435
435# Save the image to a file436# Save the image to a file
464 Input: responses.ResponseNewParamsInputUnion{465 Input: responses.ResponseNewParamsInputUnion{
465 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),466 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
466 },467 },
467468 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Action: "generate"}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst", Action: "generate"}}},
468 })469 })
469 if err != nil {470 if err != nil {
470 panic(err)471 panic(err)
530);531);
531options.Tools.Add(532options.Tools.Add(
532 ResponseTool.CreateImageGenerationTool(533 ResponseTool.CreateImageGenerationTool(
533534 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
534 action: ImageGenerationToolAction.Generate535 action: ImageGenerationToolAction.Generate
535 )536 )
536);537);
551response = client.responses.create(552response = client.responses.create(
552 model: "gpt-6-astra",553 model: "gpt-6-astra",
553 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",554 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
554555 tools: [{type: :image_generation, action: :generate}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst", action: :generate}]
555)556)
556 557
557image_call = response.output.find do |item|558image_call = response.output.find do |item|
584 model: "gpt-6-astra",585 model: "gpt-6-astra",
585 input:586 input:
586 "Generate an image of gray tabby cat hugging an otter with an orange scarf",587 "Generate an image of gray tabby cat hugging an otter with an orange scarf",
587588 tools: [{ type: "image_generation" }], tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
588});589});
589 590
590const imageData = response.output591const imageData = response.output
603 model: "gpt-6-astra",604 model: "gpt-6-astra",
604 previous_response_id: response.id,605 previous_response_id: response.id,
605 input: "Now make it look realistic",606 input: "Now make it look realistic",
606607 tools: [{ type: "image_generation" }], tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
607});608});
608 609
609const imageData_fwup = response_fwup.output610const imageData_fwup = response_fwup.output
629response = client.responses.create(630response = client.responses.create(
630 model="gpt-6-astra",631 model="gpt-6-astra",
631 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",632 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
632633 tools=[{"type": "image_generation"}], tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
633)634)
634 635
635image_data = [636image_data = [
651 model="gpt-6-astra",652 model="gpt-6-astra",
652 previous_response_id=response.id,653 previous_response_id=response.id,
653 input="Now make it look realistic",654 input="Now make it look realistic",
654655 tools=[{"type": "image_generation"}], tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
655)656)
656 657
657image_data_fwup = [658image_data_fwup = [
685 Input: responses.ResponseNewParamsInputUnion{686 Input: responses.ResponseNewParamsInputUnion{
686 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),687 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
687 },688 },
688689 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
689 })690 })
690 if err != nil {691 if err != nil {
691 panic(err)692 panic(err)
698 Input: responses.ResponseNewParamsInputUnion{699 Input: responses.ResponseNewParamsInputUnion{
699 OfString: openai.String("Now make it look realistic"),700 OfString: openai.String("Now make it look realistic"),
700 },701 },
701702 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
702 })703 })
703 if err != nil {704 if err != nil {
704 panic(err)705 panic(err)
789ResponsesClient client = new(key);790ResponsesClient client = new(key);
790 791
791CreateResponseOptions options = new() { Model = "gpt-6-astra" };792CreateResponseOptions options = new() { Model = "gpt-6-astra" };
792793options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2"));options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
793options.InputItems.Add(794options.InputItems.Add(
794 ResponseItem.CreateUserMessageItem(795 ResponseItem.CreateUserMessageItem(
795 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."796 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."
807 Model = "gpt-6-astra",808 Model = "gpt-6-astra",
808 PreviousResponseId = first.Id,809 PreviousResponseId = first.Id,
809};810};
810811followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2"));followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
811followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));812followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));
812 813
813ResponseResult second = await client.CreateResponseAsync(followUp);814ResponseResult second = await client.CreateResponseAsync(followUp);
828first = client.responses.create(829first = client.responses.create(
829 model: "gpt-6-astra",830 model: "gpt-6-astra",
830 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",831 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
831832 tools: [{type: :image_generation}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
832)833)
833 834
834first_image = first.output.find do |item|835first_image = first.output.find do |item|
845 model: "gpt-6-astra",846 model: "gpt-6-astra",
846 input: "Now make it look realistic.",847 input: "Now make it look realistic.",
847 previous_response_id: first.id,848 previous_response_id: first.id,
848849 tools: [{type: :image_generation}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
849)850)
850 851
851follow_up_image = follow_up.output.find do |item|852follow_up_image = follow_up.output.find do |item|
876 model: "gpt-6-astra",877 model: "gpt-6-astra",
877 input:878 input:
878 "Generate an image of gray tabby cat hugging an otter with an orange scarf",879 "Generate an image of gray tabby cat hugging an otter with an orange scarf",
879880 tools: [{ type: "image_generation" }], tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
880});881});
881 882
882const imageGenerationCalls = response.output.filter(883const imageGenerationCalls = response.output.filter(
905 id: imageGenerationCalls[0].id,906 id: imageGenerationCalls[0].id,
906 },907 },
907 ],908 ],
908909 tools: [{ type: "image_generation" }], tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
909});910});
910 911
911const imageData_fwup = response_fwup.output912const imageData_fwup = response_fwup.output
929response = openai.responses.create(930response = openai.responses.create(
930 model="gpt-6-astra",931 model="gpt-6-astra",
931 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",932 input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
932933 tools=[{"type": "image_generation"}], tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
933)934)
934 935
935image_generation_calls = [936image_generation_calls = [
959 "id": image_generation_calls[0].id,960 "id": image_generation_calls[0].id,
960 },961 },
961 ],962 ],
962963 tools=[{"type": "image_generation"}], tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
963)964)
964 965
965image_data_fwup = [966image_data_fwup = [
994 Input: responses.ResponseNewParamsInputUnion{995 Input: responses.ResponseNewParamsInputUnion{
995 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),996 OfString: openai.String("Generate an image of gray tabby cat hugging an otter with an orange scarf"),
996 },997 },
997998 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
998 })999 })
999 if err != nil {1000 if err != nil {
1000 panic(err)1001 panic(err)
1010 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{1011 followUp, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
1011 Model: "gpt-6-astra",1012 Model: "gpt-6-astra",
1012 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},1013 Input: responses.ResponseNewParamsInputUnion{OfInputItemList: input},
10131014 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
1014 })1015 })
1015 if err != nil {1016 if err != nil {
1016 panic(err)1017 panic(err)
1127ResponsesClient client = new(key);1128ResponsesClient client = new(key);
1128 1129
1129CreateResponseOptions options = new() { Model = "gpt-6-astra" };1130CreateResponseOptions options = new() { Model = "gpt-6-astra" };
11301131options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2"));options.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
1131options.InputItems.Add(1132options.InputItems.Add(
1132 ResponseItem.CreateUserMessageItem(1133 ResponseItem.CreateUserMessageItem(
1133 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."1134 "Generate an image of a gray tabby cat hugging an otter with an orange scarf."
1141await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());1142await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());
1142 1143
1143CreateResponseOptions followUp = new() { Model = "gpt-6-astra" };1144CreateResponseOptions followUp = new() { Model = "gpt-6-astra" };
11441145followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2"));followUp.Tools.Add(ResponseTool.CreateImageGenerationTool(model: "gpt-image-2.5-sunburst"));
1145followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));1146followUp.InputItems.Add(ResponseItem.CreateUserMessageItem("Now make it look realistic."));
1146followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));1147followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));
1147 1148
1163first = client.responses.create(1164first = client.responses.create(
1164 model: "gpt-6-astra",1165 model: "gpt-6-astra",
1165 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",1166 input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf.",
11661167 tools: [{type: :image_generation}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
1167)1168)
1168 1169
1169first_image = first.output.find do |item|1170first_image = first.output.find do |item|
1185 },1186 },
1186 {type: :image_generation_call, id: first_image.id}1187 {type: :image_generation_call, id: first_image.id}
1187 ],1188 ],
11881189 tools: [{type: :image_generation}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
1189)1190)
1190 1191
1191follow_up_image = follow_up.output.find do |item|1192follow_up_image = follow_up.output.find do |item|
1219 paddingBottom: "16px",1220 paddingBottom: "16px",
1220 }}1221 }}
1221 >1222 >
12221223 <img src="https://cdn.openai.com/API/docs/images/cat_and_otter.png" <img src="https://developers.openai.com/images/image-25-article/cat_and_otter.png"
1223 alt="A cat and an otter"1224 alt="A cat and an otter"
1224 style={{ width: "200px", borderRadius: "8px" }}1225 style={{ width: "200px", borderRadius: "8px" }}
1225 />1226 />
1230 "Now make it look realistic"1231 "Now make it look realistic"
1231 </td>1232 </td>
1232 <td style={{ textAlign: "right", verticalAlign: "top" }}>1233 <td style={{ textAlign: "right", verticalAlign: "top" }}>
12331234 <img src="https://cdn.openai.com/API/docs/images/cat_and_otter_realistic.png" <img src="https://developers.openai.com/images/image-25-article/cat_and_otter_realistic.png"
1234 alt="A cat and an otter"1235 alt="A cat and an otter"
1235 style={{ width: "200px", borderRadius: "8px" }}1236 style={{ width: "200px", borderRadius: "8px" }}
1236 />1237 />
1271 input:1272 input:
1272 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1273 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
1273 stream: true,1274 stream: true,
12741275 tools: [{ type: "image_generation", partial_images: 2 }], tools: [
1276 { type: "image_generation", model: "gpt-image-2.5-sunburst", partial_images: 2 },
1277 ],
1275});1278});
1276 1279
1277for await (const event of stream) {1280for await (const event of stream) {
1307 model="gpt-6-astra",1310 model="gpt-6-astra",
1308 input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1311 input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
1309 stream=True,1312 stream=True,
13101313 tools=[{"type": "image_generation", "partial_images": 2}], tools=[
1314 {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "partial_images": 2}
1315 ],
1311)1316)
1312 1317
1313for event in stream:1318for event in stream:
1345 Input: responses.ResponseNewParamsInputUnion{1350 Input: responses.ResponseNewParamsInputUnion{
1346 OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),1351 OfString: openai.String("Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape"),
1347 },1352 },
13481353 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{PartialImages: openai.Int(2)}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst", PartialImages: openai.Int(2)}}},
1349 })1354 })
1350 for stream.Next() {1355 for stream.Next() {
1351 event := stream.Current()1356 event := stream.Current()
1433stream = client.responses.stream(1438stream = client.responses.stream(
1434 model: "gpt-6-astra",1439 model: "gpt-6-astra",
1435 input: "Generate an image of a river made of white owl feathers.",1440 input: "Generate an image of a river made of white owl feathers.",
14361441 tools: [{type: :image_generation, partial_images: 2}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst", partial_images: 2}]
1437)1442)
1438 1443
1439stream.each do |event|1444stream.each do |event|
1474 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape";1479 "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape";
1475const stream = await openai.images.generate({1480const stream = await openai.images.generate({
1476 prompt: prompt,1481 prompt: prompt,
14771482 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
1478 stream: true,1483 stream: true,
1479 partial_images: 2,1484 partial_images: 2,
1480});1485});
1497 1502
1498stream = client.images.generate(1503stream = client.images.generate(
1499 prompt="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1504 prompt="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
15001505 model="gpt-image-2", model="gpt-image-2.5-sunburst",
1501 stream=True,1506 stream=True,
1502 partial_images=2,1507 partial_images=2,
1503)1508)
1526func main() {1531func main() {
1527 client := openai.NewClient()1532 client := openai.NewClient()
1528 stream := client.Images.GenerateStreaming(context.Background(), openai.ImageGenerateParams{1533 stream := client.Images.GenerateStreaming(context.Background(), openai.ImageGenerateParams{
15291534 Model: openai.ImageModel("gpt-image-2"), Model: openai.ImageModel("gpt-image-2.5-sunburst"),
1530 Prompt: "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",1535 Prompt: "Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
1531 PartialImages: openai.Int(2),1536 PartialImages: openai.Int(2),
1532 })1537 })
1560 1565
1561client = OpenAI::Client.new1566client = OpenAI::Client.new
1562stream = client.images.generate_stream_raw(1567stream = client.images.generate_stream_raw(
15631568 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
1564 prompt: "A river made of white owl feathers in a winter landscape",1569 prompt: "A river made of white owl feathers in a winter landscape",
1565 partial_images: 21570 partial_images: 2
1566)1571)
1581 1586
1582 1587
1583| Partial 1 | Partial 2 | Final image |1588| Partial 1 | Partial 2 | Final image |
15841589| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- || ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
15851590| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming1.png" alt="1st partial" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming2.png" alt="2nd partial" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/imgen1p5-streaming3.png" alt="3rd partial" /> || <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/river-partial-0.png" alt="1st partial" /> | <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/river-partial-1.png" alt="2nd partial" /> | <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/river-final.png" alt="Final image" /> |
1586 1591
1587 1592
1588 1593
1842 ],1847 ],
1843 },1848 },
1844 ],1849 ],
18451850 tools: [{ type: "image_generation" }], tools: [{ type: "image_generation", model: "gpt-image-2.5-sunburst" }],
1846});1851});
1847 1852
1848const imageData = response.output1853const imageData = response.output
1910 ],1915 ],
1911 }1916 }
1912 ],1917 ],
19131918 tools=[{"type": "image_generation"}], tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
1914)1919)
1915 1920
1916image_generation_calls = [1921image_generation_calls = [
1958 responses.EasyInputMessageRoleUser,1963 responses.EasyInputMessageRoleUser,
1959 ),1964 ),
1960 }},1965 }},
19611966 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{}}}, Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{Model: "gpt-image-2.5-sunburst"}}},
1962 })1967 })
1963 if err != nil {1968 if err != nil {
1964 panic(err)1969 panic(err)
2120 end2125 end
2121 ]2126 ]
2122 }],2127 }],
21232128 tools: [{type: :image_generation}] tools: [{type: :image_generation, model: "gpt-image-2.5-sunburst"}]
2124)2129)
2125 2130
2126image_call = response.output.find do |item|2131image_call = response.output.find do |item|
2172);2177);
2173 2178
2174const response = await client.images.edit({2179const response = await client.images.edit({
21752180 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
2176 image: images,2181 image: images,
2177 prompt,2182 prompt,
2178});2183});
2196"""2201"""
2197 2202
2198result = client.images.edit(2203result = client.images.edit(
21992204 model="gpt-image-2", model="gpt-image-2.5-sunburst",
2200 image=[2205 image=[
2201 open("body-lotion.png", "rb"),2206 open("body-lotion.png", "rb"),
2202 open("bath-bomb.png", "rb"),2207 open("bath-bomb.png", "rb"),
2237 defer closeFiles()2242 defer closeFiles()
2238 2243
2239 response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{2244 response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{
22402245 Model: openai.ImageModel("gpt-image-2"), Model: openai.ImageModel("gpt-image-2.5-sunburst"),
2241 Image: openai.ImageEditParamsImageUnion{OfFileArray: files},2246 Image: openai.ImageEditParamsImageUnion{OfFileArray: files},
2242 Prompt: "Generate a photorealistic image of a gift basket on a white background " +2247 Prompt: "Generate a photorealistic image of a gift basket on a white background " +
2243 "labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures.",2248 "labeled 'Relax & Unwind' with a ribbon and handwriting-like font, containing all the items in the reference pictures.",
2307 .images()2312 .images()
2308 .edit(2313 .edit(
2309 ImageEditParams.builder()2314 ImageEditParams.builder()
23102315 .model("gpt-image-2") .model("gpt-image-2.5-sunburst")
2311 .image(2316 .image(
2312 MultipartField.<ImageEditParams.Image>builder()2317 MultipartField.<ImageEditParams.Image>builder()
2313 .value(2318 .value(
2341end2346end
2342result = client.images.edit(2347result = client.images.edit(
2343 image: images,2348 image: images,
23442349 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
2345 prompt: <<~PROMPT2350 prompt: <<~PROMPT
2346 Generate a photorealistic image of a gift basket on a white background2351 Generate a photorealistic image of a gift basket on a white background
2347 labeled 'Relax & Unwind' with a ribbon and handwriting-like font,2352 labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
2357 -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \2362 -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \
2358 -X POST "https://api.openai.com/v1/images/edits" \2363 -X POST "https://api.openai.com/v1/images/edits" \
2359 -H "Authorization: Bearer $OPENAI_API_KEY" \2364 -H "Authorization: Bearer $OPENAI_API_KEY" \
23602365 -F "model=gpt-image-2" \ -F "model=gpt-image-2.5-sunburst" \
2361 -F "image[]=@body-lotion.png" \2366 -F "image[]=@body-lotion.png" \
2362 -F "image[]=@bath-bomb.png" \2367 -F "image[]=@bath-bomb.png" \
2363 -F "image[]=@incense-kit.png" \2368 -F "image[]=@incense-kit.png" \
2367 2372
2368```bash2373```bash
2369openai images edit \2374openai images edit \
23702375 --model gpt-image-2 \ --model gpt-image-2.5-sunburst \
2371 --image body-lotion.png \2376 --image body-lotion.png \
2372 --image bath-bomb.png \2377 --image bath-bomb.png \
2373 --image incense-kit.png \2378 --image incense-kit.png \
2434 tools: [2439 tools: [
2435 {2440 {
2436 type: "image_generation",2441 type: "image_generation",
2442 model: "gpt-image-2.5-sunburst",
2437 quality: "high",2443 quality: "high",
2438 input_image_mask: {2444 input_image_mask: {
2439 file_id: maskId,2445 file_id: maskId,
2488 tools=[2494 tools=[
2489 {2495 {
2490 "type": "image_generation",2496 "type": "image_generation",
2497 "model": "gpt-image-2.5-sunburst",
2491 "quality": "high",2498 "quality": "high",
2492 "input_image_mask": {2499 "input_image_mask": {
2493 "file_id": maskId,2500 "file_id": maskId,
2536 ),2543 ),
2537 }},2544 }},
2538 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{2545 Tools: []responses.ToolUnionParam{{OfImageGeneration: &responses.ToolImageGenerationParam{
2546 Model: "gpt-image-2.5-sunburst",
2539 Quality: "high",2547 Quality: "high",
2540 InputImageMask: responses.ToolImageGenerationInputImageMaskParam{FileID: openai.String(maskID)},2548 InputImageMask: responses.ToolImageGenerationInputImageMaskParam{FileID: openai.String(maskID)},
2541 }}},2549 }}},
2664 ]2672 ]
2665 }],2673 }],
2666 tools: [{2674 tools: [{
26672675 type: :image_generation, type: :image_generation, model: "gpt-image-2.5-sunburst",
2668 input_image_mask: {file_id: mask.id}2676 input_image_mask: {file_id: mask.id}
2669 }]2677 }]
2670)2678)
2695const client = new OpenAI();2703const client = new OpenAI();
2696 2704
2697const rsp = await client.images.edit({2705const rsp = await client.images.edit({
26982706 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
2699 image: await toFile(fs.createReadStream("fixtures/sunlit_lounge.png"), null, {2707 image: await toFile(fs.createReadStream("fixtures/sunlit_lounge.png"), null, {
2700 type: "image/png",2708 type: "image/png",
2701 }),2709 }),
2718client = OpenAI()2726client = OpenAI()
2719 2727
2720result = client.images.edit(2728result = client.images.edit(
27212729 model="gpt-image-2", model="gpt-image-2.5-sunburst",
2722 image=open("sunlit_lounge.png", "rb"),2730 image=open("sunlit_lounge.png", "rb"),
2723 mask=open("mask.png", "rb"),2731 mask=open("mask.png", "rb"),
2724 prompt="A sunlit indoor lounge area with a pool containing a flamingo",2732 prompt="A sunlit indoor lounge area with a pool containing a flamingo",
2757 defer mask.Close()2765 defer mask.Close()
2758 2766
2759 response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{2767 response, err := client.Images.Edit(context.Background(), openai.ImageEditParams{
27602768 Model: openai.ImageModel("gpt-image-2"), Model: openai.ImageModel("gpt-image-2.5-sunburst"),
2761 Image: openai.ImageEditParamsImageUnion{OfFile: openai.File(image, "sunlit_lounge.png", "image/png")},2769 Image: openai.ImageEditParamsImageUnion{OfFile: openai.File(image, "sunlit_lounge.png", "image/png")},
2762 Mask: openai.File(mask, "mask.png", "image/png"),2770 Mask: openai.File(mask, "mask.png", "image/png"),
2763 Prompt: "A sunlit indoor lounge area with a pool containing a flamingo",2771 Prompt: "A sunlit indoor lounge area with a pool containing a flamingo",
2795 .images()2803 .images()
2796 .edit(2804 .edit(
2797 ImageEditParams.builder()2805 ImageEditParams.builder()
27982806 .model("gpt-image-2") .model("gpt-image-2.5-sunburst")
2799 .image(2807 .image(
2800 MultipartField.<ImageEditParams.Image>builder()2808 MultipartField.<ImageEditParams.Image>builder()
2801 .value(ImageEditParams.Image.ofInputStream(image))2809 .value(ImageEditParams.Image.ofInputStream(image))
2828result = client.images.edit(2836result = client.images.edit(
2829 image: image,2837 image: image,
2830 mask: mask,2838 mask: mask,
28312839 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
2832 prompt: "A sunlit indoor lounge area with a pool containing a flamingo"2840 prompt: "A sunlit indoor lounge area with a pool containing a flamingo"
2833)2841)
2834generated_image = result.data&.first or raise "No image returned"2842generated_image = result.data&.first or raise "No image returned"
2840 -o >(jq -r '.data[0].b64_json' | base64 --decode > lounge.png) \2848 -o >(jq -r '.data[0].b64_json' | base64 --decode > lounge.png) \
2841 -X POST "https://api.openai.com/v1/images/edits" \2849 -X POST "https://api.openai.com/v1/images/edits" \
2842 -H "Authorization: Bearer $OPENAI_API_KEY" \2850 -H "Authorization: Bearer $OPENAI_API_KEY" \
28432851 -F "model=gpt-image-2" \ -F "model=gpt-image-2.5-sunburst" \
2844 -F "mask=@mask.png" \2852 -F "mask=@mask.png" \
2845 -F "image[]=@sunlit_lounge.png" \2853 -F "image[]=@sunlit_lounge.png" \
2846 -F 'prompt=A sunlit indoor lounge area with a pool containing a flamingo'2854 -F 'prompt=A sunlit indoor lounge area with a pool containing a flamingo'
2848 2856
2849```bash2857```bash
2850openai images edit \2858openai images edit \
28512859 --model gpt-image-2 \ --model gpt-image-2.5-sunburst \
2852 --image sunlit_lounge.png \2860 --image sunlit_lounge.png \
2853 --mask mask.png \2861 --mask mask.png \
2854 --prompt "A sunlit indoor lounge area with a pool containing a flamingo" \2862 --prompt "A sunlit indoor lounge area with a pool containing a flamingo" \
2862 2870
2863 2871
2864| Image | Mask | Output |2872| Image | Mask | Output |
28652873| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
28662874| <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge.png" alt="A pink room with a pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/mask.png" alt="A mask in part of the pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge_result.png" alt="The original pool with an inflatable flamingo replacing the mask" /> || <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/sunlit_lounge.png" alt="A pink room with a pool" /> | <img className="images-example-image" src="https://cdn.openai.com/API/docs/images/mask.png" alt="A mask in part of the pool" /> | <img className="images-example-image" src="https://developers.openai.com/images/image-25-article/sunlit_lounge_result.png" alt="The original pool with an inflatable flamingo replacing the mask" /> |
2867 2875
2868 2876
2869 2877
2952```2960```
2953 2961
2954 2962
2955### Image input fidelity
2956
2957The `input_fidelity` parameter controls how strongly a model preserves details from input images during edits and reference-image workflows. For `gpt-image-2`, omit this parameter; the API doesn't allow changing it because the model processes every image input at high fidelity automatically.
2958
2959Because `gpt-image-2` always processes image inputs at high fidelity, image
2960 input tokens can be higher for edit requests that include reference images. To
2961 understand the cost implications, refer to the [vision
2962 costs](https://developers.openai.com/api/docs/guides/images-vision?api-mode=responses#calculating-costs)
2963 section.
2964
2965## Customize Image Output2963## Customize Image Output
2966 2964
2967You can configure the following output options:2965You can configure the following output options:
2974 2972
2975`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.2973`size`, `quality`, and `background` support the `auto` option, where the model will automatically select the best option based on the prompt.
2976 2974
2977Transparent backgrounds are available in preview for `gpt-image-2`. Set
2978 `background: "transparent"` to request one. Use `png` (the default) or `webp`;
2979 `jpeg` isn't supported with transparent backgrounds.
2980
2981### Size and quality options2975### Size and quality options
2982 2976
29832977`gpt-image-2` accepts any resolution in the `size` parameter when it satisfies the constraints below. Square images are typically fastest to generate.`gpt-image-2.5-sunburst` and `gpt-image-2.5-flare` add `xhigh` and `max` quality settings. Both default to `auto`. Earlier GPT Image models support quality settings up to `high`.
2984 2978
29852979<table>| Setting | Options |
29862980 <tbody>| ----------------- | --------------------------------------------------------------------- |
29872981 <tr>| Recommended sizes | `1024x1024` (square), `1536x1024` (landscape), `1024x1536` (portrait) |
29882982 <td>Popular sizes</td>| Quality | `low`, `medium`, `high`, `xhigh`, `max`, `auto` |
29892983 <td>
29902984 <ul>Both models also support custom dimensions as `WIDTHxHEIGHT` strings, such as `1536x864`. Width and height must be multiples of 16, the aspect ratio must be between 1:3 and 3:1, and neither edge may exceed 3840 pixels. The total pixel count must be between 655,360 and 8,294,400 (4K). Resolutions above `2560x1440` are experimental.
2991 <li>
2992 `1024x1024` (square)
2993 </li>
2994 <li>
2995 `1536x1024` (landscape)
2996 </li>
2997 <li>
2998 `1024x1536` (portrait)
2999 </li>
3000 <li>
3001 `2048x2048` (2K square)
3002 </li>
3003 <li>
3004 `2048x1152` (2K landscape)
3005 </li>
3006 <li>
3007 `3840x2160` (4K landscape)
3008 </li>
3009 <li>
3010 `2160x3840` (4K portrait)
3011 </li>
3012 <li>
3013 `auto` (default)
3014 </li>
3015 </ul>
3016 </td>
3017 </tr>
3018 <tr>
3019 <td>Size constraints</td>
3020 <td>
3021 <ul>
3022 <li>
3023 Maximum edge length must be less than or equal to
3024 `3840px`
3025 </li>
3026 <li>
3027 Both edges must be multiples of `16px`
3028 </li>
3029 <li>
3030 Long edge to short edge ratio must not exceed `3:1`
3031 </li>
3032 <li>
3033 Total pixels must be at least `655,360` and no more than
3034 `8,294,400`
3035 </li>
3036 </ul>
3037 </td>
3038 </tr>
3039 <tr>
3040 <td>Quality options</td>
3041 <td>
3042 <ul>
3043 <li>
3044 `low`
3045 </li>
3046 <li>
3047 `medium`
3048 </li>
3049 <li>
3050 `high`
3051 </li>
3052 <li>
3053 `auto` (default)
3054 </li>
3055 </ul>
3056 </td>
3057 </tr>
3058 </tbody>
3059</table>
3060 2985
30612986Use `quality: "low"` for fast drafts, thumbnails, and quick iterations. It isFor transparent backgrounds with either model, set `background: "transparent"` and use `output_format: "png"` or `"webp"`.
3062 the fastest option and works well for many common use cases before you move to
3063 `medium` or `high` for final assets.
3064 2987
30652988Outputs that contain more than `2560x1440` (`3,686,400`) total pixels,Use `quality: "low"` for quick drafts. For final assets, compare higher quality settings to find the right balance of detail, latency, and cost.
3066 typically referred to as 2K, are considered experimental.
3067 2989
3068### Output format2990### Output format
3069 2991
3077 2999
3078## Limitations3000## Limitations
3079 3001
30803002GPT Image models (`gpt-image-2`, `gpt-image-1.5`, `gpt-image-1`, and `gpt-image-1-mini`) are powerful and versatile image generation models, but they still have some limitations to be aware of:GPT Image models are powerful and versatile image generation models, but they still have some limitations to be aware of:
3081 3003
3082- **Latency:** Complex prompts may take up to 2 minutes to process.3004- **Latency:** Complex prompts may take up to 2 minutes to process.
3083- **Text Rendering:** Although significantly improved, the model can still struggle with precise text placement and clarity.3005- **Text Rendering:** Although significantly improved, the model can still struggle with precise text placement and clarity.
3088 3010
3089All prompts and generated images are filtered in accordance with our [content policy](https://openai.com/policies/usage-policies/).3011All prompts and generated images are filtered in accordance with our [content policy](https://openai.com/policies/usage-policies/).
3090 3012
30913013For image generation using GPT Image models (`gpt-image-2`, `gpt-image-1.5`, `gpt-image-1`, and `gpt-image-1-mini`), you can control moderation strictness with the `moderation` parameter. This parameter supports two values:For image generation using GPT Image models, you can control moderation strictness with the `moderation` parameter. This parameter supports two values:
3092 3014
3093- `auto` (default): Standard filtering that seeks to limit creating certain categories of potentially age-inappropriate content.3015- `auto` (default): Standard filtering that seeks to limit creating certain categories of potentially age-inappropriate content.
3094- `low`: Less restrictive filtering.3016- `low`: Less restrictive filtering.
3095 3017
3096### Handling blocked requests and other errors3018### Handling blocked requests and other errors
3097 3019
30983020Handle image generation failures the same way you handle other API errors: check the HTTP status or SDK exception type, log the request ID, and refer to the [error codes guide](https://developers.openai.com/api/docs/guides/error-codes) for authentication, quota, rate-limit, and server failures. Retries are appropriate for transient failures like `429` and `5xx`, but not for image generation user errors that require changing the request.Handle image generation failures the same way you handle other API errors: check the HTTP status or SDK exception type, log the request ID, and refer to the [error codes guide](https://developers.openai.com/api/docs/guides/error-codes) for authentication, quota, rate-limit, and server failures. Retry transient rate-limit and server failures with backoff. Don't automatically retry quota errors or image generation user errors that require changing the request.
3099 3021
3100Some image generation failures are user-correctable and may return `error.type = "image_generation_user_error"`. Don't automatically retry these errors without modifying the prompt or input images. For programmatic handling, use `error.code` as the stable discriminator.3022Some image generation failures are user-correctable and may return `error.type = "image_generation_user_error"`. Don't automatically retry these errors without modifying the prompt or input images. For programmatic handling, use `error.code` as the stable discriminator.
3101 3023
3126 3048
3127For most apps, keep the primary end-user message generic. Use `moderation_details` for developer logs, support workflows, analytics, and light remediation hints.3049For most apps, keep the primary end-user message generic. Use `moderation_details` for developer logs, support workflows, analytics, and light remediation hints.
3128 3050
3129For example, if `harassment` appears, suggest removing abusive or targeting language. If the block happened at the `input` stage, guide the user to revise the prompt. If it happened at the `output` stage, treat it as a generated result safety block and distinguish it in your logs. Always branch on `error.code = "moderation_blocked"` first, and treat `moderation_details` as optional extra context.
3130
3131Handle moderation-blocked image generation errors3051Handle moderation-blocked image generation errors
3132 3052
3133```javascript3053```javascript
3139 // The same error handling pattern applies to image generation requests,3059 // The same error handling pattern applies to image generation requests,
3140 // image edits, and Responses API tool calls that generate images.3060 // image edits, and Responses API tool calls that generate images.
3141 await openai.images.generate({3061 await openai.images.generate({
31423062 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
3143 prompt: "Create a poster humiliating my coworker with insulting captions",3063 prompt: "Create a poster humiliating my coworker with insulting captions",
3144 });3064 });
3145} catch (error) {3065} catch (error) {
3185 # The same error handling pattern applies to image generation requests,3105 # The same error handling pattern applies to image generation requests,
3186 # image edits, and Responses API tool calls that generate images.3106 # image edits, and Responses API tool calls that generate images.
3187 client.images.generate(3107 client.images.generate(
31883108 model="gpt-image-2", model="gpt-image-2.5-sunburst",
3189 prompt="Create a poster humiliating my coworker with insulting captions",3109 prompt="Create a poster humiliating my coworker with insulting captions",
3190 )3110 )
3191except openai.BadRequestError as error:3111except openai.BadRequestError as error:
3234func main() {3154func main() {
3235 client := openai.NewClient()3155 client := openai.NewClient()
3236 _, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{3156 _, err := client.Images.Generate(context.Background(), openai.ImageGenerateParams{
32373157 Model: openai.ImageModel("gpt-image-2"), Model: openai.ImageModel("gpt-image-2.5-sunburst"),
3238 Prompt: "Create a poster humiliating my coworker with insulting captions",3158 Prompt: "Create a poster humiliating my coworker with insulting captions",
3239 })3159 })
3240 if err == nil {3160 if err == nil {
3283 .images()3203 .images()
3284 .generate(3204 .generate(
3285 ImageGenerateParams.builder()3205 ImageGenerateParams.builder()
32863206 .model("gpt-image-2") .model("gpt-image-2.5-sunburst")
3287 .prompt("Create a poster humiliating my coworker with insulting captions")3207 .prompt("Create a poster humiliating my coworker with insulting captions")
3288 .build());3208 .build());
3289 3209
3316client = OpenAI::Client.new3236client = OpenAI::Client.new
3317begin3237begin
3318 client.images.generate(3238 client.images.generate(
33193239 model: "gpt-image-2", model: "gpt-image-2.5-sunburst",
3320 prompt: "Create a poster humiliating my coworker with insulting captions"3240 prompt: "Create a poster humiliating my coworker with insulting captions"
3321 )3241 )
3322rescue OpenAI::Errors::BadRequestError => error3242rescue OpenAI::Errors::BadRequestError => error
3347 3267
3348## Cost and latency3268## Cost and latency
3349 3269
33503270### `gpt-image-2` output tokens### GPT Image 2.5 costs
3271
3272Responses API requests include the mainline model's token usage in addition to image generation costs.
3273
3274Both GPT Image 2.5 models use the same token rates: $8 per million image input tokens, $2 per million cached image input tokens, $30 per million image output tokens, $5 per million text input tokens, and $1.25 per million cached text input tokens. See [pricing](https://developers.openai.com/api/docs/pricing#image-generation).
3275
3276Use the response's `usage` to measure token consumption for your prompts, sizes, and quality settings. Equal token rates don't mean equal cost per image: token consumption can differ by model and quality setting. For older-model pricing examples, see [Earlier GPT Image models](#earlier-gpt-image-models).
3277
3278
3351 3279
33523280For `gpt-image-2`, use the calculator to estimate output tokens from the requested `quality` and `size`:
3281### GPT Image 2.5 and GPT Image 2 output tokens
3282
3283Select a model, quality, and size to estimate output tokens and image output cost.
3284For `gpt-image-2.5-sunburst` and `gpt-image-2.5-flare`, the quality options are `low`, `medium`, `high`, `xhigh`, and `max`.
3285For `gpt-image-2`, the options are `low`, `medium`, and `high`.
3286The models can use different token counts for the same quality setting and share the same price per image output token.
3287Use explicit quality and size values for this estimate; `auto` depends on the generated image.
3288
3289<GptImageTokenCalculator
3290 client:load
3291 outputPricePerMillion={Number(
3292 pricing.latest.subsections
3293 .find((section) => section.price_type === "Image tokens")
3294 ?.items.find((item) => item.name === "gpt-image-2")?.values.main.output
3295 )}
3296/>
3297
3298### Partial images cost
3299
3300If you want to [stream image generation](#streaming) using the `partial_images` parameter, each partial image will incur an additional 100 image output tokens.
3301
3302## Earlier GPT Image models
3303
3304The details below apply to earlier models, not Sunburst or Flare. For new integrations, use one of the GPT Image 2.5 models described above.
3305
3306<details>
3307<summary>GPT Image 2 settings and input fidelity</summary>
3308
3309`gpt-image-2` accepts any resolution in the `size` parameter when it satisfies the constraints below. Square images are typically fastest to generate.
3310
3311<table>
3312 <tbody>
3313 <tr>
3314 <td>Popular sizes</td>
3315 <td>
3316 <ul>
3317 <li>
3318 `1024x1024` (square)
3319 </li>
3320 <li>
3321 `1536x1024` (landscape)
3322 </li>
3323 <li>
3324 `1024x1536` (portrait)
3325 </li>
3326 <li>
3327 `2048x2048` (2K square)
3328 </li>
3329 <li>
3330 `2048x1152` (2K landscape)
3331 </li>
3332 <li>
3333 `3840x2160` (4K landscape)
3334 </li>
3335 <li>
3336 `2160x3840` (4K portrait)
3337 </li>
3338 <li>
3339 `auto` (default)
3340 </li>
3341 </ul>
3342 </td>
3343 </tr>
3344 <tr>
3345 <td>Size constraints</td>
3346 <td>
3347 <ul>
3348 <li>
3349 Maximum edge length must be less than or equal to
3350 `3840px`
3351 </li>
3352 <li>
3353 Both edges must be multiples of `16px`
3354 </li>
3355 <li>
3356 Long edge to short edge ratio must not exceed `3:1`
3357 </li>
3358 <li>
3359 Total pixels must be at least `655,360` and no more than
3360 `8,294,400`
3361 </li>
3362 </ul>
3363 </td>
3364 </tr>
3365 <tr>
3366 <td>Quality options</td>
3367 <td>
3368 <ul>
3369 <li>
3370 `low`
3371 </li>
3372 <li>
3373 `medium`
3374 </li>
3375 <li>
3376 `high`
3377 </li>
3378 <li>
3379 `auto` (default)
3380 </li>
3381 </ul>
3382 </td>
3383 </tr>
3384 </tbody>
3385</table>
3386
3387### Image input fidelity
3388
3389The `input_fidelity` parameter controls how strongly a model preserves details from input images during edits and reference-image workflows. For `gpt-image-2`, omit this parameter; the API doesn't allow changing it because the model processes every image input at high fidelity automatically.
3390
3391Because `gpt-image-2` always processes image inputs at high fidelity, image
3392 input tokens can be higher for edit requests that include reference images. To
3393 understand the cost implications, refer to the [vision
3394 costs](https://developers.openai.com/api/docs/guides/images-vision?api-mode=responses#calculating-costs)
3395 section.
3396
3397</details>
3398
3399<details>
3400<summary>Older-model pricing examples</summary>
3353 3401
3354### Models prior to `gpt-image-2`3402### Models prior to `gpt-image-2`
3355 3403
3499 </tbody>3547 </tbody>
3500</table>3548</table>
3501 3549
35023550### Partial images cost</details>
3503
3504If you want to [stream image generation](#streaming) using the `partial_images` parameter, each partial image will incur an additional 100 image output tokens.





