openai/openai-java

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
71cf8abd87f4e7ea4ab658d813499f3e30aee632

Branches

Tags

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

Clone

HTTPS

Download ZIP

README.md

1669lines · modecode

1# OpenAI Java API Library
2
3<!-- x-release-please-start-version -->
4
5[![Maven Central](https://img.shields.io/maven-central/v/com.openai/openai-java)](https://central.sonatype.com/artifact/com.openai/openai-java/2.16.0)
6[![javadoc](https://javadoc.io/badge2/com.openai/openai-java/2.16.0/javadoc.svg)](https://javadoc.io/doc/com.openai/openai-java/2.16.0)
7
8<!-- x-release-please-end -->
9
10The OpenAI Java SDK provides convenient access to the [OpenAI REST API](https://platform.openai.com/docs) from applications written in Java.
11
12<!-- x-release-please-start-version -->
13
14The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.openai/openai-java/2.16.0).
15
16<!-- x-release-please-end -->
17
18## Installation
19
20<!-- x-release-please-start-version -->
21
22### Gradle
23
24```kotlin
25implementation("com.openai:openai-java:2.16.0")
26```
27
28### Maven
29
30```xml
31<dependency>
32 <groupId>com.openai</groupId>
33 <artifactId>openai-java</artifactId>
34 <version>2.16.0</version>
35</dependency>
36```
37
38<!-- x-release-please-end -->
39
40## Requirements
41
42This library requires Java 8 or later.
43
44## Usage
45
46See the [`openai-java-example`](openai-java-example/src/main/java/com/openai/example) directory for complete and runnable examples.
47
48The primary API for interacting with OpenAI models is the [Responses API](https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below.
49
50```java
51import com.openai.client.OpenAIClient;
52import com.openai.client.okhttp.OpenAIOkHttpClient;
53import com.openai.models.ChatModel;
54import com.openai.models.responses.Response;
55import com.openai.models.responses.ResponseCreateParams;
56
57// Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID` and `OPENAI_PROJECT_ID` environment variables
58OpenAIClient client = OpenAIOkHttpClient.fromEnv();
59
60ResponseCreateParams params = ResponseCreateParams.builder()
61 .input("Say this is a test")
62 .model(ChatModel.GPT_4_1)
63 .build();
64Response response = client.responses().create(params);
65```
66
67The previous standard (supported indefinitely) for generating text is the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below.
68
69```java
70import com.openai.client.OpenAIClient;
71import com.openai.client.okhttp.OpenAIOkHttpClient;
72import com.openai.models.ChatModel;
73import com.openai.models.chat.completions.ChatCompletion;
74import com.openai.models.chat.completions.ChatCompletionCreateParams;
75
76// Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
77OpenAIClient client = OpenAIOkHttpClient.fromEnv();
78
79ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
80 .addUserMessage("Say this is a test")
81 .model(ChatModel.GPT_4_1)
82 .build();
83ChatCompletion chatCompletion = client.chat().completions().create(params);
84```
85
86## Client configuration
87
88Configure the client using environment variables:
89
90```java
91import com.openai.client.OpenAIClient;
92import com.openai.client.okhttp.OpenAIOkHttpClient;
93
94// Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
95OpenAIClient client = OpenAIOkHttpClient.fromEnv();
96```
97
98Or manually:
99
100```java
101import com.openai.client.OpenAIClient;
102import com.openai.client.okhttp.OpenAIOkHttpClient;
103
104OpenAIClient client = OpenAIOkHttpClient.builder()
105 .apiKey("My API Key")
106 .build();
107```
108
109Or using a combination of the two approaches:
110
111```java
112import com.openai.client.OpenAIClient;
113import com.openai.client.okhttp.OpenAIOkHttpClient;
114
115OpenAIClient client = OpenAIOkHttpClient.builder()
116 // Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
117 .fromEnv()
118 .apiKey("My API Key")
119 .build();
120```
121
122See this table for the available options:
123
124| Setter | Environment variable | Required | Default value |
125| --------------- | ----------------------- | -------- | ----------------------------- |
126| `apiKey` | `OPENAI_API_KEY` | true | - |
127| `organization` | `OPENAI_ORG_ID` | false | - |
128| `project` | `OPENAI_PROJECT_ID` | false | - |
129| `webhookSecret` | `OPENAI_WEBHOOK_SECRET` | false | - |
130| `baseUrl` | `OPENAI_BASE_URL` | true | `"https://api.openai.com/v1"` |
131
132> [!TIP]
133> Don't create more than one client in the same application. Each client has a connection pool and
134> thread pools, which are more efficient to share between requests.
135
136### Modifying configuration
137
138To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `withOptions()` on any client or service:
139
140```java
141import com.openai.client.OpenAIClient;
142
143OpenAIClient clientWithOptions = client.withOptions(optionsBuilder -> {
144 optionsBuilder.baseUrl("https://example.com");
145 optionsBuilder.maxRetries(42);
146});
147```
148
149The `withOptions()` method does not affect the original client or service.
150
151## Requests and responses
152
153To send a request to the OpenAI API, build an instance of some `Params` class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.
154
155For example, `client.chat().completions().create(...)` should be called with an instance of `ChatCompletionCreateParams`, and it will return an instance of `ChatCompletion`.
156
157## Immutability
158
159Each class in the SDK has an associated [builder](https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java) or factory method for constructing it.
160
161Each class is [immutable](https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html) once constructed. If the class has an associated builder, then it has a `toBuilder()` method, which can be used to convert it back to a builder for making a modified copy.
162
163Because each class is immutable, builder modification will _never_ affect already built class instances.
164
165## Asynchronous execution
166
167The default client is synchronous. To switch to asynchronous execution, call the `async()` method:
168
169```java
170import com.openai.client.OpenAIClient;
171import com.openai.client.okhttp.OpenAIOkHttpClient;
172import com.openai.models.ChatModel;
173import com.openai.models.chat.completions.ChatCompletion;
174import com.openai.models.chat.completions.ChatCompletionCreateParams;
175import java.util.concurrent.CompletableFuture;
176
177// Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
178OpenAIClient client = OpenAIOkHttpClient.fromEnv();
179
180ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
181 .addUserMessage("Say this is a test")
182 .model(ChatModel.GPT_4_1)
183 .build();
184CompletableFuture<ChatCompletion> chatCompletion = client.async().chat().completions().create(params);
185```
186
187Or create an asynchronous client from the beginning:
188
189```java
190import com.openai.client.OpenAIClientAsync;
191import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
192import com.openai.models.ChatModel;
193import com.openai.models.chat.completions.ChatCompletion;
194import com.openai.models.chat.completions.ChatCompletionCreateParams;
195import java.util.concurrent.CompletableFuture;
196
197// Configures using the `OPENAI_API_KEY`, `OPENAI_ORG_ID`, `OPENAI_PROJECT_ID`, `OPENAI_WEBHOOK_SECRET` and `OPENAI_BASE_URL` environment variables
198OpenAIClientAsync client = OpenAIOkHttpClientAsync.fromEnv();
199
200ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
201 .addUserMessage("Say this is a test")
202 .model(ChatModel.GPT_4_1)
203 .build();
204CompletableFuture<ChatCompletion> chatCompletion = client.chat().completions().create(params);
205```
206
207The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.
208
209## Streaming
210
211The SDK defines methods that return response "chunk" streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response. Streaming methods generally correspond to [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) or [JSONL](https://jsonlines.org) responses.
212
213Some of these methods may have streaming and non-streaming variants, but a streaming method will always have a `Streaming` suffix in its name, even if it doesn't have a non-streaming variant.
214
215These streaming methods return [`StreamResponse`](openai-java-core/src/main/kotlin/com/openai/core/http/StreamResponse.kt) for synchronous clients:
216
217```java
218import com.openai.core.http.StreamResponse;
219import com.openai.models.chat.completions.ChatCompletionChunk;
220
221try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(params)) {
222 streamResponse.stream().forEach(chunk -> {
223 System.out.println(chunk);
224 });
225 System.out.println("No more chunks!");
226}
227```
228
229Or [`AsyncStreamResponse`](openai-java-core/src/main/kotlin/com/openai/core/http/AsyncStreamResponse.kt) for asynchronous clients:
230
231```java
232import com.openai.core.http.AsyncStreamResponse;
233import com.openai.models.chat.completions.ChatCompletionChunk;
234import java.util.Optional;
235
236client.async().chat().completions().createStreaming(params).subscribe(chunk -> {
237 System.out.println(chunk);
238});
239
240// If you need to handle errors or completion of the stream
241client.async().chat().completions().createStreaming(params).subscribe(new AsyncStreamResponse.Handler<>() {
242 @Override
243 public void onNext(ChatCompletionChunk chunk) {
244 System.out.println(chunk);
245 }
246
247 @Override
248 public void onComplete(Optional<Throwable> error) {
249 if (error.isPresent()) {
250 System.out.println("Something went wrong!");
251 throw new RuntimeException(error.get());
252 } else {
253 System.out.println("No more chunks!");
254 }
255 }
256});
257
258// Or use futures
259client.async().chat().completions().createStreaming(params)
260 .subscribe(chunk -> {
261 System.out.println(chunk);
262 })
263 .onCompleteFuture();
264 .whenComplete((unused, error) -> {
265 if (error != null) {
266 System.out.println("Something went wrong!");
267 throw new RuntimeException(error);
268 } else {
269 System.out.println("No more chunks!");
270 }
271 });
272```
273
274Async streaming uses a dedicated per-client cached thread pool [`Executor`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html) to stream without blocking the current thread. This default is suitable for most purposes.
275
276To use a different `Executor`, configure the subscription using the `executor` parameter:
277
278```java
279import java.util.concurrent.Executor;
280import java.util.concurrent.Executors;
281
282Executor executor = Executors.newFixedThreadPool(4);
283client.async().chat().completions().createStreaming(params).subscribe(
284 chunk -> System.out.println(chunk), executor
285);
286```
287
288Or configure the client globally using the `streamHandlerExecutor` method:
289
290```java
291import com.openai.client.OpenAIClient;
292import com.openai.client.okhttp.OpenAIOkHttpClient;
293import java.util.concurrent.Executors;
294
295OpenAIClient client = OpenAIOkHttpClient.builder()
296 .fromEnv()
297 .streamHandlerExecutor(Executors.newFixedThreadPool(4))
298 .build();
299```
300
301### Streaming helpers
302
303The SDK provides conveniences for streamed chat completions. A
304[`ChatCompletionAccumulator`](openai-java-core/src/main/kotlin/com/openai/helpers/ChatCompletionAccumulator.kt)
305can record the stream of chat completion chunks in the response as they are processed and accumulate
306a [`ChatCompletion`](openai-java-core/src/main/kotlin/com/openai/models/chat/completions/ChatCompletion.kt)
307object similar to that which would have been returned by the non-streaming API.
308
309For a synchronous response add a
310[`Stream.peek()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#peek-java.util.function.Consumer-)
311call to the stream pipeline to accumulate each chunk:
312
313```java
314import com.openai.core.http.StreamResponse;
315import com.openai.helpers.ChatCompletionAccumulator;
316import com.openai.models.chat.completions.ChatCompletion;
317import com.openai.models.chat.completions.ChatCompletionChunk;
318
319ChatCompletionAccumulator chatCompletionAccumulator = ChatCompletionAccumulator.create();
320
321try (StreamResponse<ChatCompletionChunk> streamResponse =
322 client.chat().completions().createStreaming(createParams)) {
323 streamResponse.stream()
324 .peek(chatCompletionAccumulator::accumulate)
325 .flatMap(completion -> completion.choices().stream())
326 .flatMap(choice -> choice.delta().content().stream())
327 .forEach(System.out::print);
328}
329
330ChatCompletion chatCompletion = chatCompletionAccumulator.chatCompletion();
331```
332
333For an asynchronous response, add the `ChatCompletionAccumulator` to the `subscribe()` call:
334
335```java
336import com.openai.helpers.ChatCompletionAccumulator;
337import com.openai.models.chat.completions.ChatCompletion;
338
339ChatCompletionAccumulator chatCompletionAccumulator = ChatCompletionAccumulator.create();
340
341client.chat()
342 .completions()
343 .createStreaming(createParams)
344 .subscribe(chunk -> chatCompletionAccumulator.accumulate(chunk).choices().stream()
345 .flatMap(choice -> choice.delta().content().stream())
346 .forEach(System.out::print))
347 .onCompleteFuture()
348 .join();
349
350ChatCompletion chatCompletion = chatCompletionAccumulator.chatCompletion();
351```
352
353The SDK provides conveniences for streamed responses. A
354[`ResponseAccumulator`](openai-java-core/src/main/kotlin/com/openai/helpers/ResponseAccumulator.kt)
355can record the stream of response events as they are processed and accumulate a
356[`Response`](openai-java-core/src/main/kotlin/com/openai/models/responses/Response.kt)
357object similar to that which would have been returned by the non-streaming API.
358
359For a synchronous response add a
360[`Stream.peek()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#peek-java.util.function.Consumer-)
361call to the stream pipeline to accumulate each event:
362
363```java
364import com.openai.core.http.StreamResponse;
365import com.openai.helpers.ResponseAccumulator;
366import com.openai.models.responses.Response;
367import com.openai.models.responses.ResponseStreamEvent;
368
369ResponseAccumulator responseAccumulator = ResponseAccumulator.create();
370
371try (StreamResponse<ResponseStreamEvent> streamResponse =
372 client.responses().createStreaming(createParams)) {
373 streamResponse.stream()
374 .peek(responseAccumulator::accumulate)
375 .flatMap(event -> event.outputTextDelta().stream())
376 .forEach(textEvent -> System.out.print(textEvent.delta()));
377}
378
379Response response = responseAccumulator.response();
380```
381
382For an asynchronous response, add the `ResponseAccumulator` to the `subscribe()` call:
383
384```java
385import com.openai.helpers.ResponseAccumulator;
386import com.openai.models.responses.Response;
387
388ResponseAccumulator responseAccumulator = ResponseAccumulator.create();
389
390client.responses()
391 .createStreaming(createParams)
392 .subscribe(event -> responseAccumulator.accumulate(event)
393 .outputTextDelta().ifPresent(textEvent -> System.out.print(textEvent.delta())))
394 .onCompleteFuture()
395 .join();
396
397Response response = responseAccumulator.response();
398```
399
400## Structured outputs with JSON schemas
401
402Open AI [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs?api-mode=chat)
403is a feature that ensures that the model will always generate responses that adhere to a supplied
404[JSON schema](https://json-schema.org/overview/what-is-jsonschema).
405
406A JSON schema can be defined by creating a
407[`ResponseFormatJsonSchema`](openai-java-core/src/main/kotlin/com/openai/models/ResponseFormatJsonSchema.kt)
408and setting it on the input parameters. However, for greater convenience, a JSON schema can instead
409be derived automatically from the structure of an arbitrary Java class. The JSON content from the
410response will then be converted automatically to an instance of that Java class. A full, working
411example of the use of Structured Outputs with arbitrary Java classes can be seen in
412[`StructuredOutputsExample`](openai-java-example/src/main/java/com/openai/example/StructuredOutputsExample.java).
413
414Java classes can contain fields declared to be instances of other classes and can use collections
415(see [Defining JSON schema properties](#defining-json-schema-properties) for more details):
416
417```java
418class Person {
419 public String name;
420 public int birthYear;
421}
422
423class Book {
424 public String title;
425 public Person author;
426 public int publicationYear;
427}
428
429class BookList {
430 public List<Book> books;
431}
432```
433
434Pass the top-level class—`BookList` in this example—to `responseFormat(Class<T>)` when building the
435parameters and then access an instance of `BookList` from the generated message content in the
436response:
437
438```java
439import com.openai.models.ChatModel;
440import com.openai.models.chat.completions.ChatCompletionCreateParams;
441import com.openai.models.chat.completions.StructuredChatCompletionCreateParams;
442
443StructuredChatCompletionCreateParams<BookList> params = ChatCompletionCreateParams.builder()
444 .addUserMessage("List some famous late twentieth century novels.")
445 .model(ChatModel.GPT_4_1)
446 .responseFormat(BookList.class)
447 .build();
448
449client.chat().completions().create(params).choices().stream()
450 .flatMap(choice -> choice.message().content().stream())
451 .flatMap(bookList -> bookList.books.stream())
452 .forEach(book -> System.out.println(book.title + " by " + book.author.name));
453```
454
455You can start building the parameters with an instance of
456[`ChatCompletionCreateParams.Builder`](openai-java-core/src/main/kotlin/com/openai/models/chat/completions/ChatCompletionCreateParams.kt)
457or
458[`StructuredChatCompletionCreateParams.Builder`](openai-java-core/src/main/kotlin/com/openai/models/chat/completions/StructuredChatCompletionCreateParams.kt).
459If you start with the former (which allows for more compact code) the builder type will change to
460the latter when `ChatCompletionCreateParams.Builder.responseFormat(Class<T>)` is called.
461
462If a field in a class is optional and does not require a defined value, you can represent this using
463the [`java.util.Optional`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) class.
464It is up to the AI model to decide whether to provide a value for that field or leave it empty.
465
466```java
467import java.util.Optional;
468
469class Book {
470 public String title;
471 public Person author;
472 public int publicationYear;
473 public Optional<String> isbn;
474}
475```
476
477Generic type information for fields is retained in the class's metadata, but _generic type erasure_
478applies in other scopes. While, for example, a JSON schema defining an array of books can be derived
479from the `BookList.books` field with type `List<Book>`, a valid JSON schema cannot be derived from a
480local variable of that same type, so the following will _not_ work:
481
482```java
483List<Book> books = new ArrayList<>();
484
485StructuredChatCompletionCreateParams<List<Book>> params = ChatCompletionCreateParams.builder()
486 .responseFormat(books.getClass())
487 // ...
488 .build();
489```
490
491If an error occurs while converting a JSON response to an instance of a Java class, the error
492message will include the JSON response to assist in diagnosis. For instance, if the response is
493truncated, the JSON data will be incomplete and cannot be converted to a class instance. If your
494JSON response may contain sensitive information, avoid logging it directly, or ensure that you
495redact any sensitive details from the error message.
496
497### Local JSON schema validation
498
499Structured Outputs supports a
500[subset](https://platform.openai.com/docs/guides/structured-outputs#supported-schemas) of the JSON
501Schema language. Schemas are generated automatically from classes to align with this subset.
502However, due to the inherent structure of the classes, the generated schema may still violate
503certain OpenAI schema restrictions, such as exceeding the maximum nesting depth or utilizing
504unsupported data types.
505
506To facilitate compliance, the method `responseFormat(Class<T>)` performs a validation check on the
507schema derived from the specified class. This validation ensures that all restrictions are adhered
508to. If any issues are detected, an exception will be thrown, providing a detailed message outlining
509the reasons for the validation failure.
510
511- **Local Validation**: The validation process occurs locally, meaning no requests are sent to the
512 remote AI model. If the schema passes local validation, it is likely to pass remote validation as
513 well.
514- **Remote Validation**: The remote AI model will conduct its own validation upon receiving the JSON
515 schema in the request.
516- **Version Compatibility**: There may be instances where local validation fails while remote
517 validation succeeds. This can occur if the SDK version is outdated compared to the restrictions
518 enforced by the remote AI model.
519- **Disabling Local Validation**: If you encounter compatibility issues and wish to bypass local
520 validation, you can disable it by passing
521 [`JsonSchemaLocalValidation.NO`](openai-java-core/src/main/kotlin/com/openai/core/JsonSchemaLocalValidation.kt)
522 to the `responseFormat(Class<T>, JsonSchemaLocalValidation)` method when building the parameters.
523 (The default value for this parameter is `JsonSchemaLocalValidation.YES`.)
524
525```java
526import com.openai.core.JsonSchemaLocalValidation;
527import com.openai.models.ChatModel;
528import com.openai.models.chat.completions.ChatCompletionCreateParams;
529import com.openai.models.chat.completions.StructuredChatCompletionCreateParams;
530
531StructuredChatCompletionCreateParams<BookList> params = ChatCompletionCreateParams.builder()
532 .addUserMessage("List some famous late twentieth century novels.")
533 .model(ChatModel.GPT_4_1)
534 .responseFormat(BookList.class, JsonSchemaLocalValidation.NO)
535 .build();
536```
537
538By following these guidelines, you can ensure that your structured outputs conform to the necessary
539schema requirements and minimize the risk of remote validation errors.
540
541### Usage with the Responses API
542
543_Structured Outputs_ are also supported for the Responses API. The usage is the same as described
544except where the Responses API differs slightly from the Chat Completions API. Pass the top-level
545class to `text(Class<T>)` when building the parameters and then access an instance of the class from
546the generated message content in the response.
547
548You can start building the parameters with an instance of
549[`ResponseCreateParams.Builder`](openai-java-core/src/main/kotlin/com/openai/models/responses/ResponseCreateParams.kt)
550or
551[`StructuredResponseCreateParams.Builder`](openai-java-core/src/main/kotlin/com/openai/models/responses/StructuredResponseCreateParams.kt).
552If you start with the former (which allows for more compact code) the builder type will change to
553the latter when `ResponseCreateParams.Builder.text(Class<T>)` is called.
554
555For a full example of the usage of _Structured Outputs_ with the Responses API, see
556[`ResponsesStructuredOutputsExample`](openai-java-example/src/main/java/com/openai/example/ResponsesStructuredOutputsExample.java).
557
558### Usage with streaming
559
560_Structured Outputs_ can also be used with [Streaming](#streaming) and the Chat Completions API. As
561responses are returned in "chunks", the full response must first be accumulated to concatenate the
562JSON strings that can then be converted into instances of the arbitrary Java class. Normal streaming
563operations can be performed while accumulating the JSON strings.
564
565Use the [`ChatCompletionAccumulator`](openai-java-core/src/main/kotlin/com/openai/helpers/ChatCompletionAccumulator.kt)
566as described in the section on [Streaming helpers](#streaming-helpers) to accumulate the JSON
567strings. Once accumulated, use `ChatCompletionAccumulator.chatCompletion(Class<T>)` to convert the
568accumulated `ChatCompletion` into a
569[`StructuredChatCompletion`](openai-java-core/src/main/kotlin/com/openai/models/chat/completions/StructuredChatCompletion.kt).
570The `StructuredChatCompletion` can then automatically deserialize the JSON strings into instances of
571your Java class.
572
573For a full example of the usage of _Structured Outputs_ with Streaming and the Chat Completions API,
574see
575[`StructuredOutputsStreamingExample`](openai-java-example/src/main/java/com/openai/example/StructuredOutputsStreamingExample.java).
576
577With the Responses API, accumulate events while streaming using the
578[`ResponseAccumulator`](openai-java-core/src/main/kotlin/com/openai/helpers/ResponseAccumulator.kt).
579Once accumulated, use `ResponseAccumulator.response(Class<T>)` to convert the accumulated `Response`
580into a
581[`StructuredResponse`](openai-java-core/src/main/kotlin/com/openai/models/responses/StructuredResponse.kt).
582The [`StructuredResponse`] can then automatically deserialize the JSON strings into instances of
583your Java class.
584
585For a full example of the usage of _Structured Outputs_ with Streaming and the Responses API, see
586[`ResponsesStructuredOutputsStreamingExample`](openai-java-example/src/main/java/com/openai/example/ResponsesStructuredOutputsStreamingExample.java).
587
588### Defining JSON schema properties
589
590When a JSON schema is derived from your Java classes, all properties represented by `public` fields
591or `public` getter methods are included in the schema by default. Non-`public` fields and getter
592methods are _not_ included by default. You can exclude `public`, or include non-`public` fields or
593getter methods, by using the `@JsonIgnore` or `@JsonProperty` annotations respectively (see
594[Annotating classes and JSON schemas](#annotating-classes-and-json-schemas) for details).
595
596If you do not want to define `public` fields, you can define `private` fields and corresponding
597`public` getter methods. For example, a `private` field `myValue` with a `public` getter method
598`getMyValue()` will result in a `"myValue"` property being included in the JSON schema. If you
599prefer not to use the conventional Java "get" prefix for the name of the getter method, then you
600_must_ annotate the getter method with the `@JsonProperty` annotation and the full method name will
601be used as the property name. You do not have to define any corresponding setter methods if you do
602not need them.
603
604Each of your classes _must_ define at least one property to be included in the JSON schema. A
605validation error will occur if any class contains no fields or getter methods from which schema
606properties can be derived. This may occur if, for example:
607
608- There are no fields or getter methods in the class.
609- All fields and getter methods are `public`, but all are annotated with `@JsonIgnore`.
610- All fields and getter methods are non-`public`, but none are annotated with `@JsonProperty`.
611- A field or getter method is declared with a `Map` type. A `Map` is treated like a separate class
612 with no named properties, so it will result in an empty `"properties"` field in the JSON schema.
613
614### Annotating classes and JSON schemas
615
616You can use annotations to add further information to the JSON schema derived from your Java
617classes, or to control which fields or getter methods will be included in the schema. Details from
618annotations captured in the JSON schema may be used by the AI model to improve its response. The SDK
619supports the use of [Jackson Databind](https://github.com/FasterXML/jackson-databind) annotations.
620
621```java
622import com.fasterxml.jackson.annotation.JsonClassDescription;
623import com.fasterxml.jackson.annotation.JsonIgnore;
624import com.fasterxml.jackson.annotation.JsonPropertyDescription;
625
626class Person {
627 @JsonPropertyDescription("The first name and surname of the person")
628 public String name;
629 public int birthYear;
630 @JsonPropertyDescription("The year the person died, or 'present' if the person is living.")
631 public String deathYear;
632}
633
634@JsonClassDescription("The details of one published book")
635class Book {
636 public String title;
637 public Person author;
638 @JsonPropertyDescription("The year in which the book was first published.")
639 public int publicationYear;
640 @JsonIgnore public String genre;
641}
642
643class BookList {
644 public List<Book> books;
645}
646```
647
648- Use `@JsonClassDescription` to add a detailed description to a class.
649- Use `@JsonPropertyDescription` to add a detailed description to a field or getter method of a
650 class.
651- Use `@JsonIgnore` to exclude a `public` field or getter method of a class from the generated JSON
652 schema.
653- Use `@JsonProperty` to include a non-`public` field or getter method of a class in the generated
654 JSON schema.
655
656If you use `@JsonProperty(required = false)`, the `false` value will be ignored. OpenAI JSON schemas
657must mark all properties as _required_, so the schema generated from your Java classes will respect
658that restriction and ignore any annotation that would violate it.
659
660You can also use [OpenAPI Swagger 2](https://swagger.io/specification/v2/)
661[`@Schema`](https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#schema) and
662[`@ArraySchema`](https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations#arrayschema)
663annotations. These allow type-specific constraints to be added to your schema properties. You can
664learn more about the supported constraints in the OpenAI documentation on
665[Supported properties](https://platform.openai.com/docs/guides/structured-outputs#supported-properties).
666
667```java
668import io.swagger.v3.oas.annotations.media.Schema;
669import io.swagger.v3.oas.annotations.media.ArraySchema;
670
671class Article {
672 @ArraySchema(minItems = 1, maxItems = 10)
673 public List<String> authors;
674
675 @Schema(pattern = "^[A-Za-z ]+$")
676 public String title;
677
678 @Schema(format = "date")
679 public String publicationDate;
680
681 @Schema(minimum = "1")
682 public int pageCount;
683}
684```
685
686Local validation will check that you have not used any unsupported constraint keywords. However, the
687values of the constraints are _not_ validated locally. For example, if you use a value for the
688`"format"` constraint of a string property that is not in the list of
689[supported format names](https://platform.openai.com/docs/guides/structured-outputs#supported-properties),
690then local validation will pass, but the AI model may report an error.
691
692If you use both Jackson and Swagger annotations to set the same schema field, the Jackson annotation
693will take precedence. In the following example, the description of `myProperty` will be set to
694"Jackson description"; "Swagger description" will be ignored:
695
696```java
697import com.fasterxml.jackson.annotation.JsonPropertyDescription;
698import io.swagger.v3.oas.annotations.media.Schema;
699
700class MyObject {
701 @Schema(description = "Swagger description")
702 @JsonPropertyDescription("Jackson description")
703 public String myProperty;
704}
705```
706
707## Function calling with JSON schemas
708
709OpenAI [Function Calling](https://platform.openai.com/docs/guides/function-calling?api-mode=chat)
710lets you integrate external functions directly into the language model's responses. Instead of
711producing plain text, the model can output instructions (with parameters) for calling a function
712when appropriate. You define a [JSON schema](https://json-schema.org/overview/what-is-jsonschema)
713for functions, and the model uses it to decide when and how to trigger these calls, enabling more
714interactive, data-driven applications.
715
716A JSON schema describing a function's parameters can be defined via the API by building a
717[`ChatCompletionTool`](openai-java-core/src/main/kotlin/com/openai/models/chat/completions/ChatCompletionTool.kt)
718containing a
719[`FunctionDefinition`](openai-java-core/src/main/kotlin/com/openai/models/FunctionDefinition.kt)
720and then using `addTool` to set it on the input parameters. The response from the AI model may then
721contain requests to call your functions, detailing the functions' names and their parameter values
722as JSON data that conforms to the JSON schema from the function definition. You can then parse the
723parameter values from this JSON, invoke your functions, and pass your functions' results back to the
724AI model. A full, working example of _Function Calling_ using the low-level API can be seen in
725[`FunctionCallingRawExample`](openai-java-example/src/main/java/com/openai/example/FunctionCallingRawExample.java).
726
727However, for greater convenience, the SDK can derive a function and its parameters automatically
728from the structure of an arbitrary Java class: the class's name provides the function name, and the
729class's fields define the function's parameters. When the AI model responds with the parameter
730values in JSON form, you can then easily convert that JSON to an instance of your Java class and
731use the parameter values to invoke your custom function. A full, working example of the use of
732_Function Calling_ with Java classes to define function parameters can be seen in
733[`FunctionCallingExample`](openai-java-example/src/main/java/com/openai/example/FunctionCallingExample.java).
734
735Like for [Structured Outputs](#structured-outputs-with-json-schemas), Java classes can contain
736fields declared to be instances of other classes and can use collections (see
737[Defining JSON schema properties](#defining-json-schema-properties) for more details). Optionally,
738annotations can be used to set the descriptions of the function (class) and its parameters (fields)
739to assist the AI model in understanding the purpose of the function and the possible values of its
740parameters.
741
742```java
743import com.fasterxml.jackson.annotation.JsonClassDescription;
744import com.fasterxml.jackson.annotation.JsonPropertyDescription;
745
746@JsonClassDescription("Gets the quality of the given SDK.")
747static class GetSdkQuality {
748 @JsonPropertyDescription("The name of the SDK.")
749 public String name;
750
751 public SdkQuality execute() {
752 return new SdkQuality(
753 name, name.contains("OpenAI") ? "It's robust and polished!" : "*shrug*");
754 }
755}
756
757static class SdkQuality {
758 public String quality;
759
760 public SdkQuality(String name, String evaluation) {
761 quality = name + ": " + evaluation;
762 }
763}
764
765@JsonClassDescription("Gets the review score (out of 10) for the named SDK.")
766static class GetSdkScore {
767 public String name;
768
769 public int execute() {
770 return name.contains("OpenAI") ? 10 : 3;
771 }
772}
773```
774
775When your functions are defined, add them to the input parameters using `addTool(Class<T>)` and then
776call them if requested to do so in the AI model's response. `Function.argments(Class<T>)` can be
777used to parse a function's parameters in JSON form to an instance of your function-defining class.
778The fields of that instance will be set to the values of the parameters to the function call.
779
780After calling the function, use `ChatCompletionToolMessageParam.Builder.contentAsJson(Object)` to
781pass the function's result back to the AI model. The method will convert the result to JSON form
782for consumption by the model. The `Object` can be any object, including simple `String` instances
783and boxed primitive types.
784
785```java
786import com.openai.client.OpenAIClient;
787import com.openai.client.okhttp.OpenAIOkHttpClient;
788import com.openai.models.ChatModel;
789import com.openai.models.chat.completions.*;
790import java.util.Collection;
791
792OpenAIClient client = OpenAIOkHttpClient.fromEnv();
793
794ChatCompletionCreateParams.Builder createParamsBuilder = ChatCompletionCreateParams.builder()
795 .model(ChatModel.GPT_3_5_TURBO)
796 .maxCompletionTokens(2048)
797 .addTool(GetSdkQuality.class)
798 .addTool(GetSdkScore.class)
799 .addUserMessage("How good are the following SDKs and what do reviewers say: "
800 + "OpenAI Java SDK, Unknown Company SDK.");
801
802client.chat().completions().create(createParamsBuilder.build()).choices().stream()
803 .map(ChatCompletion.Choice::message)
804 // Add each assistant message onto the builder so that we keep track of the
805 // conversation for asking a follow-up question later.
806 .peek(createParamsBuilder::addMessage)
807 .flatMap(message -> {
808 message.content().ifPresent(System.out::println);
809 return message.toolCalls().stream().flatMap(Collection::stream);
810 })
811 .forEach(toolCall -> {
812 Object result = callFunction(toolCall.function());
813 // Add the tool call result to the conversation.
814 createParamsBuilder.addMessage(ChatCompletionToolMessageParam.builder()
815 .toolCallId(toolCall.id())
816 .contentAsJson(result)
817 .build());
818 });
819
820// Ask a follow-up question about the function call result.
821createParamsBuilder.addUserMessage("Why do you say that?");
822client.chat().completions().create(createParamsBuilder.build()).choices().stream()
823 .flatMap(choice -> choice.message().content().stream())
824 .forEach(System.out::println);
825
826static Object callFunction(ChatCompletionMessageToolCall.Function function) {
827 switch (function.name()) {
828 case "GetSdkQuality":
829 return function.arguments(GetSdkQuality.class).execute();
830 case "GetSdkScore":
831 return function.arguments(GetSdkScore.class).execute();
832 default:
833 throw new IllegalArgumentException("Unknown function: " + function.name());
834 }
835}
836```
837
838In the code above, an `execute()` method encapsulates each function's logic. However, there is no
839requirement to follow that pattern. You are free to implement your function's logic in any way that
840best suits your use case. The pattern above is only intended to _suggest_ that a suitable pattern
841may make the process of function calling simpler to understand and implement.
842
843### Usage with the Responses API
844
845_Function Calling_ is also supported for the Responses API. The usage is the same as described
846except where the Responses API differs slightly from the Chat Completions API. Pass the top-level
847class to `addTool(Class<T>)` when building the parameters. In the response, look for
848[`RepoonseOutputItem`](openai-java-core/src/main/kotlin/com/openai/models/responses/ResponseOutputItem.kt)
849instances that are function calls. Parse the parameters to each function call to an instance of the
850class using
851[`ResponseFunctionToolCall.arguments(Class<T>)`](openai-java-core/src/main/kotlin/com/openai/models/responses/ResponseFunctionToolCall.kt).
852Finally, pass the result of each call back to the model.
853
854For a full example of the usage of _Function Calling_ with the Responses API using the low-level
855API to define and parse function parameters, see
856[`ResponsesFunctionCallingRawExample`](openai-java-example/src/main/java/com/openai/example/ResponsesFunctionCallingRawExample.java).
857
858For a full example of the usage of _Function Calling_ with the Responses API using Java classes to
859define and parse function parameters, see
860[`ResponsesFunctionCallingExample`](openai-java-example/src/main/java/com/openai/example/ResponsesFunctionCallingExample.java).
861
862### Local function JSON schema validation
863
864Like for _Structured Outputs_, you can perform local validation to check that the JSON schema
865derived from your function class respects the restrictions imposed by OpenAI on such schemas. Local
866validation is enabled by default, but it can be disabled by adding `JsonSchemaLocalValidation.NO` to
867the call to `addTool`.
868
869```java
870ChatCompletionCreateParams.Builder createParamsBuilder = ChatCompletionCreateParams.builder()
871 .model(ChatModel.GPT_3_5_TURBO)
872 .maxCompletionTokens(2048)
873 .addTool(GetSdkQuality.class, JsonSchemaLocalValidation.NO)
874 .addTool(GetSdkScore.class, JsonSchemaLocalValidation.NO)
875 .addUserMessage("How good are the following SDKs and what do reviewers say: "
876 + "OpenAI Java SDK, Unknown Company SDK.");
877```
878
879See [Local JSON schema validation](#local-json-schema-validation) for more details on local schema
880validation and under what circumstances you might want to disable it.
881
882### Annotating function classes
883
884You can use annotations to add further information about functions to the JSON schemas that are
885derived from your function classes, or to control which fields or getter methods will be used as
886parameters to the function. Details from annotations captured in the JSON schema may be used by the
887AI model to improve its response. The SDK supports the use of
888[Jackson Databind](https://github.com/FasterXML/jackson-databind) annotations.
889
890- Use `@JsonClassDescription` to add a description to a function class detailing when and how to use
891 that function.
892- Use `@JsonTypeName` to set the function name to something other than the simple name of the class,
893 which is used by default.
894- Use `@JsonPropertyDescription` to add a detailed description to function parameter (a field or
895 getter method of a function class).
896- Use `@JsonIgnore` to exclude a `public` field or getter method of a class from the generated JSON
897 schema for a function's parameters.
898- Use `@JsonProperty` to include a non-`public` field or getter method of a class in the generated
899 JSON schema for a function's parameters.
900
901OpenAI provides some
902[Best practices for defining functions](https://platform.openai.com/docs/guides/function-calling#best-practices-for-defining-functions)
903that may help you to understand how to use the above annotations effectively for your functions.
904
905See also [Defining JSON schema properties](#defining-json-schema-properties) for more details on how
906to use fields and getter methods and combine access modifiers and annotations to define the
907parameters of your functions. The same rules apply to function classes and to the structured output
908classes described in that section.
909
910## File uploads
911
912The SDK defines methods that accept files.
913
914To upload a file, pass a [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html):
915
916```java
917import com.openai.models.files.FileCreateParams;
918import com.openai.models.files.FileObject;
919import com.openai.models.files.FilePurpose;
920import java.nio.file.Paths;
921
922FileCreateParams params = FileCreateParams.builder()
923 .purpose(FilePurpose.FINE_TUNE)
924 .file(Paths.get("input.jsonl"))
925 .build();
926FileObject fileObject = client.files().create(params);
927```
928
929Or an arbitrary [`InputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html):
930
931```java
932import com.openai.models.files.FileCreateParams;
933import com.openai.models.files.FileObject;
934import com.openai.models.files.FilePurpose;
935import java.net.URL;
936
937FileCreateParams params = FileCreateParams.builder()
938 .purpose(FilePurpose.FINE_TUNE)
939 .file(new URL("https://example.com/input.jsonl").openStream())
940 .build();
941FileObject fileObject = client.files().create(params);
942```
943
944Or a `byte[]` array:
945
946```java
947import com.openai.models.files.FileCreateParams;
948import com.openai.models.files.FileObject;
949import com.openai.models.files.FilePurpose;
950
951FileCreateParams params = FileCreateParams.builder()
952 .purpose(FilePurpose.FINE_TUNE)
953 .file("content".getBytes())
954 .build();
955FileObject fileObject = client.files().create(params);
956```
957
958Note that when passing a non-`Path` its filename is unknown so it will not be included in the request. To manually set a filename, pass a [`MultipartField`](openai-java-core/src/main/kotlin/com/openai/core/Values.kt):
959
960```java
961import com.openai.core.MultipartField;
962import com.openai.models.files.FileCreateParams;
963import com.openai.models.files.FileObject;
964import com.openai.models.files.FilePurpose;
965import java.io.InputStream;
966import java.net.URL;
967
968FileCreateParams params = FileCreateParams.builder()
969 .purpose(FilePurpose.FINE_TUNE)
970 .file(MultipartField.<InputStream>builder()
971 .value(new URL("https://example.com/input.jsonl").openStream())
972 .filename("input.jsonl")
973 .build())
974 .build();
975FileObject fileObject = client.files().create(params);
976```
977
978## Webhook Verification
979
980Verifying webhook signatures is _optional but encouraged_.
981
982For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks).
983
984### Parsing webhook payloads
985
986For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.webhooks().unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will throw an exception if the signature is invalid.
987
988Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). The `.unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI.
989
990```java
991import com.openai.client.OpenAIClient;
992import com.openai.client.okhttp.OpenAIOkHttpClient;
993import com.openai.core.http.Headers;
994import com.openai.models.webhooks.UnwrapWebhookEvent;
995import java.util.Optional;
996
997OpenAIClient client = OpenAIOkHttpClient.fromEnv(); // OPENAI_WEBHOOK_SECRET env var used by default
998
999public void handleWebhook(String body, Map<String, String> headers) {
1000 try {
1001 Headers headersList = Headers.builder()
1002 .putAll(headers)
1003 .build();
1004
1005 UnwrapWebhookEvent event = client.webhooks().unwrap(body, headersList, Optional.empty());
1006
1007 if (event.isResponseCompletedWebhookEvent()) {
1008 System.out.println("Response completed: " + event.asResponseCompletedWebhookEvent().data());
1009 } else if (event.isResponseFailed()) {
1010 System.out.println("Response failed: " + event.asResponseFailed().data());
1011 } else {
1012 System.out.println("Unhandled event type: " + event.getClass().getSimpleName());
1013 }
1014 } catch (Exception e) {
1015 System.err.println("Invalid webhook signature: " + e.getMessage());
1016 // Handle invalid signature
1017 }
1018}
1019```
1020
1021### Verifying webhook payloads directly
1022
1023In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.webhooks().verifySignature()` to _only verify_ the signature of a webhook request. Like `.unwrap()`, this method will throw an exception if the signature is invalid.
1024
1025Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature.
1026
1027```java
1028import com.fasterxml.jackson.databind.ObjectMapper;
1029import com.openai.client.OpenAIClient;
1030import com.openai.client.okhttp.OpenAIOkHttpClient;
1031import com.openai.core.http.Headers;
1032import com.openai.models.webhooks.WebhookVerificationParams;
1033import java.util.Optional;
1034
1035OpenAIClient client = OpenAIOkHttpClient.fromEnv(); // OPENAI_WEBHOOK_SECRET env var used by default
1036ObjectMapper objectMapper = new ObjectMapper();
1037
1038public void handleWebhook(String body, Map<String, String> headers) {
1039 try {
1040 Headers headersList = Headers.builder()
1041 .putAll(headers)
1042 .build();
1043
1044 client.webhooks().verifySignature(
1045 WebhookVerificationParams.builder()
1046 .payload(body)
1047 .headers(headersList)
1048 .build()
1049 );
1050
1051 // Parse the body after verification
1052 Map<String, Object> event = objectMapper.readValue(body, Map.class);
1053 System.out.println("Verified event: " + event);
1054 } catch (Exception e) {
1055 System.err.println("Invalid webhook signature: " + e.getMessage());
1056 // Handle invalid signature
1057 }
1058}
1059```
1060
1061## Binary responses
1062
1063The SDK defines methods that return binary responses, which are used for API responses that shouldn't necessarily be parsed, like non-JSON data.
1064
1065These methods return [`HttpResponse`](openai-java-core/src/main/kotlin/com/openai/core/http/HttpResponse.kt):
1066
1067```java
1068import com.openai.core.http.HttpResponse;
1069import com.openai.models.files.FileContentParams;
1070
1071HttpResponse response = client.files().content("file_id");
1072```
1073
1074To save the response content to a file, use the [`Files.copy(...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) method:
1075
1076```java
1077import com.openai.core.http.HttpResponse;
1078import java.nio.file.Files;
1079import java.nio.file.Paths;
1080import java.nio.file.StandardCopyOption;
1081
1082try (HttpResponse response = client.files().content(params)) {
1083 Files.copy(
1084 response.body(),
1085 Paths.get(path),
1086 StandardCopyOption.REPLACE_EXISTING
1087 );
1088} catch (Exception e) {
1089 System.out.println("Something went wrong!");
1090 throw new RuntimeException(e);
1091}
1092```
1093
1094Or transfer the response content to any [`OutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html):
1095
1096```java
1097import com.openai.core.http.HttpResponse;
1098import java.nio.file.Files;
1099import java.nio.file.Paths;
1100
1101try (HttpResponse response = client.files().content(params)) {
1102 response.body().transferTo(Files.newOutputStream(Paths.get(path)));
1103} catch (Exception e) {
1104 System.out.println("Something went wrong!");
1105 throw new RuntimeException(e);
1106}
1107```
1108
1109## Raw responses
1110
1111The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don't provide access to the response headers, status code, or the raw response body.
1112
1113To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`:
1114
1115```java
1116import com.openai.core.http.Headers;
1117import com.openai.core.http.HttpResponseFor;
1118import com.openai.models.ChatModel;
1119import com.openai.models.chat.completions.ChatCompletion;
1120import com.openai.models.chat.completions.ChatCompletionCreateParams;
1121
1122ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
1123 .addUserMessage("Say this is a test")
1124 .model(ChatModel.GPT_4_1)
1125 .build();
1126HttpResponseFor<ChatCompletion> chatCompletion = client.chat().completions().withRawResponse().create(params);
1127
1128int statusCode = chatCompletion.statusCode();
1129Headers headers = chatCompletion.headers();
1130```
1131
1132You can still deserialize the response into an instance of a Java class if needed:
1133
1134```java
1135import com.openai.models.chat.completions.ChatCompletion;
1136
1137ChatCompletion parsedChatCompletion = chatCompletion.parse();
1138```
1139
1140### Request IDs
1141
1142> For more information on debugging requests, see [the API docs](https://platform.openai.com/docs/api-reference/debugging-requests).
1143
1144When using raw responses, you can access the `x-request-id` response header using the `requestId()` method:
1145
1146```java
1147import com.openai.core.http.HttpResponseFor;
1148import com.openai.models.chat.completions.ChatCompletion;
1149import java.util.Optional;
1150
1151HttpResponseFor<ChatCompletion> chatCompletion = client.chat().completions().withRawResponse().create(params);
1152Optional<String> requestId = chatCompletion.requestId();
1153```
1154
1155This can be used to quickly log failing requests and report them back to OpenAI.
1156
1157## Error handling
1158
1159The SDK throws custom unchecked exception types:
1160
1161- [`OpenAIServiceException`](openai-java-core/src/main/kotlin/com/openai/errors/OpenAIServiceException.kt): Base class for HTTP errors. See this table for which exception subclass is thrown for each HTTP status code:
1162
1163 | Status | Exception |
1164 | ------ | ---------------------------------------------------------------------------------------------------------------------- |
1165 | 400 | [`BadRequestException`](openai-java-core/src/main/kotlin/com/openai/errors/BadRequestException.kt) |
1166 | 401 | [`UnauthorizedException`](openai-java-core/src/main/kotlin/com/openai/errors/UnauthorizedException.kt) |
1167 | 403 | [`PermissionDeniedException`](openai-java-core/src/main/kotlin/com/openai/errors/PermissionDeniedException.kt) |
1168 | 404 | [`NotFoundException`](openai-java-core/src/main/kotlin/com/openai/errors/NotFoundException.kt) |
1169 | 422 | [`UnprocessableEntityException`](openai-java-core/src/main/kotlin/com/openai/errors/UnprocessableEntityException.kt) |
1170 | 429 | [`RateLimitException`](openai-java-core/src/main/kotlin/com/openai/errors/RateLimitException.kt) |
1171 | 5xx | [`InternalServerException`](openai-java-core/src/main/kotlin/com/openai/errors/InternalServerException.kt) |
1172 | others | [`UnexpectedStatusCodeException`](openai-java-core/src/main/kotlin/com/openai/errors/UnexpectedStatusCodeException.kt) |
1173
1174 [`SseException`](openai-java-core/src/main/kotlin/com/openai/errors/SseException.kt) is thrown for errors encountered during [SSE streaming](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) after a successful initial HTTP response.
1175
1176- [`OpenAIIoException`](openai-java-core/src/main/kotlin/com/openai/errors/OpenAIIoException.kt): I/O networking errors.
1177
1178- [`OpenAIInvalidDataException`](openai-java-core/src/main/kotlin/com/openai/errors/OpenAIInvalidDataException.kt): Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.
1179
1180- [`OpenAIException`](openai-java-core/src/main/kotlin/com/openai/errors/OpenAIException.kt): Base class for all exceptions. Most errors will result in one of the previously mentioned ones, but completely generic errors may be thrown using the base class.
1181
1182## Pagination
1183
1184The SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.
1185
1186### Auto-pagination
1187
1188To iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.
1189
1190When using the synchronous client, the method returns an [`Iterable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)
1191
1192```java
1193import com.openai.models.finetuning.jobs.FineTuningJob;
1194import com.openai.models.finetuning.jobs.JobListPage;
1195
1196JobListPage page = client.fineTuning().jobs().list();
1197
1198// Process as an Iterable
1199for (FineTuningJob job : page.autoPager()) {
1200 System.out.println(job);
1201}
1202
1203// Process as a Stream
1204page.autoPager()
1205 .stream()
1206 .limit(50)
1207 .forEach(job -> System.out.println(job));
1208```
1209
1210When using the asynchronous client, the method returns an [`AsyncStreamResponse`](openai-java-core/src/main/kotlin/com/openai/core/http/AsyncStreamResponse.kt):
1211
1212```java
1213import com.openai.core.http.AsyncStreamResponse;
1214import com.openai.models.finetuning.jobs.FineTuningJob;
1215import com.openai.models.finetuning.jobs.JobListPageAsync;
1216import java.util.Optional;
1217import java.util.concurrent.CompletableFuture;
1218
1219CompletableFuture<JobListPageAsync> pageFuture = client.async().fineTuning().jobs().list();
1220
1221pageFuture.thenRun(page -> page.autoPager().subscribe(job -> {
1222 System.out.println(job);
1223}));
1224
1225// If you need to handle errors or completion of the stream
1226pageFuture.thenRun(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {
1227 @Override
1228 public void onNext(FineTuningJob job) {
1229 System.out.println(job);
1230 }
1231
1232 @Override
1233 public void onComplete(Optional<Throwable> error) {
1234 if (error.isPresent()) {
1235 System.out.println("Something went wrong!");
1236 throw new RuntimeException(error.get());
1237 } else {
1238 System.out.println("No more!");
1239 }
1240 }
1241}));
1242
1243// Or use futures
1244pageFuture.thenRun(page -> page.autoPager()
1245 .subscribe(job -> {
1246 System.out.println(job);
1247 })
1248 .onCompleteFuture()
1249 .whenComplete((unused, error) -> {
1250 if (error != null) {
1251 System.out.println("Something went wrong!");
1252 throw new RuntimeException(error);
1253 } else {
1254 System.out.println("No more!");
1255 }
1256 }));
1257```
1258
1259### Manual pagination
1260
1261To access individual page items and manually request the next page, use the `items()`,
1262`hasNextPage()`, and `nextPage()` methods:
1263
1264```java
1265import com.openai.models.finetuning.jobs.FineTuningJob;
1266import com.openai.models.finetuning.jobs.JobListPage;
1267
1268JobListPage page = client.fineTuning().jobs().list();
1269while (true) {
1270 for (FineTuningJob job : page.items()) {
1271 System.out.println(job);
1272 }
1273
1274 if (!page.hasNextPage()) {
1275 break;
1276 }
1277
1278 page = page.nextPage();
1279}
1280```
1281
1282## Logging
1283
1284The SDK uses the standard [OkHttp logging interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor).
1285
1286Enable logging by setting the `OPENAI_LOG` environment variable to `info`:
1287
1288```sh
1289$ export OPENAI_LOG=info
1290```
1291
1292Or to `debug` for more verbose logging:
1293
1294```sh
1295$ export OPENAI_LOG=debug
1296```
1297
1298## Jackson
1299
1300The SDK depends on [Jackson](https://github.com/FasterXML/jackson) for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.
1301
1302The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).
1303
1304If the SDK threw an exception, but you're _certain_ the version is compatible, then disable the version check using the `checkJacksonVersionCompatibility` on [`OpenAIOkHttpClient`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClient.kt) or [`OpenAIOkHttpClientAsync`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClientAsync.kt).
1305
1306> [!CAUTION]
1307> We make no guarantee that the SDK works correctly when the Jackson version check is disabled.
1308
1309## Microsoft Azure
1310
1311To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the same
1312OpenAI client builder but with the Azure-specific configuration.
1313
1314```java
1315OpenAIClient client = OpenAIOkHttpClient.builder()
1316 // Gets the API key and endpoint from the `AZURE_OPENAI_KEY` and `OPENAI_BASE_URL` environment variables, respectively
1317 .fromEnv()
1318 // Set the Azure Entra ID
1319 .credential(BearerTokenCredential.create(AuthenticationUtil.getBearerTokenSupplier(
1320 new DefaultAzureCredentialBuilder().build(), "https://cognitiveservices.azure.com/.default")))
1321 .build();
1322```
1323
1324See the complete Azure OpenAI example in the [`openai-java-example`](openai-java-example/src/main/java/com/openai/example/AzureEntraIdExample.java) directory. The other examples in the directory also work with Azure as long as the client is configured to use it.
1325
1326## Network options
1327
1328### Retries
1329
1330The SDK automatically retries 2 times by default, with a short exponential backoff.
1331
1332Only the following error types are retried:
1333
1334- Connection errors (for example, due to a network connectivity problem)
1335- 408 Request Timeout
1336- 409 Conflict
1337- 429 Rate Limit
1338- 5xx Internal
1339
1340The API may also explicitly instruct the SDK to retry or not retry a response.
1341
1342To set a custom number of retries, configure the client using the `maxRetries` method:
1343
1344```java
1345import com.openai.client.OpenAIClient;
1346import com.openai.client.okhttp.OpenAIOkHttpClient;
1347
1348OpenAIClient client = OpenAIOkHttpClient.builder()
1349 .fromEnv()
1350 .maxRetries(4)
1351 .build();
1352```
1353
1354### Timeouts
1355
1356Requests time out after 10 minutes by default.
1357
1358To set a custom timeout, configure the method call using the `timeout` method:
1359
1360```java
1361import com.openai.models.chat.completions.ChatCompletion;
1362
1363ChatCompletion chatCompletion = client.chat().completions().create(
1364 params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()
1365);
1366```
1367
1368Or configure the default for all method calls at the client level:
1369
1370```java
1371import com.openai.client.OpenAIClient;
1372import com.openai.client.okhttp.OpenAIOkHttpClient;
1373import java.time.Duration;
1374
1375OpenAIClient client = OpenAIOkHttpClient.builder()
1376 .fromEnv()
1377 .timeout(Duration.ofSeconds(30))
1378 .build();
1379```
1380
1381### Proxies
1382
1383To route requests through a proxy, configure the client using the `proxy` method:
1384
1385```java
1386import com.openai.client.OpenAIClient;
1387import com.openai.client.okhttp.OpenAIOkHttpClient;
1388import java.net.InetSocketAddress;
1389import java.net.Proxy;
1390
1391OpenAIClient client = OpenAIOkHttpClient.builder()
1392 .fromEnv()
1393 .proxy(new Proxy(
1394 Proxy.Type.HTTP, new InetSocketAddress(
1395 "https://example.com", 8080
1396 )
1397 ))
1398 .build();
1399```
1400
1401### Custom HTTP client
1402
1403The SDK consists of three artifacts:
1404
1405- `openai-java-core`
1406 - Contains core SDK logic
1407 - Does not depend on [OkHttp](https://square.github.io/okhttp)
1408 - Exposes [`OpenAIClient`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClient.kt), [`OpenAIClientAsync`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsync.kt), [`OpenAIClientImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt), and [`OpenAIClientAsyncImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt), all of which can work with any HTTP client
1409- `openai-java-client-okhttp`
1410 - Depends on [OkHttp](https://square.github.io/okhttp)
1411 - Exposes [`OpenAIOkHttpClient`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClient.kt) and [`OpenAIOkHttpClientAsync`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClientAsync.kt), which provide a way to construct [`OpenAIClientImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt) and [`OpenAIClientAsyncImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt), respectively, using OkHttp
1412- `openai-java`
1413 - Depends on and exposes the APIs of both `openai-java-core` and `openai-java-client-okhttp`
1414 - Does not have its own logic
1415
1416This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies.
1417
1418#### Customized [`OkHttpClient`](https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html)
1419
1420> [!TIP]
1421> Try the available [network options](#network-options) before replacing the default client.
1422
1423To use a customized `OkHttpClient`:
1424
14251. Replace your [`openai-java` dependency](#installation) with `openai-java-core`
14262. Copy `openai-java-client-okhttp`'s [`OkHttpClient`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OkHttpClient.kt) class into your code and customize it
14273. Construct [`OpenAIClientImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt) or [`OpenAIClientAsyncImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt), similarly to [`OpenAIOkHttpClient`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClient.kt) or [`OpenAIOkHttpClientAsync`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClientAsync.kt), using your customized client
1428
1429### Completely custom HTTP client
1430
1431To use a completely custom HTTP client:
1432
14331. Replace your [`openai-java` dependency](#installation) with `openai-java-core`
14342. Write a class that implements the [`HttpClient`](openai-java-core/src/main/kotlin/com/openai/core/http/HttpClient.kt) interface
14353. Construct [`OpenAIClientImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt) or [`OpenAIClientAsyncImpl`](openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt), similarly to [`OpenAIOkHttpClient`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClient.kt) or [`OpenAIOkHttpClientAsync`](openai-java-client-okhttp/src/main/kotlin/com/openai/client/okhttp/OpenAIOkHttpClientAsync.kt), using your new client class
1436
1437## Undocumented API functionality
1438
1439The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.
1440
1441### Parameters
1442
1443To set undocumented parameters, call the `putAdditionalHeader`, `putAdditionalQueryParam`, or `putAdditionalBodyProperty` methods on any `Params` class:
1444
1445```java
1446import com.openai.core.JsonValue;
1447import com.openai.models.chat.completions.ChatCompletionCreateParams;
1448
1449ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
1450 .putAdditionalHeader("Secret-Header", "42")
1451 .putAdditionalQueryParam("secret_query_param", "42")
1452 .putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
1453 .build();
1454```
1455
1456These can be accessed on the built object later using the `_additionalHeaders()`, `_additionalQueryParams()`, and `_additionalBodyProperties()` methods.
1457
1458To set undocumented parameters on _nested_ headers, query params, or body classes, call the `putAdditionalProperty` method on the nested class:
1459
1460```java
1461import com.openai.core.JsonValue;
1462import com.openai.models.chat.completions.ChatCompletionCreateParams;
1463
1464ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
1465 .responseFormat(ChatCompletionCreateParams.ResponseFormat.builder()
1466 .putAdditionalProperty("secretProperty", JsonValue.from("42"))
1467 .build())
1468 .build();
1469```
1470
1471These properties can be accessed on the nested built object later using the `_additionalProperties()` method.
1472
1473To set a documented parameter or property to an undocumented or not yet supported _value_, pass a [`JsonValue`](openai-java-core/src/main/kotlin/com/openai/core/Values.kt) object to its setter:
1474
1475```java
1476import com.openai.core.JsonValue;
1477import com.openai.models.ChatModel;
1478import com.openai.models.chat.completions.ChatCompletionCreateParams;
1479
1480ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
1481 .messages(JsonValue.from(42))
1482 .model(ChatModel.GPT_4_1)
1483 .build();
1484```
1485
1486The most straightforward way to create a [`JsonValue`](openai-java-core/src/main/kotlin/com/openai/core/Values.kt) is using its `from(...)` method:
1487
1488```java
1489import com.openai.core.JsonValue;
1490import java.util.List;
1491import java.util.Map;
1492
1493// Create primitive JSON values
1494JsonValue nullValue = JsonValue.from(null);
1495JsonValue booleanValue = JsonValue.from(true);
1496JsonValue numberValue = JsonValue.from(42);
1497JsonValue stringValue = JsonValue.from("Hello World!");
1498
1499// Create a JSON array value equivalent to `["Hello", "World"]`
1500JsonValue arrayValue = JsonValue.from(List.of(
1501 "Hello", "World"
1502));
1503
1504// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`
1505JsonValue objectValue = JsonValue.from(Map.of(
1506 "a", 1,
1507 "b", 2
1508));
1509
1510// Create an arbitrarily nested JSON equivalent to:
1511// {
1512// "a": [1, 2],
1513// "b": [3, 4]
1514// }
1515JsonValue complexValue = JsonValue.from(Map.of(
1516 "a", List.of(
1517 1, 2
1518 ),
1519 "b", List.of(
1520 3, 4
1521 )
1522));
1523```
1524
1525Normally a `Builder` class's `build` method will throw [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html) if any required parameter or property is unset.
1526
1527To forcibly omit a required parameter or property, pass [`JsonMissing`](openai-java-core/src/main/kotlin/com/openai/core/Values.kt):
1528
1529```java
1530import com.openai.core.JsonMissing;
1531import com.openai.models.ChatModel;
1532import com.openai.models.chat.completions.ChatCompletionCreateParams;
1533
1534ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
1535 .model(ChatModel.GPT_4_1)
1536 .messages(JsonMissing.of())
1537 .build();
1538```
1539
1540### Response properties
1541
1542To access undocumented response properties, call the `_additionalProperties()` method:
1543
1544```java
1545import com.openai.core.JsonValue;
1546import java.util.Map;
1547
1548Map<String, JsonValue> additionalProperties = client.chat().completions().create(params)._additionalProperties();
1549JsonValue secretPropertyValue = additionalProperties.get("secretProperty");
1550
1551String result = secretPropertyValue.accept(new JsonValue.Visitor<>() {
1552 @Override
1553 public String visitNull() {
1554 return "It's null!";
1555 }
1556
1557 @Override
1558 public String visitBoolean(boolean value) {
1559 return "It's a boolean!";
1560 }
1561
1562 @Override
1563 public String visitNumber(Number value) {
1564 return "It's a number!";
1565 }
1566
1567 // Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`
1568 // The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden
1569});
1570```
1571
1572To access a property's raw JSON value, which may be undocumented, call its `_` prefixed method:
1573
1574```java
1575import com.openai.core.JsonField;
1576import com.openai.models.chat.completions.ChatCompletionMessageParam;
1577import java.util.Optional;
1578
1579JsonField<List<ChatCompletionMessageParam>> messages = client.chat().completions().create(params)._messages();
1580
1581if (messages.isMissing()) {
1582 // The property is absent from the JSON response
1583} else if (messages.isNull()) {
1584 // The property was set to literal null
1585} else {
1586 // Check if value was provided as a string
1587 // Other methods include `asNumber()`, `asBoolean()`, etc.
1588 Optional<String> jsonString = messages.asString();
1589
1590 // Try to deserialize into a custom type
1591 MyClass myObject = messages.asUnknown().orElseThrow().convert(MyClass.class);
1592}
1593```
1594
1595### Response validation
1596
1597In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a `String`, but the API could return something else.
1598
1599By default, the SDK will not throw an exception in this case. It will throw [`OpenAIInvalidDataException`](openai-java-core/src/main/kotlin/com/openai/errors/OpenAIInvalidDataException.kt) only if you directly access the property.
1600
1601If you would prefer to check that the response is completely well-typed upfront, then either call `validate()`:
1602
1603```java
1604import com.openai.models.chat.completions.ChatCompletion;
1605
1606ChatCompletion chatCompletion = client.chat().completions().create(params).validate();
1607```
1608
1609Or configure the method call to validate the response using the `responseValidation` method:
1610
1611```java
1612import com.openai.models.chat.completions.ChatCompletion;
1613
1614ChatCompletion chatCompletion = client.chat().completions().create(
1615 params, RequestOptions.builder().responseValidation(true).build()
1616);
1617```
1618
1619Or configure the default for all method calls at the client level:
1620
1621```java
1622import com.openai.client.OpenAIClient;
1623import com.openai.client.okhttp.OpenAIOkHttpClient;
1624
1625OpenAIClient client = OpenAIOkHttpClient.builder()
1626 .fromEnv()
1627 .responseValidation(true)
1628 .build();
1629```
1630
1631## FAQ
1632
1633### Why don't you use plain `enum` classes?
1634
1635Java `enum` classes are not trivially [forwards compatible](https://www.stainless.com/blog/making-java-enums-forwards-compatible). Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.
1636
1637### Why do you represent fields using `JsonField<T>` instead of just plain `T`?
1638
1639Using `JsonField<T>` enables a few features:
1640
1641- Allowing usage of [undocumented API functionality](#undocumented-api-functionality)
1642- Lazily [validating the API response against the expected shape](#response-validation)
1643- Representing absent vs explicitly null values
1644
1645### Why don't you use [`data` classes](https://kotlinlang.org/docs/data-classes.html)?
1646
1647It is not [backwards compatible to add new fields to a data class](https://kotlinlang.org/docs/api-guidelines-backward-compatibility.html#avoid-using-data-classes-in-your-api) and we don't want to introduce a breaking change every time we add a field to a class.
1648
1649### Why don't you use checked exceptions?
1650
1651Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.
1652
1653Checked exceptions:
1654
1655- Are verbose to handle
1656- Encourage error handling at the wrong level of abstraction, where nothing can be done about the error
1657- Are tedious to propagate due to the [function coloring problem](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function)
1658- Don't play well with lambdas (also due to the function coloring problem)
1659
1660## Semantic versioning
1661
1662This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
1663
16641. 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.)_
16652. Changes that we do not expect to impact the vast majority of users in practice.
1666
1667We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
1668
1669We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-java/issues) with questions, bugs, or suggestions.