You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
4
4
5
-
== Getting Started
5
+
== Pre-requisites
6
6
7
7
You will need to create an API with OpenAI to access ChatGPT models.
8
-
9
8
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
-
11
9
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
-
13
10
Exporting an environment variable is one way to set that configuration property:
14
11
15
12
[source,shell]
16
13
----
17
14
export SPRING_AI_OPENAI_API_KEY=<INSERT KEY HERE>
18
15
----
19
16
20
-
=== Configure the OpenAI Chat Client Manually
21
-
22
-
Add the `spring-ai-openai` dependency to your project's Maven `pom.xml` file:
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
94
18
95
19
Spring AI provides Spring Boot auto-configuration for the OpenAI Chat Client.
96
20
To enable it add the following dependency to your project's Maven `pom.xml` file:
@@ -115,16 +39,47 @@ dependencies {
115
39
116
40
NOTE: Refer to the xref:getting-started.adoc#_dependency_management[Dependency Management] section to add Milestone and/or Snapshot Repositories to your build file.
117
41
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
119
43
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.
121
45
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
126
49
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
128
83
129
84
This will create a `ChatClient` implementation that you can inject into your class.
130
85
Here is an example of a simple `@Controller` class that uses the `ChatClient` implementation.
@@ -163,43 +118,76 @@ public class ChatController {
163
118
}
164
119
----
165
120
166
-
== OpenAI Chat Properties
121
+
== Manual Configuration
167
122
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
+
----
169
133
170
-
[cols="3,5,1"]
171
-
|====
172
-
| Property | Description | Default
134
+
or to your Gradle `build.gradle` build file.
173
135
174
-
| spring.ai.openai.base-url | The URL to connect to | https://api.openai.com
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.
179
144
180
-
[cols="3,5,1"]
181
-
|====
182
-
| Property | Description | Default
145
+
Next, create an `OpenAiChatClient` instance and use it to text generations requests:
183
146
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());
201
157
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.
202
193
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