OpenAI Chat
Spring AI supports the various AI language models from OpenAI, the company behind ChatGPT, which has been instrumental in sparking interest in AI-driven text generation thanks to its creation of industry-leading text generation models and embeddings.
Prerequisites
You will need to create an API 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.
Exporting an environment variable is one way to set that configuration property:
export SPRING_AI_OPENAI_API_KEY=<INSERT KEY HERE>
Add Repositories and BOM
Spring AI artifacts are published in Spring Milestone and Snapshot repositories. Refer to the Repositories section to add these repositories to your build system.
To help with dependency management, Spring AI provides a BOM (bill of materials) to ensure that a consistent version of Spring AI is used throughout the entire project. Refer to the Dependency Management section to add the Spring AI BOM to your build system.
Auto-configuration
Spring AI provides Spring Boot auto-configuration for the OpenAI Chat Client.
To enable it add the following dependency to your project’s Maven pom.xml
or Gradle build.gradle
build files:
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
Chat Properties
Retry Properties
The prefix spring.ai.retry
is used as the property prefix that lets you configure the retry mechanism for the OpenAI chat model.
Property | Description | Default |
---|---|---|
spring.ai.retry.max-attempts |
Maximum number of retry attempts. |
10 |
spring.ai.retry.backoff.initial-interval |
Initial sleep duration for the exponential backoff policy. |
2 sec. |
spring.ai.retry.backoff.multiplier |
Backoff interval multiplier. |
5 |
spring.ai.retry.backoff.max-interval |
Maximum backoff duration. |
3 min. |
spring.ai.retry.on-client-errors |
If false, throw a NonTransientAiException, and do not attempt retry for |
false |
spring.ai.retry.exclude-on-http-codes |
List of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException). |
empty |
spring.ai.retry.on-http-codes |
List of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException). |
empty |
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 |
|
spring.ai.openai.api-key |
The API Key |
- |
spring.ai.openai.organization-id |
Optionally, you can specify which organization to use for an API request. |
- |
spring.ai.openai.project-id |
Optionally, you can specify which project to use for an API request. |
- |
For users that belong to multiple organizations (or are accessing their projects through their legacy user API key), you can optionally 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. |
Configuration Properties
The prefix spring.ai.openai.chat
is the property prefix that lets you configure the chat model implementation for OpenAI.
Property | Description | Default |
---|---|---|
spring.ai.openai.chat.enabled |
Enable OpenAI chat model. |
true |
spring.ai.openai.chat.base-url |
Optional override for the |
- |
spring.ai.openai.chat.completions-path |
The path to append to the base URL. |
|
spring.ai.openai.chat.api-key |
Optional override for the |
- |
spring.ai.openai.chat.organization-id |
Optionally, you can specify which organization to use for an API request. |
- |
spring.ai.openai.chat.project-id |
Optionally, you can specify which project to use for an API request. |
- |
spring.ai.openai.chat.options.model |
Name of the OpenAI chat model to use. You can select between models such as: |
|
spring.ai.openai.chat.options.temperature |
The sampling temperature to use that controls the apparent creativity of generated completions. Higher values will make output more random while lower values will make results more focused and deterministic. It is not recommended to modify |
0.8 |
spring.ai.openai.chat.options.frequencyPenalty |
Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model’s likelihood to repeat the same line verbatim. |
0.0f |
spring.ai.openai.chat.options.logitBias |
Modify the likelihood of specified tokens appearing in the completion. |
- |
spring.ai.openai.chat.options.maxTokens |
(Deprecated in favour of |
- |
spring.ai.openai.chat.options.maxCompletionTokens |
An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens. |
- |
spring.ai.openai.chat.options.n |
How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep |
1 |
spring.ai.openai.chat.options.presencePenalty |
Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model’s likelihood to talk about new topics. |
- |
spring.ai.openai.chat.options.responseFormat.type |
Compatible with |
- |
spring.ai.openai.chat.options.responseFormat.name |
Response format schema name. Applicable only for |
custom_schema |
spring.ai.openai.chat.options.responseFormat.schema |
Response format JSON schema. Applicable only for |
- |
spring.ai.openai.chat.options.responseFormat.strict |
Response format JSON schema adherence strictness. Applicable only for |
- |
spring.ai.openai.chat.options.seed |
This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result. |
- |
spring.ai.openai.chat.options.stop |
Up to 4 sequences where the API will stop generating further tokens. |
- |
spring.ai.openai.chat.options.topP |
An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with |
- |
spring.ai.openai.chat.options.tools |
A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. |
- |
spring.ai.openai.chat.options.toolChoice |
Controls which (if any) function is called by the model. |
- |
spring.ai.openai.chat.options.user |
A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. |
- |
spring.ai.openai.chat.options.functions |
List of functions, identified by their names, to enable for function calling in a single prompt requests. Functions with those names must exist in the |
- |
spring.ai.openai.chat.options.stream-usage |
(For streaming only) Set to add an additional chunk with token usage statistics for the entire request. The |
false |
spring.ai.openai.chat.options.parallel-tool-calls |
Whether to enable parallel function calling during tool use. |
true |
spring.ai.openai.chat.options.http-headers |
Optional HTTP headers to be added to the chat completion request. To override the |
- |
spring.ai.openai.chat.options.proxy-tool-calls |
If true, the Spring AI will not handle the function calls internally, but will proxy them to the client. Then is the client’s responsibility to handle the function calls, dispatch them to the appropriate function, and return the results. If false (the default), the Spring AI will handle the function calls internally. Applicable only for chat models with function calling support |
false |
You can override the common spring.ai.openai.base-url and spring.ai.openai.api-key for the ChatModel and EmbeddingModel implementations.
The spring.ai.openai.chat.base-url and spring.ai.openai.chat.api-key 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.chat.options can be overridden at runtime by adding request-specific Runtime Options to the Prompt call.
|
Runtime Options
The OpenAiChatOptions.java class provides model configurations such as the model to use, the temperature, the frequency penalty, etc.
On start-up, the default options can be configured with the OpenAiChatModel(api, options)
constructor or the spring.ai.openai.chat.options.*
properties.
At run-time, you can override the default options by adding new, request-specific options to the Prompt
call.
For example, to override the default model and temperature for a specific request:
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
OpenAiChatOptions.builder()
.withModel("gpt-4-o")
.withTemperature(0.4)
.build()
));
In addition to the model specific OpenAiChatOptions you can use a portable ChatOptions instance, created with ChatOptionsBuilder#builder(). |
Function Calling
You can register custom Java functions with the OpenAiChatModel
and have the OpenAI model intelligently choose to output a JSON object containing arguments to call one or many of the registered functions.
This is a powerful technique to connect the LLM capabilities with external tools and APIs.
Read more about OpenAI Function Calling.
Multimodal
Multimodality refers to a model’s ability to simultaneously understand and process information from various sources, including text, images, audio, and other data formats.
OpenAI models that offer multimodal support include gpt-4
, gpt-4o
, and gpt-4o-mini
.
Refer to the Vision guide for more information.
The OpenAI User Message API can incorporate a list of base64-encoded images or image urls with the message.
Spring AI’s Message interface facilitates multimodal AI models by introducing the Media type.
This type encompasses data and details regarding media attachments in messages, utilizing Spring’s org.springframework.util.MimeType
and a org.springframework.core.io.Resource
for the raw media data.
Below is a code example excerpted from OpenAiChatModelIT.java, illustrating the fusion of user text with an image using the gpt-4o
model.
var imageResource = new ClassPathResource("/multimodal.test.png");
var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG, this.imageResource));
ChatResponse response = chatModel.call(new Prompt(this.userMessage,
OpenAiChatOptions.builder().withModel(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));
GPT_4_VISION_PREVIEW will continue to be available only to existing users of this model starting June 17, 2024. If you are not an existing user, please use the GPT_4_O or GPT_4_TURBO models. More details here |
or the image URL equivalent using the gpt-4o
model:
var userMessage = new UserMessage("Explain what do you see on this picture?",
new Media(MimeTypeUtils.IMAGE_PNG,
"https://docs.spring.io/spring-ai/reference/_images/multimodal.test.png"));
ChatResponse response = chatModel.call(new Prompt(this.userMessage,
OpenAiChatOptions.builder().withModel(OpenAiApi.ChatModel.GPT_4_O.getValue()).build()));
You can pass multiple images as well. |
The example shows a model taking as an input the multimodal.test.png
image:
along with the text message "Explain what do you see on this picture?", and generating a response like this:
This is an image of a fruit bowl with a simple design. The bowl is made of metal with curved wire edges that create an open structure, allowing the fruit to be visible from all angles. Inside the bowl, there are two yellow bananas resting on top of what appears to be a red apple. The bananas are slightly overripe, as indicated by the brown spots on their peels. The bowl has a metal ring at the top, likely to serve as a handle for carrying. The bowl is placed on a flat surface with a neutral-colored background that provides a clear view of the fruit inside.
Structured Outputs
OpenAI provides custom Structured Outputs APIs that ensure your model generates responses conforming strictly to your provided JSON Schema
.
In addition to the existing Spring AI model-agnostic Structured Output Converter, these APIs offer enhanced control and precision.
Currently, OpenAI supports a subset of the JSON Schema language format. |
Configuration
Spring AI allows you to configure your response format either programmatically using the OpenAiChatOptions
builder or through application properties.
Using the Chat Options Builder
You can set the response format programmatically with the OpenAiChatOptions
builder as shown below:
String jsonSchema = """
{
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"explanation": { "type": "string" },
"output": { "type": "string" }
},
"required": ["explanation", "output"],
"additionalProperties": false
}
},
"final_answer": { "type": "string" }
},
"required": ["steps", "final_answer"],
"additionalProperties": false
}
""";
Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.withModel(ChatModel.GPT_4_O_MINI)
.withResponseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, this.jsonSchema))
.build());
ChatResponse response = this.openAiChatModel.call(this.prompt);
Adhere to the OpenAI subset of the JSON Schema language format. |
Integrating with BeanOutputConverter Utilities
You can leverage existing BeanOutputConverter utilities to automatically generate the JSON Schema from your domain objects and later convert the structured response into domain-specific instances:
-
Java
-
Kotlin
record MathReasoning(
@JsonProperty(required = true, value = "steps") Steps steps,
@JsonProperty(required = true, value = "final_answer") String finalAnswer) {
record Steps(
@JsonProperty(required = true, value = "items") Items[] items) {
record Items(
@JsonProperty(required = true, value = "explanation") String explanation,
@JsonProperty(required = true, value = "output") String output) {
}
}
}
var outputConverter = new BeanOutputConverter<>(MathReasoning.class);
var jsonSchema = this.outputConverter.getJsonSchema();
Prompt prompt = new Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.withModel(ChatModel.GPT_4_O_MINI)
.withResponseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, this.jsonSchema))
.build());
ChatResponse response = this.openAiChatModel.call(this.prompt);
String content = this.response.getResult().getOutput().getContent();
MathReasoning mathReasoning = this.outputConverter.convert(this.content);
data class MathReasoning(
@get:JsonProperty(required = true, value = "steps") val steps: Steps,
@get:JsonProperty(required = true, value = "final_answer") val finalAnswer: String) {
data class Steps(@get:JsonProperty(required = true, value = "items") val items: Array<Items>) {
data class Items(
@get:JsonProperty(required = true, value = "explanation") val explanation: String,
@get:JsonProperty(required = true, value = "output") val output: String)
}
}
val outputConverter = BeanOutputConverter(MathReasoning::class.java)
val jsonSchema = outputConverter.jsonSchema;
val prompt = Prompt("how can I solve 8x + 7 = -23",
OpenAiChatOptions.builder()
.withModel(ChatModel.GPT_4_O_MINI)
.withResponseFormat(ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, jsonSchema))
.build())
val response = openAiChatModel.call(prompt)
val content = response.getResult().getOutput().getContent()
val mathReasoning = outputConverter.convert(content)
Ensure you use the @JsonProperty(required = true,…) annotation (@get:JsonProperty(required = true,…) with Kotlin in order to generate the annotation on the related getters, see related documentation).
This is crucial for generating a schema that accurately marks fields as required .
Although this is optional for JSON Schema, OpenAI mandates it for the structured response to function correctly.
|
Configuring via Application Properties
Alternatively, when using the OpenAI auto-configuration, you can configure the desired response format through the following application properties:
spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o-mini
spring.ai.openai.chat.options.response-format.type=JSON_SCHEMA
spring.ai.openai.chat.options.response-format.name=MySchemaName
spring.ai.openai.chat.options.response-format.schema={"type":"object","properties":{"steps":{"type":"array","items":{"type":"object","properties":{"explanation":{"type":"string"},"output":{"type":"string"}},"required":["explanation","output"],"additionalProperties":false}},"final_answer":{"type":"string"}},"required":["steps","final_answer"],"additionalProperties":false}
spring.ai.openai.chat.options.response-format.strict=true
Sample Controller
Create a new Spring Boot project and add the spring-ai-openai-spring-boot-starter
to your pom (or gradle) dependencies.
Add an application.properties
file under the src/main/resources
directory to enable and configure the OpenAi chat model:
spring.ai.openai.api-key=YOUR_API_KEY
spring.ai.openai.chat.options.model=gpt-4o
spring.ai.openai.chat.options.temperature=0.7
Replace the api-key with your OpenAI credentials.
|
This will create an OpenAiChatModel
implementation that you can inject into your classes.
Here is an example of a simple @RestController
class that uses the chat model for text generations.
@RestController
public class ChatController {
private final OpenAiChatModel chatModel;
@Autowired
public ChatController(OpenAiChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map<String,String> generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return Map.of("generation", this.chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return this.chatModel.stream(prompt);
}
}
Manual Configuration
The OpenAiChatModel implements the ChatModel
and StreamingChatModel
and uses the Low-level OpenAiApi Client to connect to the OpenAI service.
Add the spring-ai-openai
dependency to your project’s Maven pom.xml
file:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai</artifactId>
</dependency>
or to your Gradle build.gradle
build file.
dependencies {
implementation 'org.springframework.ai:spring-ai-openai'
}
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
Next, create an OpenAiChatModel
and use it for text generations:
var openAiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));
var openAiChatOptions = OpenAiChatOptions.builder()
.withModel("gpt-3.5-turbo")
.withTemperature(0.4)
.withMaxTokens(200)
.build();
var chatModel = new OpenAiChatModel(this.openAiApi, this.openAiChatOptions);
ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
// Or with streaming responses
Flux<ChatResponse> response = this.chatModel.stream(
new Prompt("Generate the names of 5 famous pirates."));
The OpenAiChatOptions
provides the configuration information for the chat requests.
The OpenAiChatOptions.Builder
is a fluent options-builder.
Low-level OpenAiApi Client
The OpenAiApi provides is lightweight Java client for OpenAI Chat API OpenAI Chat API.
Following class diagram illustrates the OpenAiApi
chat interfaces and building blocks:
Here is a simple snippet showing how to use the API programmatically:
OpenAiApi openAiApi =
new OpenAiApi(System.getenv("OPENAI_API_KEY"));
ChatCompletionMessage chatCompletionMessage =
new ChatCompletionMessage("Hello world", Role.USER);
// Sync request
ResponseEntity<ChatCompletion> response = this.openAiApi.chatCompletionEntity(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), "gpt-3.5-turbo", 0.8, false));
// Streaming request
Flux<ChatCompletionChunk> streamResponse = this.openAiApi.chatCompletionStream(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), "gpt-3.5-turbo", 0.8, true));
Follow the OpenAiApi.java's JavaDoc for further information.
Low-level API Examples
-
The OpenAiApiIT.java tests provide some general examples of how to use the lightweight library.
-
The OpenAiApiToolFunctionCallIT.java tests show how to use the low-level API to call tool functions. Based on the OpenAI Function Calling tutorial.