Image Generation API

Types and functions for the Image Generation API (/v1/images/generations).

Request Type

UniLM.ImageGenerationType
ImageGeneration(; prompt, model="", kwargs...)

Configuration struct for an OpenAI Image Generation API request.

Key Fields

  • model::String: Model to use. The default is the sentinel "", which resolves at serialization time to the service's default image model ("gpt-image-2" for OpenAI) — so the field READS BACK as "" until you set it explicitly, and a service with no default image model throws ArgumentError when the request is serialized. Inspect JSON.json(ig) to see the model that will go on the wire.
  • prompt::String: A text description of the desired image
  • n::Union{Int,Nothing}: Number of images to generate (1–10)
  • size::Union{String,Nothing}: Size ("1024x1024", "1536x1024", "1024x1536", "auto")
  • quality::Union{String,Nothing}: Quality level ("low", "medium", "high", "auto")
  • background::Union{String,Nothing}: Background ("transparent", "opaque", "auto")
  • output_format::Union{String,Nothing}: File format ("png", "webp", "jpeg")
  • output_compression::Union{Int,Nothing}: Compression (0–100, for "webp" and "jpeg")
  • user::Union{String,Nothing}: End-user identifier
  • input_fidelity::Union{String,Nothing}: How closely to preserve an input image
  • moderation::Union{String,Nothing}: Content-moderation strictness

Examples

# Simple prompt
ImageGeneration(prompt="A watercolor painting of a mountain sunset")

# With all options
ImageGeneration(
    prompt="A minimalist logo for a Julia package",
    size="1024x1024",
    quality="high",
    background="transparent",
    output_format="png"
)
source
UniLM.ImageEditType
ImageEdit(; image, prompt, mask=nothing, model="", n=nothing, size=nothing,
          quality=nothing, input_fidelity=nothing, background=nothing, output_format=nothing)

An image-edit request. image is a path (or vector of paths); mask is an optional path. Sent as multipart/form-data to /v1/images/edits.

source

Construction

using UniLM
using JSON

# Minimal request. `model` is a sentinel: it stays "" on the struct and resolves
# only when the request is serialized, so read the wire body to see what will be
# sent rather than the field.
ig = ImageGeneration(prompt="A watercolor painting of a sunset")
println("Model field: ", repr(ig.model))
println("Model on the wire: ", JSON.parse(JSON.json(ig))["model"])
println("Prompt: ", ig.prompt)

# Full options
ig2 = ImageGeneration(
    prompt="A minimalist logo for a Julia package",
    size="1024x1024",
    quality="high",
    background="transparent",
    output_format="png",
    n=2
)
println("\nFull options:")
println("  Size: ", ig2.size)
println("  Quality: ", ig2.quality)
println("  Background: ", ig2.background)
println("  Format: ", ig2.output_format)
println("  Count: ", ig2.n)
Model field: ""
Model on the wire: gpt-image-2
Prompt: A watercolor painting of a sunset

Full options:
  Size: 1024x1024
  Quality: high
  Background: transparent
  Format: png
  Count: 2

JSON Serialization

ig = ImageGeneration(prompt="A cute robot", quality="high", size="1024x1024")
println(JSON.json(ig))
{"model":"gpt-image-2","prompt":"A cute robot","quality":"high","size":"1024x1024"}

Response Types

UniLM.ImageObjectType
ImageObject

A single generated image from the API response.

Fields

  • b64_json::Union{String,Nothing}: Base64-encoded image data
  • revised_prompt::Union{String,Nothing}: The prompt as revised by the model
source
UniLM.ImageResponseType
ImageResponse

Parsed response from the Image Generation API.

Accessors

  • image_data(r) — extract base64-encoded image data
  • r.created, r.data, r.usage — basic fields
  • r.raw — the complete raw JSON dict

Fields

  • created::Int64: Timestamp when the response was created
  • data::Vector{ImageObject}: Generated images
  • usage::Union{Dict{String,Any},Nothing}: Token usage information
  • raw::Dict{String,Any}: Complete raw JSON response
source

Result Types

UniLM.ImageSuccessType
ImageSuccess <: LLMRequestResponse

Successful image generation. Access the parsed response via .response.

Examples

result = generate_image("A cute robot")
if result isa ImageSuccess
    imgs = image_data(result)   # Vector{String} of base64 images
    save_image(imgs[1], "robot.png")
end
source
UniLM.ImageFailureType
ImageFailure <: LLMRequestResponse

HTTP-level failure from the Image Generation API. Contains the response body and status code.

source
UniLM.ImageCallErrorType
ImageCallError <: LLMRequestResponse

Exception-level error during an Image Generation API call (network, parsing, etc.).

source

Request Function

UniLM.generate_imageFunction
generate_image(ig::ImageGeneration)

Send a request to the OpenAI Image Generation API.

Returns ImageSuccess, ImageFailure, or ImageCallError.

Throws ArgumentError before any network I/O when ig.service is an endpoint type that declares its capabilities and does not list :images.

Examples

ig = ImageGeneration(prompt="A cute robot learning Julia", quality="high")
result = generate_image(ig)
if result isa ImageSuccess
    println("Generated $(length(result.response.data)) image(s)")
    save_image(image_data(result)[1], "robot.png")
end

Pass config::Union{Nothing,RequestConfig} to override the timeout/retry budget for this call.

source
generate_image(prompt::String; kwargs...)

Convenience method: create an ImageGeneration from a prompt + keyword arguments and send it.

Examples

# Simple generation
result = generate_image("A watercolor painting of a Julia butterfly")

# With options
result = generate_image(
    "A minimalist logo",
    size="1024x1024",
    quality="high",
    background="transparent"
)

# Save to file
if result isa ImageSuccess
    save_image(image_data(result)[1], "logo.png")
end
source
UniLM.edit_imageFunction
edit_image(e::ImageEdit) -> LLMRequestResponse
edit_image(image, prompt; mask=nothing, service=OPENAIServiceEndpoint, kwargs...)

Edit/extend image(s) under a text prompt. Returns the same ImageSuccess/ImageFailure/ ImageCallError shapes as generate_image.

Pass config::Union{Nothing,RequestConfig} to override the timeout/retry budget for this call.

source

Usage Examples

julia> result = generate_image(
           "A watercolor painting of a friendly robot reading a Julia programming book",
           size="1024x1024", quality="medium"
       )

julia> result isa ImageSuccess
true

julia> length(image_data(result))
1

julia> save_image(image_data(result)[1], "robot_julia.png")
"robot_julia.png"

Accessor Functions

UniLM.image_dataFunction
image_data(r::ImageResponse)::Vector{String}
image_data(r::ImageSuccess)::Vector{String}

Extract base64-encoded image data from a response. Returns a vector of base64 strings, one per generated image.

Examples

result = generate_image("A sunset over mountains")
imgs = image_data(result)       # Vector{String}
length(imgs)                     # number of images generated
source
UniLM.save_imageFunction
save_image(img_b64::String, filepath::String)

Decode a base64-encoded image and save it to a file.

Decoding happens before filepath is opened, so a malformed payload raises without touching whatever already lives there — a failed save costs nothing.

Examples

result = generate_image("A watercolor landscape")
if result isa ImageSuccess
    save_image(image_data(result)[1], "landscape.png")
end
source

Saving Images

result = generate_image("A sunset over mountains", n=3)
if result isa ImageSuccess
    for (i, img) in enumerate(image_data(result))
        save_image(img, "sunset_$i.png")
    end
end

Parameters Reference

ParameterTypeDefaultDescription
modelString""Sentinel; resolves on serialization to "gpt-image-2" for OpenAI
promptString(required)Text description of the image
nInt1Number of images (1–10)
sizeString"auto""1024x1024", "1536x1024", etc.
qualityString"auto""low", "medium", "high"
backgroundString"auto""transparent", "opaque"
output_formatString"png""png", "webp", "jpeg"
output_compressionInt0–100, for webp/jpeg
userStringEnd-user identifier
input_fidelityStringHow closely to preserve an input image
moderationStringContent-moderation strictness

Defaults shown as quoted strings other than model are the API's defaults for an omitted field; the struct stores nothing and omits them from the request body.