OpenAI 图像生成工具

2026-11-06 11:49 更新

图像生成工具可以根据文本提示和可选的图像输入生成图像。它使用GPT Image模型,包括gpt-image-2.5-sunburst、gpt-image-2.5-flare、gpt-image-2、gpt-image-1.5及gpt-image-1-mini,并自动优化文本输入以改善效果。这里保留官方工具页的模型列表;其中较早模型的生命周期应同时核对弃用公告。

需要精确编辑时,将image_generation工具的model设为gpt-image-2.5-sunburst;需要快速、高质量图像生成时,可使用gpt-image-2.5-flare。Responses顶层的model则应选择支持该工具的主模型,不能将两层模型字段混淆。

gpt-image-1已于2026年10月23日关闭,迁移详情见弃用公告。

完整生成流程见图像生成指南。

用法

请求中加入image_generation工具后,模型会根据提示和图像输入,决定何时及如何在对话中生成图像。image_generation_call工具结果包含Base64编码的图像。

如果应用服务于不同终端用户,应在每次顶层Responses请求中传入稳定、保护隐私的safety_identifier,后续编辑也应携带。它属于请求参数,不是image_generation工具选项。两种图像API的说明见图像安全标识符。

来源示例1(javascript)

程序中的自然语言译释3:

生成灰色虎斑猫抱着戴橙色围巾水獭的图像。

// [中文] 本例在Responses中调用图像生成工具;顶层model选择主模型,工具负责生成图像。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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"));
}

来源示例2(python)

本段复用的中文释义:译释3。

## [中文] 本例在Responses中调用图像生成工具;顶层model选择主模型,工具负责生成图像。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得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:
        # [中文] 把Base64解码后的字节保存为图像文件。
        f.write(base64.b64decode(image_base64))

来源示例3(go)

程序中的自然语言译释30:

响应未包含图像生成调用。

本段复用的中文释义:译释3。

// [中文] 本例在Responses中调用图像生成工具;顶层model选择主模型,工具负责生成图像。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得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
        }
        // [中文] 将工具结果中的Base64解码为图像字节。
        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")
}

来源示例4(java)

程序中的自然语言译释4:

生成一张灰色虎斑猫抱着戴橙色围巾水獭的图像。

程序中的自然语言译释23:

没有返回图像。

程序中的自然语言译释24:

没有返回图像生成调用。

// [中文] 本例在Responses中调用图像生成工具;顶层model选择主模型,工具负责生成图像。
// [中文] 本Java片段只设置顶层主模型,未显式指定图像工具的model;不要把主模型ID当作工具模型ID。
// [中文] 原例是API片段,使用前需已有client以及适当外层程序;未独立编译或执行请求。
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"));
// [中文] 把Base64解码所得图像字节写入文件。
Files.write(Path.of("otter.png"), Base64.getDecoder().decode(encoded));

来源示例5(csharp)

程序中的自然语言译释25:

没有返回生成的图像。

本段复用的中文释义:译释4。

// [中文] 本例在Responses中调用图像生成工具;顶层model选择主模型,工具负责生成图像。
// [中文] 本C#例显式指定图像工具模型;SDK提供ImageResultBytes,可直接保存字节,不手动解码Base64。
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.");
// [中文] SDK已提供图像字节,直接写入文件。
await File.WriteAllBytesAsync("otter.png", image.ImageResultBytes.ToArray());

来源示例6(ruby)

本段复用的中文释义:译释4、译释23、译释24。

## [中文] 本例在Responses中调用图像生成工具;顶层model选择主模型,工具负责生成图像。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
require "base64"
require "openai"

client = OpenAI::Client.new
## [中文] 发送生成请求,工具模型在tools配置中指定。
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"
## [中文] 解码Base64内容,以二进制形式写入图像文件。
File.binwrite("otter.png", Base64.strict_decode64(encoded_image))

可以使用文件ID或Base64数据提供输入图像。要强制调用图像工具,将tool_choice设为{"type": "image_generation"}。

工具选项

图像生成工具支持以下输出选项:

  • 尺寸:例如1024×1024或1024×1536。
  • 质量:例如low、medium、high。
  • 格式:输出文件格式。
  • 压缩:JPEG和WebP的压缩设置,范围0—100%。
  • 背景:透明、不透明或自动。
  • 操作:自动决定、新生成或编辑图像。

size、quality、background支持auto,由模型根据提示选择。两款GPT Image 2.5的quality还接受xhigh和max,较早模型不支持;默认仍为auto。

gpt-image-2支持符合分辨率约束的灵活尺寸。透明背景处于预览阶段,需显式设置background: "transparent",并使用默认的png或webp,透明背景不支持jpeg。更多设置见自定义图像输出。

在Responses中,支持的GPT Image工具模型可决定生成新图还是编辑上下文已有图像。action默认是auto,也可设为generate或edit来强制指定操作。

改写后的提示词

主模型(例如gpt-5.5)会自动改写提示,以改善图像生成效果。工具调用的revised_prompt字段包含改写后的提示。

来源示例7(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

程序中的自然语言译释9:

一只灰色虎斑猫抱着一只戴橙色围巾的水獭;两只动物可爱友善,采用温暖、令人暖心的风格。

{
  "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": "..."
}

提示词技巧

提示中明确使用“绘制”(draw)或“编辑”(edit)往往更有效。例如,组合两张图时,不只说“组合”或“合并”,而是说明“编辑第一张图,把第二张图中的这个元素加入其中”。

多轮编辑

引用先前响应ID或图像ID,即可跨轮次持续编辑并完善图像。

使用先前响应ID:

来源示例8(javascript)

程序中的自然语言译释5:

现在让它看起来更写实。

本段复用的中文释义:译释3。

// [中文] 先生成并保存第一幅图,再用previous_response_id引用首轮响应,要求将画面改为写实并保存后续结果。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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

// [中文] 发送后续编辑请求;下面的响应ID或调用引用提供先前图像上下文。
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")
  );
}

来源示例9(python)

本段复用的中文释义:译释3、译释5。

## [中文] 先生成并保存第一幅图,再用previous_response_id引用首轮响应,要求将画面改为写实并保存后续结果。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得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:
        # [中文] 把Base64解码后的字节保存为图像文件。
        f.write(base64.b64decode(image_base64))


## Follow up

## [中文] 发送后续请求,延续或引用首轮图像上下文。
response_fwup = client.responses.create(
    model="gpt-6-astra",
    # [中文] 引用首轮响应ID,将先前生成的图像保留在上下文中。
    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:
        # [中文] 把Base64解码后的字节保存为图像文件。
        f.write(base64.b64decode(image_base64))

来源示例10(go)

本段复用的中文释义:译释3、译释5、译释30。

// [中文] 先生成并保存第一幅图,再用previous_response_id引用首轮响应,要求将画面改为写实并保存后续结果。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得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",
        // [中文] 通过首轮响应ID延续图像上下文。
        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
        }
        // [中文] 将工具结果中的Base64解码为图像字节。
        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")
}

来源示例11(java)

程序中的自然语言译释27:

后续请求没有返回图像生成调用。

程序中的自然语言译释28:

后续请求没有返回图像。

本段复用的中文释义:译释4、译释5、译释23、译释24。

// [中文] 先生成并保存第一幅图,再用previous_response_id引用首轮响应,要求将画面改为写实并保存后续结果。
// [中文] 本Java片段只设置顶层主模型,未显式指定图像工具的model;不要把主模型ID当作工具模型ID。
// [中文] 原例是API片段,使用前需已有client以及适当外层程序;未独立编译或执行请求。
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"));
// [中文] 把Base64解码所得图像字节写入文件。
Files.write(
    Path.of("cat_and_otter.png"),
    Base64.getDecoder()
        .decode(
            firstImage
                .result()
                .orElseThrow(() -> new IllegalStateException("No image returned"))));

// [中文] 发送第二轮编辑请求,传入响应ID或图像调用引用。
var second =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .input("Now make it look realistic.")
                // [中文] 用首轮响应ID继续同一上下文。
                .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"));
// [中文] 把Base64解码所得图像字节写入文件。
Files.write(
    Path.of("cat_and_otter_realistic.png"),
    Base64.getDecoder()
        .decode(
            secondImage
                .result()
                .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));

来源示例12(csharp)

本段复用的中文释义:译释4、译释5。

// [中文] 先生成并保存第一幅图,再用previous_response_id引用首轮响应,要求将画面改为写实并保存后续结果。
// [中文] 本C#例显式指定图像工具模型;SDK提供ImageResultBytes,可直接保存字节,不手动解码Base64。
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();
// [中文] SDK已提供图像字节,直接写入文件。
await File.WriteAllBytesAsync("cat_and_otter.png", initialImage.ImageResultBytes.ToArray());

CreateResponseOptions followUp = new()
{
    Model = "gpt-6-astra",
    // [中文] 引用首轮响应ID来继续图像会话。
    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();
// [中文] SDK已提供图像字节,直接写入文件。
await File.WriteAllBytesAsync(
    "cat_and_otter_realistic.png",
    updatedImage.ImageResultBytes.ToArray()
);

来源示例13(ruby)

本段复用的中文释义:译释4、译释5、译释23、译释24、译释27、译释28。

## [中文] 先生成并保存第一幅图,再用previous_response_id引用首轮响应,要求将画面改为写实并保存后续结果。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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"
## [中文] 解码Base64内容,以二进制形式写入图像文件。
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.",
  # [中文] 用首轮响应ID延续上下文。
  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"
## [中文] 解码Base64内容,以二进制形式写入图像文件。
File.binwrite("cat_and_otter_realistic.png", Base64.strict_decode64(encoded_image))

使用图像ID:

来源示例14(javascript)

本段复用的中文释义:译释3、译释5。

// [中文] 先生成并保存第一幅图;后续输入包含新指令和先前图像生成调用引用,再保存编辑结果。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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" }],
});

// [中文] 保留图像生成调用对象,后续需要引用其调用ID。
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

// [中文] 发送后续编辑请求;下面的响应ID或调用引用提供先前图像上下文。
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;这不是本地文件名或Files上传ID。
      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")
  );
}

来源示例15(python)

本段复用的中文释义:译释3、译释5。

## [中文] 先生成并保存第一幅图;后续输入包含新指令和先前图像生成调用引用,再保存编辑结果。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得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"}],
)

## [中文] 保留图像生成调用对象以便引用调用ID。
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:
        # [中文] 把Base64解码后的字节保存为图像文件。
        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引用首轮图像,不使用Files文件ID。
            "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:
        # [中文] 把Base64解码后的字节保存为图像文件。
        f.write(base64.b64decode(image_base64))

来源示例16(go)

本段复用的中文释义:译释3、译释5、译释30。

// [中文] 本Go例先生成并保存图像,再将首轮全部output经RawJSON转换为输入项,追加后续编辑指令;没有仅传一个图像ID。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得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
        // [中文] 将输出项的原始JSON转换为可复用的输入项。
        if err := json.Unmarshal([]byte(item.RawJSON()), &converted); err != nil {
            panic(err)
        }
        input = append(input, converted.ToParam())
    }
    return input
}

func saveImage(filename, encoded string) {
    // [中文] 将工具结果中的Base64解码为图像字节。
    image, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        panic(err)
    }
    // [中文] 将图像字节写入指定文件。
    if err := os.WriteFile(filename, image, 0o600); err != nil {
        panic(err)
    }
}

来源示例17(java)

本段复用的中文释义:译释4、译释5、译释23、译释24、译释27、译释28。

// [中文] 先生成并保存第一幅图;后续输入包含新指令和先前图像生成调用引用,再保存编辑结果。
// [中文] 本Java片段只设置顶层主模型,未显式指定图像工具的model;不要把主模型ID当作工具模型ID。
// [中文] 原例是API片段,使用前需已有client以及适当外层程序;未独立编译或执行请求。
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"));
// [中文] 把Base64解码所得图像字节写入文件。
Files.write(
    Path.of("cat_and_otter.png"),
    Base64.getDecoder()
        .decode(
            firstImage
                .result()
                .orElseThrow(() -> new IllegalStateException("No image returned"))));

// [中文] 发送第二轮编辑请求,传入响应ID或图像调用引用。
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(
                                // [中文] 以首轮图像生成调用ID构造引用,不是上传文件ID。
                                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"));
// [中文] 把Base64解码所得图像字节写入文件。
Files.write(
    Path.of("cat_and_otter_realistic.png"),
    Base64.getDecoder()
        .decode(
            secondImage
                .result()
                .orElseThrow(() -> new IllegalStateException("No follow-up image returned"))));

来源示例18(csharp)

本段复用的中文释义:译释4、译释5。

// [中文] 先生成并保存第一幅图;后续输入包含新指令和先前图像生成调用引用,再保存编辑结果。
// [中文] 本C#例显式指定图像工具模型;SDK提供ImageResultBytes,可直接保存字节,不手动解码Base64。
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();
// [中文] SDK已提供图像字节,直接写入文件。
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."));
// [中文] 用首轮图像调用ID构造引用,带入下一轮输入。
followUp.InputItems.Add(ResponseItem.CreateReferenceItem(initialImage.Id));

// [中文] 读取后续编辑响应,并保存更新后的图像。
ResponseResult second = await client.CreateResponseAsync(followUp);
ImageGenerationCallResponseItem updatedImage = second
    // [中文] 从响应项中筛选图像生成调用。
    .OutputItems.OfType<ImageGenerationCallResponseItem>()
    .First();
// [中文] SDK已提供图像字节,直接写入文件。
await File.WriteAllBytesAsync(
    "cat_and_otter_realistic.png",
    updatedImage.ImageResultBytes.ToArray()
);

来源示例19(ruby)

本段复用的中文释义:译释4、译释5、译释23、译释24、译释27、译释28。

## [中文] 先生成并保存第一幅图;后续输入包含新指令和先前图像生成调用引用,再保存编辑结果。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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"
## [中文] 解码Base64内容,以二进制形式写入图像文件。
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,区别于上传文件ID。
      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"
## [中文] 解码Base64内容,以二进制形式写入图像文件。
File.binwrite("cat_and_otter_realistic.png", Base64.strict_decode64(encoded_image))

流式输出

工具生成最终图像时,可以先流式返回部分图像,让用户更快得到视觉反馈,改善等待感受。使用partial_images指定部分图像数量,工具页给出的范围为1—3。

来源示例20(javascript)

程序中的自然语言译释6:

绘制由白色猫头鹰羽毛组成的美丽河流,蜿蜒流经宁静冬日景观。

// [中文] 请求Responses流式输出和两幅部分图;按部分图像事件保存预览,再在完成事件中提取并保存最终图像。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI();

function saveBase64Image(filename, imageBase64) {
  // [中文] 将Base64字符串解码为二进制图像。
  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]);
    }
  }
}

来源示例21(python)

本段复用的中文释义:译释6。

## [中文] 请求Responses流式输出和两幅部分图;按部分图像事件保存预览,再在完成事件中提取并保存最终图像。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
from openai import OpenAI
import base64

client = OpenAI()


def save_base64_image(filename, image_base64):
    # [中文] 将Base64字符串还原为图像字节。
    image_bytes = base64.b64decode(image_base64)
    # [中文] 以二进制模式打开输出文件。
    with open(filename, "wb") as f:
        # [中文] 把Base64解码后的字节保存为图像文件。
        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])

来源示例22(go)

本段复用的中文释义:译释6。

// [中文] 请求Responses流式输出和两幅部分图;按部分图像事件保存预览,再在完成事件中提取并保存最终图像。
// [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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) {
    // [中文] 将工具结果中的Base64解码为图像字节。
    image, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        panic(err)
    }
    // [中文] 将图像字节写入指定文件。
    if err := os.WriteFile(filename, image, 0o600); err != nil {
        panic(err)
    }
}

来源示例23(java)

程序中的自然语言译释7:

生成一条由白色猫头鹰羽毛组成的河流。

程序中的自然语言译释26:

没有返回生成的图像。

程序中的自然语言译释29:

没有返回最终图像。

// [中文] 请求Responses流式输出和两幅部分图;按部分图像事件保存预览,再在完成事件中提取并保存最终图像。
// [中文] 本Java片段只设置顶层主模型,未显式指定图像工具的model;不要把主模型ID当作工具模型ID。
// [中文] 原例是API片段,使用前需已有client以及适当外层程序;未独立编译或执行请求。
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();
      // [中文] 把Base64解码所得图像字节写入文件。
      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"));
      // [中文] 把Base64解码所得图像字节写入文件。
      Files.write(
          Path.of("river-final.png"),
          Base64.getDecoder()
              .decode(
                  image
                      .result()
                      .orElseThrow(
                          () -> new IllegalStateException("No final image returned"))));
    }
  }
}

来源示例24(ruby)

本段复用的中文释义:译释7。

## [中文] 请求Responses流式输出和两幅部分图;按部分图像事件保存预览,再在完成事件中提取并保存最终图像。
## [中文] 本例分别设置顶层主模型与工具模型;从图像生成调用结果取得Base64内容,再解码保存。
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)
    # [中文] 解码Base64内容,以二进制形式写入图像文件。
    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)

    # [中文] 解码Base64内容,以二进制形式写入图像文件。
    File.binwrite(
      "river-final.png",
      Base64.strict_decode64(image_call.result)
    )
  end
end

支持的模型

以下未弃用模型已在文档中列明支持Responses API的图像生成工具。把这些ID用于顶层model字段;具体可用性和访问要求见各模型页。

模型可用性与关闭日期见弃用公告。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号