Permite que los modelos generen o editen imágenes.
La herramienta de generación de imágenes te permite generar imágenes a partir de un prompt de texto y, si lo deseas, de imágenes de entrada. Utiliza modelos GPT Image, entre ellos gpt-image-2.5-sunburst, gpt-image-2.5-flare, gpt-image-2, gpt-image-1.5 y gpt-image-1-mini, y optimiza automáticamente el texto de entrada para mejorar el rendimiento.
En la herramienta image_generation, configura model con el valor gpt-image-2.5-sunburst para editar con precisión o gpt-image-2.5-flare para generar imágenes de alta calidad rápidamente. Usa un modelo principal compatible en el campo model de nivel superior de la API Responses.
gpt-image-1 dejó de estar disponible el 23 de octubre de 2026. Consulta el aviso de retirada para conocer los detalles de la migración.
Cuando incluyes la herramienta image_generation en tu solicitud, el modelo puede decidir cuándo y cómo generar imágenes durante la conversación a partir de tu prompt y de las imágenes de entrada que proporciones.
El resultado de la llamada image_generation_call incluirá una imagen codificada en base64.
Si tu aplicación atiende a usuarios finales individuales, incluye un safety_identifier estable que proteja la privacidad en cada solicitud de nivel superior a la API Responses, también cuando solicites ediciones posteriores. Este parámetro pertenece a la solicitud. La herramienta image_generation no lo admite como opción. Consulta la sección sobre identificadores de seguridad para imágenes para saber cómo usarlos en ambas API de imágenes.
Generar una imagen
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import 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 fileconst 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"));}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22from openai import OpenAIimport base64client = 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 fileimage_data = [ output.resultfor output in response.outputif output.type =="image_generation_call"]if image_data: image_base64 = image_data[0]withopen("otter.png", "wb") as f: f.write(base64.b64decode(image_base64))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42package mainimport ( "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")}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20using OpenAI.Responses;#pragma warning disable OPENAI001string 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());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24require "base64"require "openai"client = OpenAI::Client.newresponse = 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)endunless image_call.is_a?(OpenAI::Models::Responses::ResponseOutputItem::ImageGenerationCall) raise "No image generation call returned"endencoded_image = image_call.result or raise "No image returned"File.binwrite("otter.png", Base64.strict_decode64(encoded_image))
Tamaño: dimensiones de la imagen, por ejemplo, 1024 × 1024 o 1024 × 1536
Calidad: calidad de renderizado, por ejemplo, baja, media o alta
Formato: formato del archivo de salida
Compresión: nivel de compresión (del 0 al 100 %) para los formatos JPEG y WebP
Fondo: transparente, opaco o automático
Acción: permite elegir entre generar una imagen, editarla o dejar que el modelo decida automáticamente
size, quality y background admiten el valor auto, que permite al modelo seleccionar automáticamente la mejor opción según el prompt.
Con gpt-image-2.5-sunburst y gpt-image-2.5-flare, el parámetro quality también acepta xhigh y max. Los modelos GPT Image anteriores no admiten estos valores. El valor predeterminado de calidad sigue siendo auto.
gpt-image-2 admite distintos valores de size que cumplan sus restricciones de resolución. Los fondos transparentes están disponibles en versión preliminar. Para solicitar uno, configura background: "transparent". Usa png (el formato predeterminado) o webp. El formato jpeg no admite fondos transparentes.
Cuando usas la herramienta de generación de imágenes de la API Responses, los modelos GPT Image compatibles pueden elegir entre generar una imagen nueva y editar una que ya esté en la conversación. El parámetro opcional action controla este comportamiento. Deja action en auto para que el modelo elija si genera o edita la imagen, o selecciona generate o edit para forzar la acción correspondiente. Si omites el parámetro, el valor predeterminado es auto.
Prompt revisado
Cuando usas la herramienta de generación de imágenes, el modelo principal, por ejemplo, gpt-5.5, reformula automáticamente tu prompt para mejorar el rendimiento.
Puedes consultar el prompt revisado en el campo revised_prompt de la llamada de generación de imágenes:
1234567{ "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": "..."}
Consejos para redactar prompts
La generación de imágenes funciona mejor cuando usas términos como draw o edit en tu prompt.
Por ejemplo, si quieres combinar imágenes, en lugar de usar combine o merge, puedes escribir algo como “Edita la primera imagen y agrégale este elemento de la segunda”.
Edición en varios turnos
Puedes editar imágenes de forma iterativa usando el ID de una respuesta anterior o el de una imagen. Así puedes refinar las imágenes a lo largo de varios turnos de la conversación.
La herramienta de generación de imágenes puede transmitir imágenes parciales mientras genera el resultado final. Así, los usuarios ven los primeros resultados antes y perciben una menor latencia.
Puedes definir la cantidad de imágenes parciales (de 1 a 3) con el parámetro partial_images.
Transmitir una imagen de forma progresiva
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33import 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]); } }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34from openai import OpenAIimport base64client = OpenAI()defsave_base64_image(filename, image_base64): image_bytes = base64.b64decode(image_base64)withopen(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.resultfor output in event.response.outputif output.type =="image_generation_call" ]if image_data: save_base64_image("river-final.png", image_data[0])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49package mainimport ( "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) }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33require "base64"require "openai"client = OpenAI::Client.newstream = 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) ) endend
Modelos compatibles
Los siguientes modelos siguen vigentes y cuentan con compatibilidad documentada con la herramienta de generación de imágenes de la API Responses. Usa sus ID en el campo model de nivel superior. Consulta la página de cada modelo para conocer su disponibilidad y los requisitos de acceso.