openai/openai-java

Public

mirrored from https://github.com/openai/openai-javaAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.13.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

README.md

424lines · modecode

1# OpenAI Java API Library
2
3> [!NOTE]
4> The OpenAI Java API Library is currently in _beta_.
5>
6> There may be frequent breaking changes.
7>
8> Have thoughts or feedback? [File an issue](https://github.com/openai/openai-java/issues/new) or comment on [this thread](https://community.openai.com/t/your-feedback-requested-java-sdk/1061029).
9
10<!-- x-release-please-start-version -->
11
12[![Maven Central](https://img.shields.io/maven-central/v/com.openai/openai-java)](https://central.sonatype.com/artifact/com.openai/openai-java/0.13.0)
13[![javadoc](https://javadoc.io/badge2/com.openai/openai-java/0.13.0/javadoc.svg)](https://javadoc.io/doc/com.openai/openai-java/0.13.0)
14
15<!-- x-release-please-end -->
16
17The OpenAI Java SDK provides convenient access to the OpenAI REST API from applications written in Java. It includes helper classes with helpful types and documentation for every request and response property.
18
19## Documentation
20
21The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs).
22
23---
24
25## Getting started
26
27### Install dependencies
28
29#### Gradle
30
31<!-- x-release-please-start-version -->
32
33```kotlin
34implementation("com.openai:openai-java:0.13.0")
35```
36
37#### Maven
38
39```xml
40<dependency>
41 <groupId>com.openai</groupId>
42 <artifactId>openai-java</artifactId>
43 <version>0.13.0</version>
44</dependency>
45```
46
47<!-- x-release-please-end -->
48
49### Configure the client
50
51Use `OpenAIOkHttpClient.builder()` to configure the client. At a minimum you need to set `.apiKey()`:
52
53```java
54import com.openai.client.OpenAIClient;
55import com.openai.client.okhttp.OpenAIOkHttpClient;
56
57OpenAIClient client = OpenAIOkHttpClient.builder()
58 .apiKey("My API Key")
59 .build();
60```
61
62Alternately, set the environment with `OPENAI_API_KEY`, `OPENAI_ORG_ID` or `OPENAI_PROJECT_ID`, and use `OpenAIOkHttpClient.fromEnv()` to read from the environment.
63
64```java
65import com.openai.client.OpenAIClient;
66import com.openai.client.okhttp.OpenAIOkHttpClient;
67
68OpenAIClient client = OpenAIOkHttpClient.fromEnv();
69
70// Note: you can also call fromEnv() from the client builder, for example if you need to set additional properties
71OpenAIClient client = OpenAIOkHttpClient.builder()
72 .fromEnv()
73 // ... set properties on the builder
74 .build();
75```
76
77| Property | Environment variable | Required | Default value |
78| ------------ | -------------------- | -------- | ------------- |
79| apiKey | `OPENAI_API_KEY` | true | — |
80| organization | `OPENAI_ORG_ID` | false | — |
81| project | `OPENAI_PROJECT_ID` | false | — |
82
83Read the documentation for more configuration options.
84
85---
86
87### Example: creating a resource
88
89To create a new chat completion, first use the `ChatCompletionCreateParams` builder to specify attributes, then pass that to the `create` method of the `completions` service.
90
91```java
92import com.openai.models.ChatCompletion;
93import com.openai.models.ChatCompletionCreateParams;
94import com.openai.models.ChatCompletionUserMessageParam;
95import com.openai.models.ChatModel;
96
97ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
98 .addMessage(ChatCompletionUserMessageParam.builder()
99 .content("Say this is a test")
100 .build())
101 .model(ChatModel.O1)
102 .build();
103ChatCompletion chatCompletion = client.chat().completions().create(params);
104```
105
106### Example: listing resources
107
108The OpenAI API provides a `list` method to get a paginated list of jobs. You can retrieve the first page by:
109
110```java
111import com.openai.models.FineTuningJob;
112import com.openai.models.FineTuningJobListPage;
113
114FineTuningJobListPage page = client.fineTuning().jobs().list();
115for (FineTuningJob job : page.data()) {
116 System.out.println(job);
117}
118```
119
120Use the `FineTuningJobListParams` builder to set parameters:
121
122```java
123import com.openai.models.FineTuningJobListPage;
124import com.openai.models.FineTuningJobListParams;
125
126FineTuningJobListParams params = FineTuningJobListParams.builder()
127 .after("after")
128 .limit(20L)
129 .build();
130FineTuningJobListPage page1 = client.fineTuning().jobs().list(params);
131
132// Using the `from` method of the builder you can reuse previous params values:
133FineTuningJobListPage page2 = client.fineTuning().jobs().list(FineTuningJobListParams.builder()
134 .from(params)
135 .build());
136
137// Or easily get params for the next page by using the helper `getNextPageParams`:
138FineTuningJobListPage page3 = client.fineTuning().jobs().list(params.getNextPageParams(page2));
139```
140
141See [Pagination](#pagination) below for more information on transparently working with lists of objects without worrying about fetching each page.
142
143---
144
145## Requests
146
147### Parameters and bodies
148
149To make a request to the OpenAI API, you generally build an instance of the appropriate `Params` class.
150
151In [Example: creating a resource](#example-creating-a-resource) above, we used the `ChatCompletionCreateParams.builder()` to pass to the `create` method of the `completions` service.
152
153Sometimes, the API may support other properties that are not yet supported in the Java SDK types. In that case, you can attach them using the `putAdditionalProperty` method.
154
155```java
156import com.openai.core.JsonValue;
157import com.openai.models.ChatCompletionCreateParams;
158
159ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
160 // ... normal properties
161 .putAdditionalProperty("secret_param", JsonValue.from("4242"))
162 .build();
163```
164
165## Responses
166
167### Response validation
168
169When receiving a response, the OpenAI Java SDK will deserialize it into instances of the typed model classes. In rare cases, the API may return a response property that doesn't match the expected Java type. If you directly access the mistaken property, the SDK will throw an unchecked `OpenAIInvalidDataException` at runtime. If you would prefer to check in advance that that response is completely well-typed, call `.validate()` on the returned model.
170
171```java
172import com.openai.models.ChatCompletion;
173
174ChatCompletion chatCompletion = client.chat().completions().create().validate();
175```
176
177### Response properties as JSON
178
179In rare cases, you may want to access the underlying JSON value for a response property rather than using the typed version provided by this SDK. Each model property has a corresponding JSON version, with an underscore before the method name, which returns a `JsonField` value.
180
181```java
182import com.openai.core.JsonField;
183import java.util.Optional;
184
185JsonField field = responseObj._field();
186
187if (field.isMissing()) {
188 // Value was not specified in the JSON response
189} else if (field.isNull()) {
190 // Value was provided as a literal null
191} else {
192 // See if value was provided as a string
193 Optional<String> jsonString = field.asString();
194
195 // If the value given by the API did not match the shape that the SDK expects
196 // you can deserialise into a custom type
197 MyClass myObj = responseObj._field().asUnknown().orElseThrow().convert(MyClass.class);
198}
199```
200
201### Additional model properties
202
203Sometimes, the server response may include additional properties that are not yet available in this library's types. You can access them using the model's `_additionalProperties` method:
204
205```java
206import com.openai.core.JsonValue;
207
208JsonValue secret = errorObject._additionalProperties().get("secret_field");
209```
210
211---
212
213## Pagination
214
215For methods that return a paginated list of results, this library provides convenient ways access the results either one page at a time, or item-by-item across all pages.
216
217### Auto-pagination
218
219To iterate through all results across all pages, you can use `autoPager`, which automatically handles fetching more pages for you:
220
221### Synchronous
222
223```java
224import com.openai.models.FineTuningJob;
225import com.openai.models.FineTuningJobListPage;
226
227// As an Iterable:
228FineTuningJobListPage page = client.fineTuning().jobs().list(params);
229for (FineTuningJob job : page.autoPager()) {
230 System.out.println(job);
231};
232
233// As a Stream:
234client.fineTuning().jobs().list(params).autoPager().stream()
235 .limit(50)
236 .forEach(job -> System.out.println(job));
237```
238
239### Asynchronous
240
241```java
242// Using forEach, which returns CompletableFuture<Void>:
243asyncClient.fineTuning().jobs().list(params).autoPager()
244 .forEach(job -> System.out.println(job), executor);
245```
246
247### Manual pagination
248
249If none of the above helpers meet your needs, you can also manually request pages one-by-one. A page of results has a `data()` method to fetch the list of objects, as well as top-level `response` and other methods to fetch top-level data about the page. It also has methods `hasNextPage`, `getNextPage`, and `getNextPageParams` methods to help with pagination.
250
251```java
252import com.openai.models.FineTuningJob;
253import com.openai.models.FineTuningJobListPage;
254
255FineTuningJobListPage page = client.fineTuning().jobs().list(params);
256while (page != null) {
257 for (FineTuningJob job : page.data()) {
258 System.out.println(job);
259 }
260
261 page = page.getNextPage().orElse(null);
262}
263```
264
265---
266
267## Error handling
268
269This library throws exceptions in a single hierarchy for easy handling:
270
271- **`OpenAIException`** - Base exception for all exceptions
272
273- **`OpenAIServiceException`** - HTTP errors with a well-formed response body we were able to parse. The exception message and the `.debuggingRequestId()` will be set by the server.
274
275 | 400 | BadRequestException |
276 | ------ | ----------------------------- |
277 | 401 | AuthenticationException |
278 | 403 | PermissionDeniedException |
279 | 404 | NotFoundException |
280 | 422 | UnprocessableEntityException |
281 | 429 | RateLimitException |
282 | 5xx | InternalServerException |
283 | others | UnexpectedStatusCodeException |
284
285- **`OpenAIIoException`** - I/O networking errors
286- **`OpenAIInvalidDataException`** - any other exceptions on the client side, e.g.:
287 - We failed to serialize the request body
288 - We failed to parse the response body (has access to response code and body)
289
290## Microsoft Azure OpenAI
291
292To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the same
293OpenAI client builder but with the Azure-specific configuration.
294
295```java
296OpenAIOkHttpClient.Builder clientBuilder = OpenAIOkHttpClient.builder();
297
298/* Azure-specific code starts here */
299// You can either set 'endpoint' directly in the builder.
300// or set the env var "AZURE_OPENAI_ENDPOINT" and use fromEnv() method instead
301clientBuilder
302 .baseUrl(System.getenv("AZURE_OPENAI_ENDPOINT"))
303 .credential(BearerTokenCredential.create(
304 AuthenticationUtil.getBearerTokenSupplier(
305 new DefaultAzureCredentialBuilder().build(), "https://cognitiveservices.azure.com/.default")
306 ));
307/* Azure-specific code ends here */
308
309OpenAIClient client = clientBuilder.build();
310
311ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
312 .addMessage(ChatCompletionMessageParam.ofChatCompletionUserMessageParam(
313 ChatCompletionUserMessageParam.builder()
314 .content(ChatCompletionUserMessageParam.Content.ofTextContent("Who won the world series in 2020?"))
315 .build()))
316 .model("gpt-4o")
317 .build();
318
319ChatCompletion chatCompletion = client.chat().completions().create(params);
320
321List<ChatCompletion.Choice> choices = chatCompletion.choices();
322for (ChatCompletion.Choice choice : choices) {
323 System.out.println("Choice content: " + choice.message().content().get());
324}
325```
326
327See the complete Azure OpenAI examples in the [Azure OpenAI example](https://github.com/openai/openai-java/tree/next/openai-azure-java-example/src/main/java/com.openai.azure.examples).
328
329## Network options
330
331### Retries
332
333Requests that experience certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors will all be retried by default. You can provide a `maxRetries` on the client builder to configure this:
334
335```java
336import com.openai.client.OpenAIClient;
337import com.openai.client.okhttp.OpenAIOkHttpClient;
338
339OpenAIClient client = OpenAIOkHttpClient.builder()
340 .fromEnv()
341 .maxRetries(4)
342 .build();
343```
344
345### Timeouts
346
347Requests time out after 10 minutes by default. You can configure this on the client builder:
348
349```java
350import com.openai.client.OpenAIClient;
351import com.openai.client.okhttp.OpenAIOkHttpClient;
352import java.time.Duration;
353
354OpenAIClient client = OpenAIOkHttpClient.builder()
355 .fromEnv()
356 .timeout(Duration.ofSeconds(30))
357 .build();
358```
359
360### Proxies
361
362Requests can be routed through a proxy. You can configure this on the client builder:
363
364```java
365import com.openai.client.OpenAIClient;
366import com.openai.client.okhttp.OpenAIOkHttpClient;
367import java.net.InetSocketAddress;
368import java.net.Proxy;
369
370OpenAIClient client = OpenAIOkHttpClient.builder()
371 .fromEnv()
372 .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("example.com", 8080)))
373 .build();
374```
375
376## Making custom/undocumented requests
377
378This library is typed for convenient access to the documented API. If you need to access undocumented params or response properties, the library can still be used.
379
380### Undocumented request params
381
382To make requests using undocumented parameters, you can provide or override parameters on the params object while building it.
383
384```java
385FooCreateParams address = FooCreateParams.builder()
386 .id("my_id")
387 .putAdditionalProperty("secret_prop", JsonValue.from("hello"))
388 .build();
389```
390
391### Undocumented response properties
392
393To access undocumented response properties, you can use `res._additionalProperties()` on a response object to get a map of untyped fields of type `Map<String, JsonValue>`. You can then access fields like `._additionalProperties().get("secret_prop").asString()` or use other helpers defined on the `JsonValue` class to extract it to a desired type.
394
395## Logging
396
397We use the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor).
398
399You can enable logging by setting the environment variable `OPENAI_LOG` to `info`.
400
401```sh
402$ export OPENAI_LOG=info
403```
404
405Or to `debug` for more verbose logging.
406
407```sh
408$ export OPENAI_LOG=debug
409```
410
411## Semantic versioning
412
413This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
414
4151. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_
4162. Changes that we do not expect to impact the vast majority of users in practice.
417
418We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
419
420We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-java/issues) with questions, bugs, or suggestions.
421
422## Requirements
423
424This library requires Java 8 or later.
425