This version is still in development and is not considered stable yet. For the latest stable version, please use Spring AI 2.1.0!

OpenAI Image Generation

Spring AI supports the image generation models from OpenAI, such as the GPT Image models.

Spring AI uses the official openai-java SDK for all OpenAI models. If you are upgrading from a version that used the Spring AI OpenAI client, see OpenAI Java SDK Transition. Report any issues at Spring AI GitHub Issues.

Prerequisites

You will need to create an API key with OpenAI to access ChatGPT models.

Create an account at OpenAI signup page and generate the token on the API Keys page.

The Spring AI project defines a configuration property named spring.ai.openai.api-key that you should set to the value of the API Key obtained from openai.com.

You can set this configuration property in your application.properties file:

spring.ai.openai.api-key=<your-openai-api-key>

For enhanced security when handling sensitive information like API keys, you can use Spring Expression Language (SpEL) to reference a custom environment variable:

# In application.yml
spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
# In your environment or .env file
export OPENAI_API_KEY=<your-openai-api-key>

You can also set this configuration programmatically in your application code:

// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("OPENAI_API_KEY");

Auto-configuration

Spring AI provides Spring Boot auto-configuration for the OpenAI Image Generation Client. To enable it add the following dependency to your project’s Maven pom.xml file:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
Refer to the Dependency Management section to add the Spring AI BOM to your build file.

Image Generation Properties

Connection Properties

The prefix spring.ai.openai is used as the property prefix that lets you connect to OpenAI.

Property

Description

Default

spring.ai.openai.base-url

The URL to connect to

api.openai.com

spring.ai.openai.api-key

The API Key

-

spring.ai.openai.organization-id

Optionally you can specify which organization used for an API request.

-

spring.ai.openai.timeout

Request timeout for the OpenAI client.

60 sec.

spring.ai.openai.max-retries

Maximum number of retries for the OpenAI client.

3

spring.ai.openai.proxy

Proxy settings for the OpenAI client.

-

spring.ai.openai.custom-headers

Custom HTTP headers to add to OpenAI client requests.

empty

spring.ai.openai.connection-pool-metrics-enabled

Whether to enable connection pool metrics for the underlying OkHttp client.

false

For users that belong to multiple organizations (or are accessing their projects through their legacy user API key), optionally, you can specify which organization and project is used for an API request. Usage from these API requests will count as usage for the specified organization and project.

Retry Properties

The OpenAI module does not use the spring.ai.retry properties. The OpenAI Java SDK retries failed requests itself: set spring.ai.openai.max-retries (default 3) for all OpenAI models, or spring.ai.openai.image.max-retries for this model only. See Retry for the providers that use the Spring AI retry.

Configuration Properties

Enabling and disabling of the image auto-configurations are now configured via top level properties with the prefix spring.ai.model.image.

To enable, spring.ai.model.image=openai (It is enabled by default)

To disable, spring.ai.model.image=none (or any value which doesn’t match openai)

This change is done to allow configuration of multiple models.

The prefix spring.ai.openai.image is the property prefix that lets you configure the ImageModel implementation for OpenAI.

Property

Description

Default

spring.ai.model.image

Enable OpenAI image model.

openai

spring.ai.openai.image.base-url

Optional overrides the spring.ai.openai.base-url to provide chat specific url

-

spring.ai.openai.image.api-key

Optional overrides the spring.ai.openai.api-key to provide chat specific api-key

-

spring.ai.openai.image.organization-id

Optionally you can specify which organization used for an API request.

-

spring.ai.openai.image.n

The number of images to generate. Must be between 1 and 10.

-

spring.ai.openai.image.model

The model to use for image generation.

gpt-image-1-mini

spring.ai.openai.image.quality

The quality of the image that will be generated: auto (the default of the API), low, medium or high for the GPT Image models.

-

spring.ai.openai.image.response_format

Legacy parameter of the retired DALL-E models: url or b64_json. The GPT Image models do not support it and always return base64-encoded images.

-

spring.ai.openai.image.size

The size of the generated images, for example 1024x1024, 1536x1024, 1024x1536 or auto. The sizes that are supported depend on the model.

-

spring.ai.openai.image.width

The width of the generated images. Together with height it sets the size.

-

spring.ai.openai.image.height

The height of the generated images. Together with width it sets the size.

-

spring.ai.openai.image.style

Legacy parameter of the retired DALL-E models: vivid or natural. The GPT Image models do not support it: describe the style in the prompt.

-

spring.ai.openai.image.user

A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.

-

You can override the common spring.ai.openai.base-url, spring.ai.openai.api-key, spring.ai.openai.organization-id properties. The spring.ai.openai.image.base-url, spring.ai.openai.image.api-key and spring.ai.openai.image.organization-id properties if set take precedence over the common properties. This is useful if you want to use different OpenAI accounts for different models and different model endpoints.
All properties prefixed with spring.ai.openai.image can be overridden at runtime.

Runtime Options

The OpenAiImageOptions.java provides model configurations, such as the model to use, the quality, the size, etc.

On start-up, the default options can be configured by passing OpenAiImageOptions to OpenAiImageModel.builder().options(…​). Alternatively, use the spring.ai.openai.image.* properties described previously.

At runtime you can override the default options by adding new, request specific, options to the ImagePrompt call. For example to override the OpenAI specific options such as quality and the number of images to create, use the following code example:

ImageResponse response = openaiImageModel.call(
        new ImagePrompt("A light cream colored mini golden doodle",
        OpenAiImageOptions.builder()
                .quality("high")
                .n(4)
                .height(1024)
                .width(1024).build())

);
In addition to the model specific OpenAiImageOptions you can use a portable ImageOptions instance, created with the ImageOptionsBuilder#builder().

Customizing the HTTP Client

Spring AI uses the official openai-java SDK under the hood and configures its HTTP transport with a custom OkHttp client built by SpringAiOpenAiHttpClient.Builder. You can intercept that builder before the underlying OkHttpClient is created by exposing one or more OpenAiHttpClientBuilderCustomizer beans. Each customizer receives the same builder used by every OpenAI model (chat, embedding, image, audio, moderation), so the customization applies uniformly.

@FunctionalInterface
public interface OpenAiHttpClientBuilderCustomizer {
    void customize(SpringAiOpenAiHttpClient.Builder builder);
}

Typical use cases include:

  • registering OkHttp Interceptor instances (authentication, propagation headers, custom logging);

  • swapping the dispatcher ExecutorService (for example, to route async I/O through virtual threads);

  • configuring proxy, SSL, hostname verification, or the connection-pool sizing exposed by the builder.

When several customizers are present, they are applied in @Order / Ordered order, after Spring AI’s own defaults, so user code wins.

The same hook is available when wiring a model manually via the OpenAi*Model.Builder:

var chatModel = OpenAiChatModel.builder()
    .options(OpenAiChatOptions.builder().model("gpt-4o").build())
    .httpClientBuilderCustomizer(myCustomizer)
    .build();