Skip to content

Commit ca0f6d7

Browse files
committed
OpenAi Chat/Embedding options handling optimizations
- Also restructure and clean the openai chat/embedding docs. Address review comments
1 parent aff4506 commit ca0f6d7

File tree

6 files changed

+222
-230
lines changed

6 files changed

+222
-230
lines changed

models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatClient.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2023-2023 the original author or authors.
2+
* Copyright 2023-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.

models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiEmbeddingClient.java

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import org.springframework.ai.document.MetadataMode;
2727
import org.springframework.ai.embedding.AbstractEmbeddingClient;
2828
import org.springframework.ai.embedding.Embedding;
29+
import org.springframework.ai.embedding.EmbeddingOptions;
2930
import org.springframework.ai.embedding.EmbeddingRequest;
3031
import org.springframework.ai.embedding.EmbeddingResponse;
3132
import org.springframework.ai.embedding.EmbeddingResponseMetadata;
@@ -51,9 +52,7 @@ public class OpenAiEmbeddingClient extends AbstractEmbeddingClient {
5152

5253
public static final String DEFAULT_OPENAI_EMBEDDING_MODEL = "text-embedding-ada-002";
5354

54-
private OpenAiEmbeddingOptions defaultOptions = OpenAiEmbeddingOptions.builder()
55-
.withModel(DEFAULT_OPENAI_EMBEDDING_MODEL)
56-
.build();
55+
private final OpenAiEmbeddingOptions defaultOptions;
5756

5857
private final RetryTemplate retryTemplate = RetryTemplate.builder()
5958
.maxAttempts(10)
@@ -76,15 +75,18 @@ public OpenAiEmbeddingClient(OpenAiApi openAiApi) {
7675
}
7776

7877
public OpenAiEmbeddingClient(OpenAiApi openAiApi, MetadataMode metadataMode) {
78+
this(openAiApi, metadataMode,
79+
OpenAiEmbeddingOptions.builder().withModel(DEFAULT_OPENAI_EMBEDDING_MODEL).build());
80+
}
81+
82+
public OpenAiEmbeddingClient(OpenAiApi openAiApi, MetadataMode metadataMode, OpenAiEmbeddingOptions options) {
7983
Assert.notNull(openAiApi, "OpenAiService must not be null");
8084
Assert.notNull(metadataMode, "metadataMode must not be null");
85+
Assert.notNull(options, "options must not be null");
86+
8187
this.openAiApi = openAiApi;
8288
this.metadataMode = metadataMode;
83-
}
84-
85-
public OpenAiEmbeddingClient withDefaultOptions(OpenAiEmbeddingOptions options) {
8689
this.defaultOptions = options;
87-
return this;
8890
}
8991

9092
@Override
@@ -93,19 +95,20 @@ public List<Double> embed(Document document) {
9395
return this.embed(document.getFormattedContent(this.metadataMode));
9496
}
9597

98+
@SuppressWarnings("unchecked")
9699
@Override
97100
public EmbeddingResponse call(EmbeddingRequest request) {
98101

99102
return this.retryTemplate.execute(ctx -> {
100-
org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<List<String>> apiRequest = new org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<>(
101-
request.getInstructions(), DEFAULT_OPENAI_EMBEDDING_MODEL);
102103

103-
if (this.defaultOptions != null) {
104-
apiRequest = ModelOptionsUtils.merge(apiRequest, this.defaultOptions,
105-
org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest.class);
106-
}
104+
org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<List<String>> apiRequest = (this.defaultOptions != null)
105+
? new org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<>(request.getInstructions(),
106+
this.defaultOptions.getModel(), this.defaultOptions.getEncodingFormat(),
107+
this.defaultOptions.getUser())
108+
: new org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest<>(request.getInstructions(),
109+
DEFAULT_OPENAI_EMBEDDING_MODEL);
107110

108-
if (request.getOptions() != null) {
111+
if (request.getOptions() != null && !EmbeddingOptions.EMPTY.equals(request.getOptions())) {
109112
apiRequest = ModelOptionsUtils.merge(request.getOptions(), apiRequest,
110113
org.springframework.ai.openai.api.OpenAiApi.EmbeddingRequest.class);
111114
}

spring-ai-docs/src/main/antora/modules/ROOT/pages/api/clients/openai-chat.adoc

Lines changed: 105 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -2,95 +2,19 @@
22

33
Spring AI supports ChatGPT, the AI language model by OpenAI. ChatGPT has been instrumental in sparking interest in AI-driven text generation, thanks to its creation of industry-leading text generation models and embeddings.
44

5-
== Getting Started
5+
== Pre-requisites
66

77
You will need to create an API with OpenAI to access ChatGPT models.
8-
98
Create an account at https://platform.openai.com/signup[OpenAI signup page] and generate the token on the https://platform.openai.com/account/api-keys[API Keys page].
10-
119
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.
12-
1310
Exporting an environment variable is one way to set that configuration property:
1411

1512
[source,shell]
1613
----
1714
export SPRING_AI_OPENAI_API_KEY=<INSERT KEY HERE>
1815
----
1916

20-
=== Configure the OpenAI Chat Client Manually
21-
22-
Add the `spring-ai-openai` dependency to your project's Maven `pom.xml` file:
23-
[source, xml]
24-
----
25-
<dependency>
26-
<groupId>org.springframework.ai</groupId>
27-
<artifactId>spring-ai-openai</artifactId>
28-
<version>0.8.0-SNAPSHOT</version>
29-
</dependency>
30-
----
31-
32-
or to your Gradle `build.gradle` build file.
33-
34-
[source,groovy]
35-
----
36-
dependencies {
37-
implementation 'org.springframework.ai:spring-ai-openai:0.8.0-SNAPSHOT'
38-
}
39-
----
40-
41-
NOTE: The `spring-ai-openai` dependency provides access also to the `OpenAiEmbeddingClient`. For more information about the `OpenAiEmbeddingClient` refer to the link:../embeddings/openai-embeddings.html[OpenAI Embeddings Client] section.
42-
43-
Next, create an `OpenAiChatClient` instance and use it to text generations requests:
44-
45-
[source,java]
46-
----
47-
var openAiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));
48-
49-
var chatClient = new OpenAiChatClient(openAiApi)
50-
.withDefaultOptions(OpenAiChatOptions.builder()
51-
.withModel("gpt-35-turbo")
52-
.withTemperature(0.4)
53-
.withMaxTokens(200)
54-
.build());
55-
56-
ChatResponse response = chatClient.call(
57-
new Prompt("Generate the names of 5 famous pirates."));
58-
59-
// Or with streaming responses
60-
Flux<ChatResponse> response = chatClient.stream(
61-
new Prompt("Generate the names of 5 famous pirates."));
62-
----
63-
64-
The `OpenAiChatOptions` provides the configuration information for the chat requests.
65-
The `OpenAiChatOptions.Builder` is fluent options builder.
66-
67-
==== ChatOptions and OpenAiChatOptions
68-
69-
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java[OpenAiChatOptions.java] provides provides the configuration information for the chat requests, such as the model to use, the temperature, the frequency penalty, etc.
70-
71-
The default options can be configured using the `spring.ai.openai.chat.options` properties as well.
72-
73-
On start-time use the `OpenAiChatClient#withDefaultOptions()` to set the default options applicable for all chat completion requests.
74-
At run-time you can override the default options with `OpenAiChatOptions` instance in the request `Prompt`.
75-
76-
For example to override the default model name and temperature for a specific request:
77-
78-
[source,java]
79-
----
80-
ChatResponse response = chatClient.call(
81-
new Prompt(
82-
"Generate the names of 5 famous pirates.",
83-
AzureOpenAiChatOptions.builder()
84-
.withModel("gpt-4-32k")
85-
.withTemperature(0.4)
86-
.build()
87-
));
88-
----
89-
90-
You can use as prompt options any instance that implements the portable `ChatOptions` interface.
91-
For example you can use the `ChatOptionsBuilder` to create a portable prompt options.
92-
93-
=== OpenAiChatClient Auto-configuration
17+
== Auto-configuration
9418

9519
Spring AI provides Spring Boot auto-configuration for the OpenAI Chat Client.
9620
To enable it add the following dependency to your project's Maven `pom.xml` file:
@@ -115,16 +39,47 @@ dependencies {
11539

11640
NOTE: Refer to the xref:getting-started.adoc#_dependency_management[Dependency Management] section to add Milestone and/or Snapshot Repositories to your build file.
11741

118-
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.
42+
=== Chat Properties
11943

120-
Exporting an environment variable is one way to set that configuration property:
44+
The prefix `spring.ai.openai` is used as the property prefix that lets you connect to OpenAI.
12145

122-
[source,shell]
123-
----
124-
export SPRING_AI_OPENAI_API_KEY=<INSERT KEY HERE>
125-
----
46+
[cols="3,5,1"]
47+
|====
48+
| Property | Description | Default
12649

127-
==== Sample Code
50+
| spring.ai.openai.base-url | The URL to connect to | https://api.openai.com
51+
| spring.ai.openai.api-key | The API Key | -
52+
|====
53+
54+
The prefix `spring.ai.openai.chat` is the property prefix that lets you configure the `ChatClient` implementation for OpenAI.
55+
56+
[cols="3,5,1"]
57+
|====
58+
| Property | Description | Default
59+
60+
| spring.ai.openai.chat.base-url | Optional overrides the spring.ai.openai.base-url to provide chat specific url | -
61+
| spring.ai.openai.chat.api-key | Optional overrides the spring.ai.openai.api-key to provide chat specific api-key | -
62+
| spring.ai.openai.chat.options.model | This is the OpenAI Chat model to use | `gpt-35-turbo` (the `gpt-3.5-turbo`, `gpt-4`, and `gpt-4-32k` point to the latest model versions)
63+
| 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 temperature and top_p for the same completions request as the interaction of these two settings is difficult to predict. | 0.8
64+
| 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
65+
| spring.ai.openai.chat.options.logitBias | Modify the likelihood of specified tokens appearing in the completion. | -
66+
| spring.ai.openai.chat.options.maxTokens | The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model's context length. | -
67+
| 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 n as 1 to minimize costs. | 1
68+
| 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. | -
69+
| spring.ai.openai.chat.options.responseFormat | An object specifying the format that the model must output. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.| -
70+
| 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. | -
71+
| spring.ai.openai.chat.options.stop | Up to 4 sequences where the API will stop generating further tokens. | -
72+
| 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 top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. | -
73+
| 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. | -
74+
| spring.ai.openai.chat.options.toolChoice | Controls which (if any) function is called by the model. none means the model will not call a function and instead generates a message. auto means the model can pick between generating a message or calling a function. Specifying a particular function via {"type: "function", "function": {"name": "my_function"}} forces the model to call that function. none is the default when no functions are present. auto is the default if functions are present. | -
75+
| spring.ai.openai.chat.options.user | A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. | -
76+
|====
77+
78+
NOTE: You can override the common `spring.ai.openai.base-url` and `spring.ai.openai.api-key` for the `ChatClient` and `EmbeddingClient` implementations.
79+
The `spring.ai.openai.chat.base-url` and `spring.ai.openai.chat.api-key` properties if set take precedence over the common properties.
80+
This is useful if you want to use different OpenAI accounts for different models and different model endpoints.
81+
82+
=== Sample Code
12883

12984
This will create a `ChatClient` implementation that you can inject into your class.
13085
Here is an example of a simple `@Controller` class that uses the `ChatClient` implementation.
@@ -163,43 +118,76 @@ public class ChatController {
163118
}
164119
----
165120

166-
== OpenAI Chat Properties
121+
== Manual Configuration
167122

168-
The prefix `spring.ai.openai` is used as the property prefix that lets you connect to OpenAI.
123+
If you are not using Spring Boot, you can manually configure the `OpenAiChatClient` by creating the beans in your configuration class.
124+
For this add the `spring-ai-openai` dependency to your project's Maven `pom.xml` file:
125+
[source, xml]
126+
----
127+
<dependency>
128+
<groupId>org.springframework.ai</groupId>
129+
<artifactId>spring-ai-openai</artifactId>
130+
<version>0.8.0-SNAPSHOT</version>
131+
</dependency>
132+
----
169133

170-
[cols="3,5,1"]
171-
|====
172-
| Property | Description | Default
134+
or to your Gradle `build.gradle` build file.
173135

174-
| spring.ai.openai.base-url | The URL to connect to | https://api.openai.com
175-
| spring.ai.openai.api-key | The API Key | -
176-
|====
136+
[source,groovy]
137+
----
138+
dependencies {
139+
implementation 'org.springframework.ai:spring-ai-openai:0.8.0-SNAPSHOT'
140+
}
141+
----
177142

178-
The prefix `spring.ai.openai.chat` is the property prefix that lets you configure the `ChatClient` implementation for OpenAI.
143+
NOTE: The `spring-ai-openai` dependency provides access also to the `OpenAiEmbeddingClient`. For more information about the `OpenAiEmbeddingClient` refer to the link:../embeddings/openai-embeddings.html[OpenAI Embeddings Client] section.
179144

180-
[cols="3,5,1"]
181-
|====
182-
| Property | Description | Default
145+
Next, create an `OpenAiChatClient` instance and use it to text generations requests:
183146

184-
| spring.ai.openai.chat.base-url | Optional overrides the spring.ai.openai.base-url to provide chat specific url | -
185-
| spring.ai.openai.chat.api-key | Optional overrides the spring.ai.openai.api-key to provide chat specific api-key | -
186-
| spring.ai.openai.chat.options.model | This is the OpenAI Chat model to use | `gpt-35-turbo` (the `gpt-3.5-turbo`, `gpt-4`, and `gpt-4-32k` point to the latest model versions)
187-
| 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 temperature and top_p for the same completions request as the interaction of these two settings is difficult to predict. | 0.8
188-
| 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
189-
| spring.ai.openai.chat.options.logitBias | Modify the likelihood of specified tokens appearing in the completion. | -
190-
| spring.ai.openai.chat.options.maxTokens | The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model's context length. | -
191-
| 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 n as 1 to minimize costs. | 1
192-
| 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. | -
193-
| spring.ai.openai.chat.options.responseFormat | An object specifying the format that the model must output. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.| -
194-
| 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. | -
195-
| spring.ai.openai.chat.options.stop | Up to 4 sequences where the API will stop generating further tokens. | -
196-
| 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 top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. | -
197-
| 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. | -
198-
| spring.ai.openai.chat.options.toolChoice | Controls which (if any) function is called by the model. none means the model will not call a function and instead generates a message. auto means the model can pick between generating a message or calling a function. Specifying a particular function via {"type: "function", "function": {"name": "my_function"}} forces the model to call that function. none is the default when no functions are present. auto is the default if functions are present. | -
199-
| spring.ai.openai.chat.options.user | A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. | -
200-
|====
147+
[source,java]
148+
----
149+
var openAiApi = new OpenAiApi(System.getenv("OPENAI_API_KEY"));
150+
151+
var chatClient = new OpenAiChatClient(openAiApi)
152+
.withDefaultOptions(OpenAiChatOptions.builder()
153+
.withModel("gpt-35-turbo")
154+
.withTemperature(0.4)
155+
.withMaxTokens(200)
156+
.build());
201157
158+
ChatResponse response = chatClient.call(
159+
new Prompt("Generate the names of 5 famous pirates."));
160+
161+
// Or with streaming responses
162+
Flux<ChatResponse> response = chatClient.stream(
163+
new Prompt("Generate the names of 5 famous pirates."));
164+
----
165+
166+
The `OpenAiChatOptions` provides the configuration information for the chat requests.
167+
The `OpenAiChatOptions.Builder` is fluent options builder.
168+
169+
=== Chat Options
170+
171+
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java[OpenAiChatOptions.java] provides provides the configuration information for the chat requests, such as the model to use, the temperature, the frequency penalty, etc.
172+
173+
The default options can be configured using the `spring.ai.openai.chat.options` properties as well.
174+
On start-time use the `OpenAiChatClient#withDefaultOptions()` to set the default options applicable for all chat completion requests.
175+
At run-time you can override the default options with `OpenAiChatOptions` instance in the request `Prompt`.
176+
177+
For example to override the default model name and temperature for a specific request:
178+
179+
[source,java]
180+
----
181+
ChatResponse response = chatClient.call(
182+
new Prompt(
183+
"Generate the names of 5 famous pirates.",
184+
AzureOpenAiChatOptions.builder()
185+
.withModel("gpt-4-32k")
186+
.withTemperature(0.4)
187+
.build()
188+
));
189+
----
190+
191+
You can use as prompt options any instance that implements the portable `ChatOptions` interface.
192+
For example you can use the `ChatOptionsBuilder` to create a portable prompt options.
202193

203-
NOTE: You can override the common `spring.ai.openai.base-url` and `spring.ai.openai.api-key` for the `ChatClient` and `EmbeddingClient` implementations.
204-
The `spring.ai.openai.chat.base-url` and `spring.ai.openai.chat.api-key` properties if set take precedence over the common properties.
205-
This is useful if you want to use different OpenAI accounts for different models and different model endpoints.

0 commit comments

Comments
 (0)