InfoSphere/Spring AI 1.1.9-SNAPSHOT/ 返回书籍
Image Models

OpenAI

qianmoQqianmoQ· 更新于 2026-09-20· 阅读 29 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring AI 2.0.1!

OpenAI Image Generation

Spring AI supports DALL-E, the Image generation model from OpenAI.

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

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information.

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.

PropertyDescriptionDefault
spring.ai.openai.base-urlThe URL to connect toapi.openai.com
spring.ai.openai.api-keyThe API Key-
spring.ai.openai.organization-idOptionally you can specify which organization used for an API request.-
spring.ai.openai.project-idOptionally, you can specify which project is used for an API request.-
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 prefix spring.ai.retry is used as the property prefix that lets you configure the retry mechanism for the OpenAI Image client.

PropertyDescriptionDefault
spring.ai.retry.max-attemptsMaximum number of retry attempts.10
spring.ai.retry.backoff.initial-intervalInitial sleep duration for the exponential backoff policy.2 sec.
spring.ai.retry.backoff.multiplierBackoff interval multiplier.5
spring.ai.retry.backoff.max-intervalMaximum backoff duration.3 min.
spring.ai.retry.on-client-errorsIf false, throw a NonTransientAiException, and do not attempt retry for 4xx client error codesfalse
spring.ai.retry.exclude-on-http-codesList of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException).empty
spring.ai.retry.on-http-codesList of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException).empty

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.

PropertyDescriptionDefault
spring.ai.openai.image.enabled (Removed and no longer valid)Enable OpenAI image model.true
spring.ai.model.imageEnable OpenAI image model.openai
spring.ai.openai.image.base-urlOptional overrides the spring.ai.openai.base-url to provide chat specific url-
spring.ai.openai.image.api-keyOptional overrides the spring.ai.openai.api-key to provide chat specific api-key-
spring.ai.openai.image.organization-idOptionally you can specify which organization used for an API request.-
spring.ai.openai.image.project-idOptionally, you can specify which project is used for an API request.-
spring.ai.openai.image.options.nThe number of images to generate. Must be between 1 and 10. For dall-e-3, only n=1 is supported.-
spring.ai.openai.image.options.modelThe model to use for image generation.OpenAiImageApi.DEFAULT_IMAGE_MODEL
spring.ai.openai.image.options.qualityThe quality of the image that will be generated. HD creates images with finer details and greater consistency across the image. This parameter is only supported for dall-e-3.-
spring.ai.openai.image.options.response_formatThe format in which the generated images are returned. Must be one of URL or b64_json.-
spring.ai.openai.image.options.sizeThe size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models.-
spring.ai.openai.image.options.size_widthThe width of the generated images. Must be one of 256, 512, or 1024 for dall-e-2.-
spring.ai.openai.image.options.size_heightThe height of the generated images. Must be one of 256, 512, or 1024 for dall-e-2.-
spring.ai.openai.image.options.styleThe style of the generated images. Must be one of vivid or natural. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This parameter is only supported for dall-e-3.-
spring.ai.openai.image.options.userA 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 and spring.ai.openai.project-id properties. The spring.ai.openai.image.base-url, spring.ai.openai.image.api-key, spring.ai.openai.image.organization-id and spring.ai.openai.image.project-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.options 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 with the OpenAiImageModel(OpenAiImageApi openAiImageApi) constructor and the withDefaultOptions(OpenAiImageOptions defaultOptions) method. Alternatively, use the spring.ai.openai.image.options.* 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("hd")
                .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().

评论

登录后参与评论

正在加载评论…