diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 59565e8e..65f558e7 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
{
- ".": "1.6.1"
+ ".": "2.0.0"
}
\ No newline at end of file
diff --git a/.stats.yml b/.stats.yml
index 089abe5d..5a1f2ff0 100644
--- a/.stats.yml
+++ b/.stats.yml
@@ -1,4 +1,4 @@
-configured_endpoints: 95
-openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-0ee6b36cf3cc278cef4199a6aec5f7d530a6c1f17a74830037e96d50ca1edc50.yml
-openapi_spec_hash: e8ec5f46bc0655b34f292422d58a60f6
-config_hash: d9b6b6e6bc85744663e300eebc482067
+configured_endpoints: 99
+openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-794a6ed3c3d3d77887564755168056af8a426b17cf1ec721e3a300503dc22a41.yml
+openapi_spec_hash: 25a81c220713cd5b0bafc221d1dfa79a
+config_hash: 0b768ed1b56c6d82816f0fa40dc4aaf5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f164c88f..013a2250 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,46 @@
# Changelog
+## 2.0.0 (2025-05-11)
+
+Full Changelog: [v1.6.1...v2.0.0](https://github.com/openai/openai-java/compare/v1.6.1...v2.0.0)
+
+### ⚠ BREAKING CHANGES
+
+* **client:** change precision of some numeric types
+* **client:** extract auto pagination to shared classes
+* **client:** **Migration:** - If you were referencing the `AutoPager` class on a specific `*Page` or `*PageAsync` type, then you should instead reference the shared `AutoPager` and `AutoPagerAsync` types, under the `core` package
+ - `AutoPagerAsync` now has different usage. You can call `.subscribe(...)` on the returned object instead to get called back each page item. You can also call `onCompleteFuture()` to get a future that completes when all items have been processed. Finally, you can call `.close()` on the returned object to stop auto-paginating early
+ - If you were referencing `getNextPage` or `getNextPageParams`:
+ - Swap to `nextPage()` and `nextPageParams()`
+ - Note that these both now return non-optional types (use `hasNextPage()` before calling these, since they will throw if it's impossible to get another page)
+
+### Features
+
+* **api:** Add reinforcement fine-tuning api support ([d243892](https://github.com/openai/openai-java/commit/d2438923c2f53a76879464ab3816732b5c4b5718))
+* **client:** allow providing some params positionally ([7200cf6](https://github.com/openai/openai-java/commit/7200cf61d31fcc16b15d01cd83d3a0bcc53eba4d))
+* **client:** extract auto pagination to shared classes ([f623bca](https://github.com/openai/openai-java/commit/f623bcac1e66ed15f8ba6c89375468b764cb900f))
+
+
+### Bug Fixes
+
+* add missing `deploymentModel` params ([bb85d0d](https://github.com/openai/openai-java/commit/bb85d0d1a899b3981f5c1f818dc4200939cb571d))
+* merge conflict ([4587737](https://github.com/openai/openai-java/commit/458773748bba0efefce9e67d17b8d2879338cb61))
+
+
+### Chores
+
+* **internal:** fix custom code ([1da6c92](https://github.com/openai/openai-java/commit/1da6c92fc964837aec19a3688ffb9a1089b3d91c))
+
+
+### Documentation
+
+* remove or fix invalid readme examples ([4bf868a](https://github.com/openai/openai-java/commit/4bf868a717f9f782cd2f288bffc74bb24b2bb0e7))
+
+
+### Refactors
+
+* **client:** change precision of some numeric types ([6cdb671](https://github.com/openai/openai-java/commit/6cdb6717e047e96f9f4186bec3beca0744f27a3a))
+
## 1.6.1 (2025-05-08)
Full Changelog: [v1.6.0...v1.6.1](https://github.com/openai/openai-java/compare/v1.6.0...v1.6.1)
diff --git a/README.md b/README.md
index 6a05116a..71037bd6 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,8 @@
-[](https://central.sonatype.com/artifact/com.openai/openai-java/1.6.1)
-[](https://javadoc.io/doc/com.openai/openai-java/1.6.1)
+[](https://central.sonatype.com/artifact/com.openai/openai-java/2.0.0)
+[](https://javadoc.io/doc/com.openai/openai-java/2.0.0)
@@ -11,7 +11,7 @@ The OpenAI Java SDK provides convenient access to the [OpenAI REST API](https://
-The 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/1.6.1).
+The 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.0.0).
@@ -22,7 +22,7 @@ The REST API documentation can be found on [platform.openai.com](https://platfor
### Gradle
```kotlin
-implementation("com.openai:openai-java:1.6.1")
+implementation("com.openai:openai-java:2.0.0")
```
### Maven
@@ -31,7 +31,7 @@ implementation("com.openai:openai-java:1.6.1")
com.openai
openai-java
- 1.6.1
+ 2.0.0
```
@@ -412,10 +412,7 @@ These methods return [`HttpResponse`](openai-java-core/src/main/kotlin/com/opena
import com.openai.core.http.HttpResponse;
import com.openai.models.files.FileContentParams;
-FileContentParams params = FileContentParams.builder()
- .fileId("file_id")
- .build();
-HttpResponse response = client.files().content(params);
+HttpResponse response = client.files().content("file_id");
```
To 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:
@@ -528,53 +525,101 @@ The SDK throws custom unchecked exception types:
## Pagination
-For 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.
+The 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.
### Auto-pagination
-To iterate through all results across all pages, you can use `autoPager`, which automatically handles fetching more pages for you:
+To iterate through all results across all pages, use the `autoPager()` method, which automatically fetches more pages as needed.
-### Synchronous
+When using the synchronous client, the method returns an [`Iterable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)
```java
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobListPage;
-// As an Iterable:
-JobListPage page = client.fineTuning().jobs().list(params);
+JobListPage page = client.fineTuning().jobs().list();
+
+// Process as an Iterable
for (FineTuningJob job : page.autoPager()) {
System.out.println(job);
-};
+}
-// As a Stream:
-client.fineTuning().jobs().list(params).autoPager().stream()
+// Process as a Stream
+page.autoPager()
+ .stream()
.limit(50)
.forEach(job -> System.out.println(job));
```
-### Asynchronous
+When using the asynchronous client, the method returns an [`AsyncStreamResponse`](openai-java-core/src/main/kotlin/com/openai/core/http/AsyncStreamResponse.kt):
```java
-// Using forEach, which returns CompletableFuture:
-asyncClient.fineTuning().jobs().list(params).autoPager()
- .forEach(job -> System.out.println(job), executor);
+import com.openai.core.http.AsyncStreamResponse;
+import com.openai.models.finetuning.jobs.FineTuningJob;
+import com.openai.models.finetuning.jobs.JobListPageAsync;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+
+CompletableFuture pageFuture = client.async().fineTuning().jobs().list();
+
+pageFuture.thenRun(page -> page.autoPager().subscribe(job -> {
+ System.out.println(job);
+}));
+
+// If you need to handle errors or completion of the stream
+pageFuture.thenRun(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {
+ @Override
+ public void onNext(FineTuningJob job) {
+ System.out.println(job);
+ }
+
+ @Override
+ public void onComplete(Optional error) {
+ if (error.isPresent()) {
+ System.out.println("Something went wrong!");
+ throw new RuntimeException(error.get());
+ } else {
+ System.out.println("No more!");
+ }
+ }
+}));
+
+// Or use futures
+pageFuture.thenRun(page -> page.autoPager()
+ .subscribe(job -> {
+ System.out.println(job);
+ })
+ .onCompleteFuture()
+ .whenComplete((unused, error) -> {
+ if (error != null) {
+ System.out.println("Something went wrong!");
+ throw new RuntimeException(error);
+ } else {
+ System.out.println("No more!");
+ }
+ }));
```
### Manual pagination
-If 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.
+To access individual page items and manually request the next page, use the `items()`,
+`hasNextPage()`, and `nextPage()` methods:
```java
import com.openai.models.finetuning.jobs.FineTuningJob;
import com.openai.models.finetuning.jobs.JobListPage;
-JobListPage page = client.fineTuning().jobs().list(params);
-while (page != null) {
- for (FineTuningJob job : page.data()) {
+JobListPage page = client.fineTuning().jobs().list();
+while (true) {
+ for (FineTuningJob job : page.items()) {
System.out.println(job);
}
- page = page.getNextPage().orElse(null);
+ if (!page.hasNextPage()) {
+ break;
+ }
+
+ page = page.nextPage();
}
```
@@ -657,9 +702,7 @@ Requests time out after 10 minutes by default.
To set a custom timeout, configure the method call using the `timeout` method:
```java
-import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
-import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletion chatCompletion = client.chat().completions().create(
params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()
@@ -775,11 +818,12 @@ To set a documented parameter or property to an undocumented or not yet supporte
```java
import com.openai.core.JsonValue;
+import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
- .addUserMessage("Say this is a test")
- .model(JsonValue.from(42))
+ .messages(JsonValue.from(42))
+ .model(ChatModel.GPT_4_1)
.build();
```
@@ -909,9 +953,7 @@ ChatCompletion chatCompletion = client.chat().completions().create(params).valid
Or configure the method call to validate the response using the `responseValidation` method:
```java
-import com.openai.models.ChatModel;
import com.openai.models.chat.completions.ChatCompletion;
-import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletion chatCompletion = client.chat().completions().create(
params, RequestOptions.builder().responseValidation(true).build()
diff --git a/build.gradle.kts b/build.gradle.kts
index 47de6d33..581930ee 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -8,7 +8,7 @@ repositories {
allprojects {
group = "com.openai"
- version = "1.6.1" // x-release-please-version
+ version = "2.0.0" // x-release-please-version
}
subprojects {
diff --git a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClient.kt b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClient.kt
index 3995c9ea..e990bc66 100644
--- a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClient.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClient.kt
@@ -11,6 +11,7 @@ import com.openai.services.blocking.EmbeddingService
import com.openai.services.blocking.EvalService
import com.openai.services.blocking.FileService
import com.openai.services.blocking.FineTuningService
+import com.openai.services.blocking.GraderService
import com.openai.services.blocking.ImageService
import com.openai.services.blocking.ModelService
import com.openai.services.blocking.ModerationService
@@ -65,6 +66,8 @@ interface OpenAIClient {
fun fineTuning(): FineTuningService
+ fun graders(): GraderService
+
fun vectorStores(): VectorStoreService
fun beta(): BetaService
@@ -111,6 +114,8 @@ interface OpenAIClient {
fun fineTuning(): FineTuningService.WithRawResponse
+ fun graders(): GraderService.WithRawResponse
+
fun vectorStores(): VectorStoreService.WithRawResponse
fun beta(): BetaService.WithRawResponse
diff --git a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsync.kt b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsync.kt
index 2a2d5894..aff5f61e 100644
--- a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsync.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsync.kt
@@ -11,6 +11,7 @@ import com.openai.services.async.EmbeddingServiceAsync
import com.openai.services.async.EvalServiceAsync
import com.openai.services.async.FileServiceAsync
import com.openai.services.async.FineTuningServiceAsync
+import com.openai.services.async.GraderServiceAsync
import com.openai.services.async.ImageServiceAsync
import com.openai.services.async.ModelServiceAsync
import com.openai.services.async.ModerationServiceAsync
@@ -65,6 +66,8 @@ interface OpenAIClientAsync {
fun fineTuning(): FineTuningServiceAsync
+ fun graders(): GraderServiceAsync
+
fun vectorStores(): VectorStoreServiceAsync
fun beta(): BetaServiceAsync
@@ -111,6 +114,8 @@ interface OpenAIClientAsync {
fun fineTuning(): FineTuningServiceAsync.WithRawResponse
+ fun graders(): GraderServiceAsync.WithRawResponse
+
fun vectorStores(): VectorStoreServiceAsync.WithRawResponse
fun beta(): BetaServiceAsync.WithRawResponse
diff --git a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt
index 2bbeb00b..5e2719a6 100644
--- a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientAsyncImpl.kt
@@ -22,6 +22,8 @@ import com.openai.services.async.FileServiceAsync
import com.openai.services.async.FileServiceAsyncImpl
import com.openai.services.async.FineTuningServiceAsync
import com.openai.services.async.FineTuningServiceAsyncImpl
+import com.openai.services.async.GraderServiceAsync
+import com.openai.services.async.GraderServiceAsyncImpl
import com.openai.services.async.ImageServiceAsync
import com.openai.services.async.ImageServiceAsyncImpl
import com.openai.services.async.ModelServiceAsync
@@ -84,6 +86,10 @@ class OpenAIClientAsyncImpl(private val clientOptions: ClientOptions) : OpenAICl
FineTuningServiceAsyncImpl(clientOptionsWithUserAgent)
}
+ private val graders: GraderServiceAsync by lazy {
+ GraderServiceAsyncImpl(clientOptionsWithUserAgent)
+ }
+
private val vectorStores: VectorStoreServiceAsync by lazy {
VectorStoreServiceAsyncImpl(clientOptionsWithUserAgent)
}
@@ -126,6 +132,8 @@ class OpenAIClientAsyncImpl(private val clientOptions: ClientOptions) : OpenAICl
override fun fineTuning(): FineTuningServiceAsync = fineTuning
+ override fun graders(): GraderServiceAsync = graders
+
override fun vectorStores(): VectorStoreServiceAsync = vectorStores
override fun beta(): BetaServiceAsync = beta
@@ -179,6 +187,10 @@ class OpenAIClientAsyncImpl(private val clientOptions: ClientOptions) : OpenAICl
FineTuningServiceAsyncImpl.WithRawResponseImpl(clientOptions)
}
+ private val graders: GraderServiceAsync.WithRawResponse by lazy {
+ GraderServiceAsyncImpl.WithRawResponseImpl(clientOptions)
+ }
+
private val vectorStores: VectorStoreServiceAsync.WithRawResponse by lazy {
VectorStoreServiceAsyncImpl.WithRawResponseImpl(clientOptions)
}
@@ -221,6 +233,8 @@ class OpenAIClientAsyncImpl(private val clientOptions: ClientOptions) : OpenAICl
override fun fineTuning(): FineTuningServiceAsync.WithRawResponse = fineTuning
+ override fun graders(): GraderServiceAsync.WithRawResponse = graders
+
override fun vectorStores(): VectorStoreServiceAsync.WithRawResponse = vectorStores
override fun beta(): BetaServiceAsync.WithRawResponse = beta
diff --git a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt
index 17ad13b4..c79edfec 100644
--- a/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/client/OpenAIClientImpl.kt
@@ -22,6 +22,8 @@ import com.openai.services.blocking.FileService
import com.openai.services.blocking.FileServiceImpl
import com.openai.services.blocking.FineTuningService
import com.openai.services.blocking.FineTuningServiceImpl
+import com.openai.services.blocking.GraderService
+import com.openai.services.blocking.GraderServiceImpl
import com.openai.services.blocking.ImageService
import com.openai.services.blocking.ImageServiceImpl
import com.openai.services.blocking.ModelService
@@ -78,6 +80,8 @@ class OpenAIClientImpl(private val clientOptions: ClientOptions) : OpenAIClient
FineTuningServiceImpl(clientOptionsWithUserAgent)
}
+ private val graders: GraderService by lazy { GraderServiceImpl(clientOptionsWithUserAgent) }
+
private val vectorStores: VectorStoreService by lazy {
VectorStoreServiceImpl(clientOptionsWithUserAgent)
}
@@ -116,6 +120,8 @@ class OpenAIClientImpl(private val clientOptions: ClientOptions) : OpenAIClient
override fun fineTuning(): FineTuningService = fineTuning
+ override fun graders(): GraderService = graders
+
override fun vectorStores(): VectorStoreService = vectorStores
override fun beta(): BetaService = beta
@@ -169,6 +175,10 @@ class OpenAIClientImpl(private val clientOptions: ClientOptions) : OpenAIClient
FineTuningServiceImpl.WithRawResponseImpl(clientOptions)
}
+ private val graders: GraderService.WithRawResponse by lazy {
+ GraderServiceImpl.WithRawResponseImpl(clientOptions)
+ }
+
private val vectorStores: VectorStoreService.WithRawResponse by lazy {
VectorStoreServiceImpl.WithRawResponseImpl(clientOptions)
}
@@ -211,6 +221,8 @@ class OpenAIClientImpl(private val clientOptions: ClientOptions) : OpenAIClient
override fun fineTuning(): FineTuningService.WithRawResponse = fineTuning
+ override fun graders(): GraderService.WithRawResponse = graders
+
override fun vectorStores(): VectorStoreService.WithRawResponse = vectorStores
override fun beta(): BetaService.WithRawResponse = beta
diff --git a/openai-java-core/src/main/kotlin/com/openai/core/AutoPager.kt b/openai-java-core/src/main/kotlin/com/openai/core/AutoPager.kt
new file mode 100644
index 00000000..888fd034
--- /dev/null
+++ b/openai-java-core/src/main/kotlin/com/openai/core/AutoPager.kt
@@ -0,0 +1,21 @@
+// File generated from our OpenAPI spec by Stainless.
+
+package com.openai.core
+
+import java.util.stream.Stream
+import java.util.stream.StreamSupport
+
+class AutoPager private constructor(private val firstPage: Page) : Iterable {
+
+ companion object {
+
+ fun from(firstPage: Page): AutoPager = AutoPager(firstPage)
+ }
+
+ override fun iterator(): Iterator =
+ generateSequence(firstPage) { if (it.hasNextPage()) it.nextPage() else null }
+ .flatMap { it.items() }
+ .iterator()
+
+ fun stream(): Stream = StreamSupport.stream(spliterator(), false)
+}
diff --git a/openai-java-core/src/main/kotlin/com/openai/core/AutoPagerAsync.kt b/openai-java-core/src/main/kotlin/com/openai/core/AutoPagerAsync.kt
new file mode 100644
index 00000000..649be47c
--- /dev/null
+++ b/openai-java-core/src/main/kotlin/com/openai/core/AutoPagerAsync.kt
@@ -0,0 +1,88 @@
+// File generated from our OpenAPI spec by Stainless.
+
+package com.openai.core
+
+import com.openai.core.http.AsyncStreamResponse
+import java.util.Optional
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.CompletionException
+import java.util.concurrent.Executor
+import java.util.concurrent.atomic.AtomicReference
+
+class AutoPagerAsync
+private constructor(private val firstPage: PageAsync, private val defaultExecutor: Executor) :
+ AsyncStreamResponse {
+
+ companion object {
+
+ fun from(firstPage: PageAsync, defaultExecutor: Executor): AutoPagerAsync =
+ AutoPagerAsync(firstPage, defaultExecutor)
+ }
+
+ private val onCompleteFuture = CompletableFuture()
+ private val state = AtomicReference(State.NEW)
+
+ override fun subscribe(handler: AsyncStreamResponse.Handler): AsyncStreamResponse =
+ subscribe(handler, defaultExecutor)
+
+ override fun subscribe(
+ handler: AsyncStreamResponse.Handler,
+ executor: Executor,
+ ): AsyncStreamResponse = apply {
+ // TODO(JDK): Use `compareAndExchange` once targeting JDK 9.
+ check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) {
+ if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once"
+ else "Cannot subscribe after the response is closed"
+ }
+
+ fun PageAsync.handle(): CompletableFuture {
+ if (state.get() == State.CLOSED) {
+ return CompletableFuture.completedFuture(null)
+ }
+
+ items().forEach { handler.onNext(it) }
+ return if (hasNextPage()) nextPage().thenCompose { it.handle() }
+ else CompletableFuture.completedFuture(null)
+ }
+
+ executor.execute {
+ firstPage.handle().whenComplete { _, error ->
+ val actualError =
+ if (error is CompletionException && error.cause != null) error.cause else error
+ try {
+ handler.onComplete(Optional.ofNullable(actualError))
+ } finally {
+ try {
+ if (actualError == null) {
+ onCompleteFuture.complete(null)
+ } else {
+ onCompleteFuture.completeExceptionally(actualError)
+ }
+ } finally {
+ close()
+ }
+ }
+ }
+ }
+ }
+
+ override fun onCompleteFuture(): CompletableFuture = onCompleteFuture
+
+ override fun close() {
+ val previousState = state.getAndSet(State.CLOSED)
+ if (previousState == State.CLOSED) {
+ return
+ }
+
+ // When the stream is closed, we should always consider it closed. If it closed due
+ // to an error, then we will have already completed the future earlier, and this
+ // will be a no-op.
+ onCompleteFuture.complete(null)
+ }
+}
+
+private enum class State {
+ NEW,
+ SUBSCRIBED,
+ CLOSED,
+}
diff --git a/openai-java-core/src/main/kotlin/com/openai/core/Check.kt b/openai-java-core/src/main/kotlin/com/openai/core/Check.kt
index dc411d75..53b3b919 100644
--- a/openai-java-core/src/main/kotlin/com/openai/core/Check.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/core/Check.kt
@@ -5,6 +5,9 @@ package com.openai.core
import com.fasterxml.jackson.core.Version
import com.fasterxml.jackson.core.util.VersionUtil
+fun checkRequired(name: String, condition: Boolean) =
+ check(condition) { "`$name` is required, but was not set" }
+
fun checkRequired(name: String, value: T?): T =
checkNotNull(value) { "`$name` is required, but was not set" }
diff --git a/openai-java-core/src/main/kotlin/com/openai/core/Page.kt b/openai-java-core/src/main/kotlin/com/openai/core/Page.kt
new file mode 100644
index 00000000..9c9560b4
--- /dev/null
+++ b/openai-java-core/src/main/kotlin/com/openai/core/Page.kt
@@ -0,0 +1,33 @@
+// File generated from our OpenAPI spec by Stainless.
+
+package com.openai.core
+
+/**
+ * An interface representing a single page, with items of type [T], from a paginated endpoint
+ * response.
+ *
+ * Implementations of this interface are expected to request additional pages synchronously. For
+ * asynchronous pagination, see the [PageAsync] interface.
+ */
+interface Page {
+
+ /**
+ * Returns whether there's another page after this one.
+ *
+ * The method generally doesn't make requests so the result depends entirely on the data in this
+ * page. If a significant amount of time has passed between requesting this page and calling
+ * this method, then the result could be stale.
+ */
+ fun hasNextPage(): Boolean
+
+ /**
+ * Returns the page after this one by making another request.
+ *
+ * @throws IllegalStateException if it's impossible to get the next page. This exception is
+ * avoidable by calling [hasNextPage] first.
+ */
+ fun nextPage(): Page
+
+ /** Returns the items in this page. */
+ fun items(): List
+}
diff --git a/openai-java-core/src/main/kotlin/com/openai/core/PageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/core/PageAsync.kt
new file mode 100644
index 00000000..c67ff791
--- /dev/null
+++ b/openai-java-core/src/main/kotlin/com/openai/core/PageAsync.kt
@@ -0,0 +1,35 @@
+// File generated from our OpenAPI spec by Stainless.
+
+package com.openai.core
+
+import java.util.concurrent.CompletableFuture
+
+/**
+ * An interface representing a single page, with items of type [T], from a paginated endpoint
+ * response.
+ *
+ * Implementations of this interface are expected to request additional pages asynchronously. For
+ * synchronous pagination, see the [Page] interface.
+ */
+interface PageAsync {
+
+ /**
+ * Returns whether there's another page after this one.
+ *
+ * The method generally doesn't make requests so the result depends entirely on the data in this
+ * page. If a significant amount of time has passed between requesting this page and calling
+ * this method, then the result could be stale.
+ */
+ fun hasNextPage(): Boolean
+
+ /**
+ * Returns the page after this one by making another request.
+ *
+ * @throws IllegalStateException if it's impossible to get the next page. This exception is
+ * avoidable by calling [hasNextPage] first.
+ */
+ fun nextPage(): CompletableFuture>
+
+ /** Returns the items in this page. */
+ fun items(): List
+}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionSegment.kt b/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionSegment.kt
index ffd5f56d..c2de7f04 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionSegment.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionSegment.kt
@@ -21,13 +21,13 @@ import kotlin.jvm.optionals.getOrNull
class TranscriptionSegment
private constructor(
private val id: JsonField,
- private val avgLogprob: JsonField,
- private val compressionRatio: JsonField,
- private val end: JsonField,
- private val noSpeechProb: JsonField,
+ private val avgLogprob: JsonField,
+ private val compressionRatio: JsonField,
+ private val end: JsonField,
+ private val noSpeechProb: JsonField,
private val seek: JsonField,
- private val start: JsonField,
- private val temperature: JsonField,
+ private val start: JsonField,
+ private val temperature: JsonField,
private val text: JsonField,
private val tokens: JsonField>,
private val additionalProperties: MutableMap,
@@ -38,19 +38,19 @@ private constructor(
@JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(),
@JsonProperty("avg_logprob")
@ExcludeMissing
- avgLogprob: JsonField = JsonMissing.of(),
+ avgLogprob: JsonField = JsonMissing.of(),
@JsonProperty("compression_ratio")
@ExcludeMissing
- compressionRatio: JsonField = JsonMissing.of(),
- @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(),
+ compressionRatio: JsonField = JsonMissing.of(),
+ @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(),
@JsonProperty("no_speech_prob")
@ExcludeMissing
- noSpeechProb: JsonField = JsonMissing.of(),
+ noSpeechProb: JsonField = JsonMissing.of(),
@JsonProperty("seek") @ExcludeMissing seek: JsonField = JsonMissing.of(),
- @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(),
+ @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(),
@JsonProperty("temperature")
@ExcludeMissing
- temperature: JsonField = JsonMissing.of(),
+ temperature: JsonField = JsonMissing.of(),
@JsonProperty("text") @ExcludeMissing text: JsonField = JsonMissing.of(),
@JsonProperty("tokens") @ExcludeMissing tokens: JsonField> = JsonMissing.of(),
) : this(
@@ -81,7 +81,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun avgLogprob(): Double = avgLogprob.getRequired("avg_logprob")
+ fun avgLogprob(): Float = avgLogprob.getRequired("avg_logprob")
/**
* Compression ratio of the segment. If the value is greater than 2.4, consider the compression
@@ -90,7 +90,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun compressionRatio(): Double = compressionRatio.getRequired("compression_ratio")
+ fun compressionRatio(): Float = compressionRatio.getRequired("compression_ratio")
/**
* End time of the segment in seconds.
@@ -98,7 +98,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun end(): Double = end.getRequired("end")
+ fun end(): Float = end.getRequired("end")
/**
* Probability of no speech in the segment. If the value is higher than 1.0 and the
@@ -107,7 +107,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun noSpeechProb(): Double = noSpeechProb.getRequired("no_speech_prob")
+ fun noSpeechProb(): Float = noSpeechProb.getRequired("no_speech_prob")
/**
* Seek offset of the segment.
@@ -123,7 +123,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun start(): Double = start.getRequired("start")
+ fun start(): Float = start.getRequired("start")
/**
* Temperature parameter used for generating the segment.
@@ -131,7 +131,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun temperature(): Double = temperature.getRequired("temperature")
+ fun temperature(): Float = temperature.getRequired("temperature")
/**
* Text content of the segment.
@@ -161,7 +161,7 @@ private constructor(
*
* Unlike [avgLogprob], this method doesn't throw if the JSON field has an unexpected type.
*/
- @JsonProperty("avg_logprob") @ExcludeMissing fun _avgLogprob(): JsonField = avgLogprob
+ @JsonProperty("avg_logprob") @ExcludeMissing fun _avgLogprob(): JsonField = avgLogprob
/**
* Returns the raw JSON value of [compressionRatio].
@@ -171,14 +171,14 @@ private constructor(
*/
@JsonProperty("compression_ratio")
@ExcludeMissing
- fun _compressionRatio(): JsonField = compressionRatio
+ fun _compressionRatio(): JsonField = compressionRatio
/**
* Returns the raw JSON value of [end].
*
* Unlike [end], this method doesn't throw if the JSON field has an unexpected type.
*/
- @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end
+ @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end
/**
* Returns the raw JSON value of [noSpeechProb].
@@ -187,7 +187,7 @@ private constructor(
*/
@JsonProperty("no_speech_prob")
@ExcludeMissing
- fun _noSpeechProb(): JsonField = noSpeechProb
+ fun _noSpeechProb(): JsonField = noSpeechProb
/**
* Returns the raw JSON value of [seek].
@@ -201,14 +201,14 @@ private constructor(
*
* Unlike [start], this method doesn't throw if the JSON field has an unexpected type.
*/
- @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start
+ @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start
/**
* Returns the raw JSON value of [temperature].
*
* Unlike [temperature], this method doesn't throw if the JSON field has an unexpected type.
*/
- @JsonProperty("temperature") @ExcludeMissing fun _temperature(): JsonField = temperature
+ @JsonProperty("temperature") @ExcludeMissing fun _temperature(): JsonField = temperature
/**
* Returns the raw JSON value of [text].
@@ -262,13 +262,13 @@ private constructor(
class Builder internal constructor() {
private var id: JsonField? = null
- private var avgLogprob: JsonField? = null
- private var compressionRatio: JsonField? = null
- private var end: JsonField? = null
- private var noSpeechProb: JsonField? = null
+ private var avgLogprob: JsonField? = null
+ private var compressionRatio: JsonField? = null
+ private var end: JsonField? = null
+ private var noSpeechProb: JsonField? = null
private var seek: JsonField? = null
- private var start: JsonField? = null
- private var temperature: JsonField? = null
+ private var start: JsonField? = null
+ private var temperature: JsonField? = null
private var text: JsonField? = null
private var tokens: JsonField>? = null
private var additionalProperties: MutableMap = mutableMapOf()
@@ -303,60 +303,60 @@ private constructor(
* Average logprob of the segment. If the value is lower than -1, consider the logprobs
* failed.
*/
- fun avgLogprob(avgLogprob: Double) = avgLogprob(JsonField.of(avgLogprob))
+ fun avgLogprob(avgLogprob: Float) = avgLogprob(JsonField.of(avgLogprob))
/**
* Sets [Builder.avgLogprob] to an arbitrary JSON value.
*
- * You should usually call [Builder.avgLogprob] with a well-typed [Double] value instead.
+ * You should usually call [Builder.avgLogprob] with a well-typed [Float] value instead.
* This method is primarily for setting the field to an undocumented or not yet supported
* value.
*/
- fun avgLogprob(avgLogprob: JsonField) = apply { this.avgLogprob = avgLogprob }
+ fun avgLogprob(avgLogprob: JsonField) = apply { this.avgLogprob = avgLogprob }
/**
* Compression ratio of the segment. If the value is greater than 2.4, consider the
* compression failed.
*/
- fun compressionRatio(compressionRatio: Double) =
+ fun compressionRatio(compressionRatio: Float) =
compressionRatio(JsonField.of(compressionRatio))
/**
* Sets [Builder.compressionRatio] to an arbitrary JSON value.
*
- * You should usually call [Builder.compressionRatio] with a well-typed [Double] value
+ * You should usually call [Builder.compressionRatio] with a well-typed [Float] value
* instead. This method is primarily for setting the field to an undocumented or not yet
* supported value.
*/
- fun compressionRatio(compressionRatio: JsonField) = apply {
+ fun compressionRatio(compressionRatio: JsonField) = apply {
this.compressionRatio = compressionRatio
}
/** End time of the segment in seconds. */
- fun end(end: Double) = end(JsonField.of(end))
+ fun end(end: Float) = end(JsonField.of(end))
/**
* Sets [Builder.end] to an arbitrary JSON value.
*
- * You should usually call [Builder.end] with a well-typed [Double] value instead. This
+ * You should usually call [Builder.end] with a well-typed [Float] value instead. This
* method is primarily for setting the field to an undocumented or not yet supported value.
*/
- fun end(end: JsonField) = apply { this.end = end }
+ fun end(end: JsonField) = apply { this.end = end }
/**
* Probability of no speech in the segment. If the value is higher than 1.0 and the
* `avg_logprob` is below -1, consider this segment silent.
*/
- fun noSpeechProb(noSpeechProb: Double) = noSpeechProb(JsonField.of(noSpeechProb))
+ fun noSpeechProb(noSpeechProb: Float) = noSpeechProb(JsonField.of(noSpeechProb))
/**
* Sets [Builder.noSpeechProb] to an arbitrary JSON value.
*
- * You should usually call [Builder.noSpeechProb] with a well-typed [Double] value instead.
+ * You should usually call [Builder.noSpeechProb] with a well-typed [Float] value instead.
* This method is primarily for setting the field to an undocumented or not yet supported
* value.
*/
- fun noSpeechProb(noSpeechProb: JsonField) = apply {
+ fun noSpeechProb(noSpeechProb: JsonField) = apply {
this.noSpeechProb = noSpeechProb
}
@@ -372,27 +372,27 @@ private constructor(
fun seek(seek: JsonField) = apply { this.seek = seek }
/** Start time of the segment in seconds. */
- fun start(start: Double) = start(JsonField.of(start))
+ fun start(start: Float) = start(JsonField.of(start))
/**
* Sets [Builder.start] to an arbitrary JSON value.
*
- * You should usually call [Builder.start] with a well-typed [Double] value instead. This
+ * You should usually call [Builder.start] with a well-typed [Float] value instead. This
* method is primarily for setting the field to an undocumented or not yet supported value.
*/
- fun start(start: JsonField) = apply { this.start = start }
+ fun start(start: JsonField) = apply { this.start = start }
/** Temperature parameter used for generating the segment. */
- fun temperature(temperature: Double) = temperature(JsonField.of(temperature))
+ fun temperature(temperature: Float) = temperature(JsonField.of(temperature))
/**
* Sets [Builder.temperature] to an arbitrary JSON value.
*
- * You should usually call [Builder.temperature] with a well-typed [Double] value instead.
+ * You should usually call [Builder.temperature] with a well-typed [Float] value instead.
* This method is primarily for setting the field to an undocumented or not yet supported
* value.
*/
- fun temperature(temperature: JsonField) = apply { this.temperature = temperature }
+ fun temperature(temperature: JsonField) = apply { this.temperature = temperature }
/** Text content of the segment. */
fun text(text: String) = text(JsonField.of(text))
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionWord.kt b/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionWord.kt
index e17f2505..2ebd3c15 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionWord.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/audio/transcriptions/TranscriptionWord.kt
@@ -17,16 +17,16 @@ import java.util.Objects
class TranscriptionWord
private constructor(
- private val end: JsonField,
- private val start: JsonField,
+ private val end: JsonField,
+ private val start: JsonField,
private val word: JsonField,
private val additionalProperties: MutableMap,
) {
@JsonCreator
private constructor(
- @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(),
- @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(),
+ @JsonProperty("end") @ExcludeMissing end: JsonField = JsonMissing.of(),
+ @JsonProperty("start") @ExcludeMissing start: JsonField = JsonMissing.of(),
@JsonProperty("word") @ExcludeMissing word: JsonField = JsonMissing.of(),
) : this(end, start, word, mutableMapOf())
@@ -36,7 +36,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun end(): Double = end.getRequired("end")
+ fun end(): Float = end.getRequired("end")
/**
* Start time of the word in seconds.
@@ -44,7 +44,7 @@ private constructor(
* @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
* unexpectedly missing or null (e.g. if the server responded with an unexpected value).
*/
- fun start(): Double = start.getRequired("start")
+ fun start(): Float = start.getRequired("start")
/**
* The text content of the word.
@@ -59,14 +59,14 @@ private constructor(
*
* Unlike [end], this method doesn't throw if the JSON field has an unexpected type.
*/
- @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end
+ @JsonProperty("end") @ExcludeMissing fun _end(): JsonField = end
/**
* Returns the raw JSON value of [start].
*
* Unlike [start], this method doesn't throw if the JSON field has an unexpected type.
*/
- @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start
+ @JsonProperty("start") @ExcludeMissing fun _start(): JsonField = start
/**
* Returns the raw JSON value of [word].
@@ -105,8 +105,8 @@ private constructor(
/** A builder for [TranscriptionWord]. */
class Builder internal constructor() {
- private var end: JsonField? = null
- private var start: JsonField? = null
+ private var end: JsonField? = null
+ private var start: JsonField? = null
private var word: JsonField? = null
private var additionalProperties: MutableMap = mutableMapOf()
@@ -119,26 +119,26 @@ private constructor(
}
/** End time of the word in seconds. */
- fun end(end: Double) = end(JsonField.of(end))
+ fun end(end: Float) = end(JsonField.of(end))
/**
* Sets [Builder.end] to an arbitrary JSON value.
*
- * You should usually call [Builder.end] with a well-typed [Double] value instead. This
+ * You should usually call [Builder.end] with a well-typed [Float] value instead. This
* method is primarily for setting the field to an undocumented or not yet supported value.
*/
- fun end(end: JsonField) = apply { this.end = end }
+ fun end(end: JsonField) = apply { this.end = end }
/** Start time of the word in seconds. */
- fun start(start: Double) = start(JsonField.of(start))
+ fun start(start: Float) = start(JsonField.of(start))
/**
* Sets [Builder.start] to an arbitrary JSON value.
*
- * You should usually call [Builder.start] with a well-typed [Double] value instead. This
+ * You should usually call [Builder.start] with a well-typed [Float] value instead. This
* method is primarily for setting the field to an undocumented or not yet supported value.
*/
- fun start(start: JsonField) = apply { this.start = start }
+ fun start(start: JsonField) = apply { this.start = start }
/** The text content of the word. */
fun word(word: String) = word(JsonField.of(word))
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchCancelParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchCancelParams.kt
index c9a0e725..4fd0d88f 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchCancelParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchCancelParams.kt
@@ -4,12 +4,12 @@ package com.openai.models.batches
import com.openai.core.JsonValue
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
import java.util.Objects
import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/**
* Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes,
@@ -18,13 +18,13 @@ import java.util.Optional
*/
class BatchCancelParams
private constructor(
- private val batchId: String,
+ private val batchId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
private val additionalBodyProperties: Map,
) : Params {
- fun batchId(): String = batchId
+ fun batchId(): Optional = Optional.ofNullable(batchId)
fun _additionalBodyProperties(): Map = additionalBodyProperties
@@ -36,14 +36,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [BatchCancelParams].
- *
- * The following fields are required:
- * ```java
- * .batchId()
- * ```
- */
+ @JvmStatic fun none(): BatchCancelParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [BatchCancelParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -63,7 +58,10 @@ private constructor(
additionalBodyProperties = batchCancelParams.additionalBodyProperties.toMutableMap()
}
- fun batchId(batchId: String) = apply { this.batchId = batchId }
+ fun batchId(batchId: String?) = apply { this.batchId = batchId }
+
+ /** Alias for calling [Builder.batchId] with `batchId.orElse(null)`. */
+ fun batchId(batchId: Optional) = batchId(batchId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -189,17 +187,10 @@ private constructor(
* Returns an immutable instance of [BatchCancelParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .batchId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): BatchCancelParams =
BatchCancelParams(
- checkRequired("batchId", batchId),
+ batchId,
additionalHeaders.build(),
additionalQueryParams.build(),
additionalBodyProperties.toImmutable(),
@@ -211,7 +202,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> batchId
+ 0 -> batchId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPage.kt
index 35c7aa3f..d591ebcc 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPage.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPage.kt
@@ -2,12 +2,12 @@
package com.openai.models.batches
+import com.openai.core.AutoPager
+import com.openai.core.Page
import com.openai.core.checkRequired
import com.openai.services.blocking.BatchService
import java.util.Objects
import java.util.Optional
-import java.util.stream.Stream
-import java.util.stream.StreamSupport
import kotlin.jvm.optionals.getOrNull
/** @see [BatchService.list] */
@@ -16,7 +16,7 @@ private constructor(
private val service: BatchService,
private val params: BatchListParams,
private val response: BatchListPageResponse,
-) {
+) : Page {
/**
* Delegates to [BatchListPageResponse], but gracefully handles missing data.
@@ -32,19 +32,16 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): BatchListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): Optional = getNextPageParams().map { service.list(it) }
+ override fun nextPage(): BatchListPage = service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPager = AutoPager.from(this)
/** The parameters that were used to request this page. */
fun params(): BatchListParams = params
@@ -113,25 +110,6 @@ private constructor(
)
}
- class AutoPager(private val firstPage: BatchListPage) : Iterable {
-
- override fun iterator(): Iterator = iterator {
- var page = firstPage
- var index = 0
- while (true) {
- while (index < page.data().size) {
- yield(page.data()[index++])
- }
- page = page.getNextPage().getOrNull() ?: break
- index = 0
- }
- }
-
- fun stream(): Stream {
- return StreamSupport.stream(spliterator(), false)
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPageAsync.kt
index 61612712..0b36c622 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPageAsync.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchListPageAsync.kt
@@ -2,22 +2,24 @@
package com.openai.models.batches
+import com.openai.core.AutoPagerAsync
+import com.openai.core.PageAsync
import com.openai.core.checkRequired
import com.openai.services.async.BatchServiceAsync
import java.util.Objects
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
-import java.util.function.Predicate
import kotlin.jvm.optionals.getOrNull
/** @see [BatchServiceAsync.list] */
class BatchListPageAsync
private constructor(
private val service: BatchServiceAsync,
+ private val streamHandlerExecutor: Executor,
private val params: BatchListParams,
private val response: BatchListPageResponse,
-) {
+) : PageAsync {
/**
* Delegates to [BatchListPageResponse], but gracefully handles missing data.
@@ -33,22 +35,16 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): BatchListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): CompletableFuture> =
- getNextPageParams()
- .map { service.list(it).thenApply { Optional.of(it) } }
- .orElseGet { CompletableFuture.completedFuture(Optional.empty()) }
+ override fun nextPage(): CompletableFuture = service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor)
/** The parameters that were used to request this page. */
fun params(): BatchListParams = params
@@ -66,6 +62,7 @@ private constructor(
* The following fields are required:
* ```java
* .service()
+ * .streamHandlerExecutor()
* .params()
* .response()
* ```
@@ -77,18 +74,24 @@ private constructor(
class Builder internal constructor() {
private var service: BatchServiceAsync? = null
+ private var streamHandlerExecutor: Executor? = null
private var params: BatchListParams? = null
private var response: BatchListPageResponse? = null
@JvmSynthetic
internal fun from(batchListPageAsync: BatchListPageAsync) = apply {
service = batchListPageAsync.service
+ streamHandlerExecutor = batchListPageAsync.streamHandlerExecutor
params = batchListPageAsync.params
response = batchListPageAsync.response
}
fun service(service: BatchServiceAsync) = apply { this.service = service }
+ fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply {
+ this.streamHandlerExecutor = streamHandlerExecutor
+ }
+
/** The parameters that were used to request this page. */
fun params(params: BatchListParams) = apply { this.params = params }
@@ -103,6 +106,7 @@ private constructor(
* The following fields are required:
* ```java
* .service()
+ * .streamHandlerExecutor()
* .params()
* .response()
* ```
@@ -112,47 +116,22 @@ private constructor(
fun build(): BatchListPageAsync =
BatchListPageAsync(
checkRequired("service", service),
+ checkRequired("streamHandlerExecutor", streamHandlerExecutor),
checkRequired("params", params),
checkRequired("response", response),
)
}
- class AutoPager(private val firstPage: BatchListPageAsync) {
-
- fun forEach(action: Predicate, executor: Executor): CompletableFuture {
- fun CompletableFuture>.forEach(
- action: (Batch) -> Boolean,
- executor: Executor,
- ): CompletableFuture =
- thenComposeAsync(
- { page ->
- page
- .filter { it.data().all(action) }
- .map { it.getNextPage().forEach(action, executor) }
- .orElseGet { CompletableFuture.completedFuture(null) }
- },
- executor,
- )
- return CompletableFuture.completedFuture(Optional.of(firstPage))
- .forEach(action::test, executor)
- }
-
- fun toList(executor: Executor): CompletableFuture> {
- val values = mutableListOf()
- return forEach(values::add, executor).thenApply { values }
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
- return /* spotless:off */ other is BatchListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */
+ return /* spotless:off */ other is BatchListPageAsync && service == other.service && streamHandlerExecutor == other.streamHandlerExecutor && params == other.params && response == other.response /* spotless:on */
}
- override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */
+ override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, streamHandlerExecutor, params, response) /* spotless:on */
override fun toString() =
- "BatchListPageAsync{service=$service, params=$params, response=$response}"
+ "BatchListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}"
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchRetrieveParams.kt
index 94571a8a..d1667cc1 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchRetrieveParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/batches/BatchRetrieveParams.kt
@@ -3,20 +3,21 @@
package com.openai.models.batches
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import java.util.Objects
+import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Retrieves a batch. */
class BatchRetrieveParams
private constructor(
- private val batchId: String,
+ private val batchId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun batchId(): String = batchId
+ fun batchId(): Optional = Optional.ofNullable(batchId)
fun _additionalHeaders(): Headers = additionalHeaders
@@ -26,14 +27,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [BatchRetrieveParams].
- *
- * The following fields are required:
- * ```java
- * .batchId()
- * ```
- */
+ @JvmStatic fun none(): BatchRetrieveParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [BatchRetrieveParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -51,7 +47,10 @@ private constructor(
additionalQueryParams = batchRetrieveParams.additionalQueryParams.toBuilder()
}
- fun batchId(batchId: String) = apply { this.batchId = batchId }
+ fun batchId(batchId: String?) = apply { this.batchId = batchId }
+
+ /** Alias for calling [Builder.batchId] with `batchId.orElse(null)`. */
+ fun batchId(batchId: Optional) = batchId(batchId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -155,25 +154,14 @@ private constructor(
* Returns an immutable instance of [BatchRetrieveParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .batchId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): BatchRetrieveParams =
- BatchRetrieveParams(
- checkRequired("batchId", batchId),
- additionalHeaders.build(),
- additionalQueryParams.build(),
- )
+ BatchRetrieveParams(batchId, additionalHeaders.build(), additionalQueryParams.build())
}
fun _pathParam(index: Int): String =
when (index) {
- 0 -> batchId
+ 0 -> batchId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantDeleteParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantDeleteParams.kt
index f0c6d40f..b5df03cb 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantDeleteParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantDeleteParams.kt
@@ -4,23 +4,23 @@ package com.openai.models.beta.assistants
import com.openai.core.JsonValue
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
import java.util.Objects
import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Delete an assistant. */
class AssistantDeleteParams
private constructor(
- private val assistantId: String,
+ private val assistantId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
private val additionalBodyProperties: Map,
) : Params {
- fun assistantId(): String = assistantId
+ fun assistantId(): Optional = Optional.ofNullable(assistantId)
fun _additionalBodyProperties(): Map = additionalBodyProperties
@@ -32,14 +32,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [AssistantDeleteParams].
- *
- * The following fields are required:
- * ```java
- * .assistantId()
- * ```
- */
+ @JvmStatic fun none(): AssistantDeleteParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [AssistantDeleteParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -59,7 +54,10 @@ private constructor(
additionalBodyProperties = assistantDeleteParams.additionalBodyProperties.toMutableMap()
}
- fun assistantId(assistantId: String) = apply { this.assistantId = assistantId }
+ fun assistantId(assistantId: String?) = apply { this.assistantId = assistantId }
+
+ /** Alias for calling [Builder.assistantId] with `assistantId.orElse(null)`. */
+ fun assistantId(assistantId: Optional) = assistantId(assistantId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -185,17 +183,10 @@ private constructor(
* Returns an immutable instance of [AssistantDeleteParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .assistantId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): AssistantDeleteParams =
AssistantDeleteParams(
- checkRequired("assistantId", assistantId),
+ assistantId,
additionalHeaders.build(),
additionalQueryParams.build(),
additionalBodyProperties.toImmutable(),
@@ -207,7 +198,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> assistantId
+ 0 -> assistantId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPage.kt
index c852b6fe..596b6fa6 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPage.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPage.kt
@@ -2,12 +2,12 @@
package com.openai.models.beta.assistants
+import com.openai.core.AutoPager
+import com.openai.core.Page
import com.openai.core.checkRequired
import com.openai.services.blocking.beta.AssistantService
import java.util.Objects
import java.util.Optional
-import java.util.stream.Stream
-import java.util.stream.StreamSupport
import kotlin.jvm.optionals.getOrNull
/** @see [AssistantService.list] */
@@ -16,7 +16,7 @@ private constructor(
private val service: AssistantService,
private val params: AssistantListParams,
private val response: AssistantListPageResponse,
-) {
+) : Page {
/**
* Delegates to [AssistantListPageResponse], but gracefully handles missing data.
@@ -32,19 +32,16 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): AssistantListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): Optional = getNextPageParams().map { service.list(it) }
+ override fun nextPage(): AssistantListPage = service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPager = AutoPager.from(this)
/** The parameters that were used to request this page. */
fun params(): AssistantListParams = params
@@ -113,25 +110,6 @@ private constructor(
)
}
- class AutoPager(private val firstPage: AssistantListPage) : Iterable {
-
- override fun iterator(): Iterator = iterator {
- var page = firstPage
- var index = 0
- while (true) {
- while (index < page.data().size) {
- yield(page.data()[index++])
- }
- page = page.getNextPage().getOrNull() ?: break
- index = 0
- }
- }
-
- fun stream(): Stream {
- return StreamSupport.stream(spliterator(), false)
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPageAsync.kt
index 0e90b27c..ce42fb78 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPageAsync.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantListPageAsync.kt
@@ -2,22 +2,24 @@
package com.openai.models.beta.assistants
+import com.openai.core.AutoPagerAsync
+import com.openai.core.PageAsync
import com.openai.core.checkRequired
import com.openai.services.async.beta.AssistantServiceAsync
import java.util.Objects
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
-import java.util.function.Predicate
import kotlin.jvm.optionals.getOrNull
/** @see [AssistantServiceAsync.list] */
class AssistantListPageAsync
private constructor(
private val service: AssistantServiceAsync,
+ private val streamHandlerExecutor: Executor,
private val params: AssistantListParams,
private val response: AssistantListPageResponse,
-) {
+) : PageAsync {
/**
* Delegates to [AssistantListPageResponse], but gracefully handles missing data.
@@ -33,22 +35,17 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): AssistantListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): CompletableFuture> =
- getNextPageParams()
- .map { service.list(it).thenApply { Optional.of(it) } }
- .orElseGet { CompletableFuture.completedFuture(Optional.empty()) }
+ override fun nextPage(): CompletableFuture =
+ service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor)
/** The parameters that were used to request this page. */
fun params(): AssistantListParams = params
@@ -66,6 +63,7 @@ private constructor(
* The following fields are required:
* ```java
* .service()
+ * .streamHandlerExecutor()
* .params()
* .response()
* ```
@@ -77,18 +75,24 @@ private constructor(
class Builder internal constructor() {
private var service: AssistantServiceAsync? = null
+ private var streamHandlerExecutor: Executor? = null
private var params: AssistantListParams? = null
private var response: AssistantListPageResponse? = null
@JvmSynthetic
internal fun from(assistantListPageAsync: AssistantListPageAsync) = apply {
service = assistantListPageAsync.service
+ streamHandlerExecutor = assistantListPageAsync.streamHandlerExecutor
params = assistantListPageAsync.params
response = assistantListPageAsync.response
}
fun service(service: AssistantServiceAsync) = apply { this.service = service }
+ fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply {
+ this.streamHandlerExecutor = streamHandlerExecutor
+ }
+
/** The parameters that were used to request this page. */
fun params(params: AssistantListParams) = apply { this.params = params }
@@ -103,6 +107,7 @@ private constructor(
* The following fields are required:
* ```java
* .service()
+ * .streamHandlerExecutor()
* .params()
* .response()
* ```
@@ -112,47 +117,22 @@ private constructor(
fun build(): AssistantListPageAsync =
AssistantListPageAsync(
checkRequired("service", service),
+ checkRequired("streamHandlerExecutor", streamHandlerExecutor),
checkRequired("params", params),
checkRequired("response", response),
)
}
- class AutoPager(private val firstPage: AssistantListPageAsync) {
-
- fun forEach(action: Predicate, executor: Executor): CompletableFuture {
- fun CompletableFuture>.forEach(
- action: (Assistant) -> Boolean,
- executor: Executor,
- ): CompletableFuture =
- thenComposeAsync(
- { page ->
- page
- .filter { it.data().all(action) }
- .map { it.getNextPage().forEach(action, executor) }
- .orElseGet { CompletableFuture.completedFuture(null) }
- },
- executor,
- )
- return CompletableFuture.completedFuture(Optional.of(firstPage))
- .forEach(action::test, executor)
- }
-
- fun toList(executor: Executor): CompletableFuture> {
- val values = mutableListOf()
- return forEach(values::add, executor).thenApply { values }
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
- return /* spotless:off */ other is AssistantListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */
+ return /* spotless:off */ other is AssistantListPageAsync && service == other.service && streamHandlerExecutor == other.streamHandlerExecutor && params == other.params && response == other.response /* spotless:on */
}
- override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */
+ override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, streamHandlerExecutor, params, response) /* spotless:on */
override fun toString() =
- "AssistantListPageAsync{service=$service, params=$params, response=$response}"
+ "AssistantListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}"
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantRetrieveParams.kt
index 5ded97d8..7b9b0792 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantRetrieveParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantRetrieveParams.kt
@@ -3,20 +3,21 @@
package com.openai.models.beta.assistants
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import java.util.Objects
+import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Retrieves an assistant. */
class AssistantRetrieveParams
private constructor(
- private val assistantId: String,
+ private val assistantId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun assistantId(): String = assistantId
+ fun assistantId(): Optional = Optional.ofNullable(assistantId)
fun _additionalHeaders(): Headers = additionalHeaders
@@ -26,14 +27,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [AssistantRetrieveParams].
- *
- * The following fields are required:
- * ```java
- * .assistantId()
- * ```
- */
+ @JvmStatic fun none(): AssistantRetrieveParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [AssistantRetrieveParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -51,7 +47,10 @@ private constructor(
additionalQueryParams = assistantRetrieveParams.additionalQueryParams.toBuilder()
}
- fun assistantId(assistantId: String) = apply { this.assistantId = assistantId }
+ fun assistantId(assistantId: String?) = apply { this.assistantId = assistantId }
+
+ /** Alias for calling [Builder.assistantId] with `assistantId.orElse(null)`. */
+ fun assistantId(assistantId: Optional) = assistantId(assistantId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -155,17 +154,10 @@ private constructor(
* Returns an immutable instance of [AssistantRetrieveParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .assistantId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): AssistantRetrieveParams =
AssistantRetrieveParams(
- checkRequired("assistantId", assistantId),
+ assistantId,
additionalHeaders.build(),
additionalQueryParams.build(),
)
@@ -173,7 +165,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> assistantId
+ 0 -> assistantId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantUpdateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantUpdateParams.kt
index 92fcba31..24ae8550 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantUpdateParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/assistants/AssistantUpdateParams.kt
@@ -13,7 +13,6 @@ import com.openai.core.JsonMissing
import com.openai.core.JsonValue
import com.openai.core.Params
import com.openai.core.checkKnown
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
@@ -32,13 +31,13 @@ import kotlin.jvm.optionals.getOrNull
/** Modifies an assistant. */
class AssistantUpdateParams
private constructor(
- private val assistantId: String,
+ private val assistantId: String?,
private val body: Body,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun assistantId(): String = assistantId
+ fun assistantId(): Optional = Optional.ofNullable(assistantId)
/**
* The description of the assistant. The maximum length is 512 characters.
@@ -253,14 +252,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [AssistantUpdateParams].
- *
- * The following fields are required:
- * ```java
- * .assistantId()
- * ```
- */
+ @JvmStatic fun none(): AssistantUpdateParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [AssistantUpdateParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -280,7 +274,10 @@ private constructor(
additionalQueryParams = assistantUpdateParams.additionalQueryParams.toBuilder()
}
- fun assistantId(assistantId: String) = apply { this.assistantId = assistantId }
+ fun assistantId(assistantId: String?) = apply { this.assistantId = assistantId }
+
+ /** Alias for calling [Builder.assistantId] with `assistantId.orElse(null)`. */
+ fun assistantId(assistantId: Optional) = assistantId(assistantId.getOrNull())
/**
* Sets the entire request body.
@@ -723,17 +720,10 @@ private constructor(
* Returns an immutable instance of [AssistantUpdateParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .assistantId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): AssistantUpdateParams =
AssistantUpdateParams(
- checkRequired("assistantId", assistantId),
+ assistantId,
body.build(),
additionalHeaders.build(),
additionalQueryParams.build(),
@@ -744,7 +734,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> assistantId
+ 0 -> assistantId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadDeleteParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadDeleteParams.kt
index fd960288..637a5853 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadDeleteParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadDeleteParams.kt
@@ -4,23 +4,23 @@ package com.openai.models.beta.threads
import com.openai.core.JsonValue
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
import java.util.Objects
import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Delete a thread. */
class ThreadDeleteParams
private constructor(
- private val threadId: String,
+ private val threadId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
private val additionalBodyProperties: Map,
) : Params {
- fun threadId(): String = threadId
+ fun threadId(): Optional = Optional.ofNullable(threadId)
fun _additionalBodyProperties(): Map = additionalBodyProperties
@@ -32,14 +32,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [ThreadDeleteParams].
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- */
+ @JvmStatic fun none(): ThreadDeleteParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [ThreadDeleteParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -59,7 +54,10 @@ private constructor(
additionalBodyProperties = threadDeleteParams.additionalBodyProperties.toMutableMap()
}
- fun threadId(threadId: String) = apply { this.threadId = threadId }
+ fun threadId(threadId: String?) = apply { this.threadId = threadId }
+
+ /** Alias for calling [Builder.threadId] with `threadId.orElse(null)`. */
+ fun threadId(threadId: Optional) = threadId(threadId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -185,17 +183,10 @@ private constructor(
* Returns an immutable instance of [ThreadDeleteParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): ThreadDeleteParams =
ThreadDeleteParams(
- checkRequired("threadId", threadId),
+ threadId,
additionalHeaders.build(),
additionalQueryParams.build(),
additionalBodyProperties.toImmutable(),
@@ -207,7 +198,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> threadId
+ 0 -> threadId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadRetrieveParams.kt
index 1d5bb1ae..2ee637c6 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadRetrieveParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadRetrieveParams.kt
@@ -3,20 +3,21 @@
package com.openai.models.beta.threads
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import java.util.Objects
+import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Retrieves a thread. */
class ThreadRetrieveParams
private constructor(
- private val threadId: String,
+ private val threadId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun threadId(): String = threadId
+ fun threadId(): Optional = Optional.ofNullable(threadId)
fun _additionalHeaders(): Headers = additionalHeaders
@@ -26,14 +27,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [ThreadRetrieveParams].
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- */
+ @JvmStatic fun none(): ThreadRetrieveParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [ThreadRetrieveParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -51,7 +47,10 @@ private constructor(
additionalQueryParams = threadRetrieveParams.additionalQueryParams.toBuilder()
}
- fun threadId(threadId: String) = apply { this.threadId = threadId }
+ fun threadId(threadId: String?) = apply { this.threadId = threadId }
+
+ /** Alias for calling [Builder.threadId] with `threadId.orElse(null)`. */
+ fun threadId(threadId: Optional) = threadId(threadId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -155,25 +154,14 @@ private constructor(
* Returns an immutable instance of [ThreadRetrieveParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): ThreadRetrieveParams =
- ThreadRetrieveParams(
- checkRequired("threadId", threadId),
- additionalHeaders.build(),
- additionalQueryParams.build(),
- )
+ ThreadRetrieveParams(threadId, additionalHeaders.build(), additionalQueryParams.build())
}
fun _pathParam(index: Int): String =
when (index) {
- 0 -> threadId
+ 0 -> threadId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadUpdateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadUpdateParams.kt
index 3afece77..d6d639af 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadUpdateParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/ThreadUpdateParams.kt
@@ -12,7 +12,6 @@ import com.openai.core.JsonMissing
import com.openai.core.JsonValue
import com.openai.core.Params
import com.openai.core.checkKnown
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
@@ -25,13 +24,13 @@ import kotlin.jvm.optionals.getOrNull
/** Modifies a thread. */
class ThreadUpdateParams
private constructor(
- private val threadId: String,
+ private val threadId: String?,
private val body: Body,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun threadId(): String = threadId
+ fun threadId(): Optional = Optional.ofNullable(threadId)
/**
* Set of 16 key-value pairs that can be attached to an object. This can be useful for storing
@@ -80,14 +79,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [ThreadUpdateParams].
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- */
+ @JvmStatic fun none(): ThreadUpdateParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [ThreadUpdateParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -107,7 +101,10 @@ private constructor(
additionalQueryParams = threadUpdateParams.additionalQueryParams.toBuilder()
}
- fun threadId(threadId: String) = apply { this.threadId = threadId }
+ fun threadId(threadId: String?) = apply { this.threadId = threadId }
+
+ /** Alias for calling [Builder.threadId] with `threadId.orElse(null)`. */
+ fun threadId(threadId: Optional) = threadId(threadId.getOrNull())
/**
* Sets the entire request body.
@@ -287,17 +284,10 @@ private constructor(
* Returns an immutable instance of [ThreadUpdateParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): ThreadUpdateParams =
ThreadUpdateParams(
- checkRequired("threadId", threadId),
+ threadId,
body.build(),
additionalHeaders.build(),
additionalQueryParams.build(),
@@ -308,7 +298,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> threadId
+ 0 -> threadId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageCreateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageCreateParams.kt
index 6bf8f054..caca9be5 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageCreateParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageCreateParams.kt
@@ -38,13 +38,13 @@ import kotlin.jvm.optionals.getOrNull
/** Create a message. */
class MessageCreateParams
private constructor(
- private val threadId: String,
+ private val threadId: String?,
private val body: Body,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun threadId(): String = threadId
+ fun threadId(): Optional = Optional.ofNullable(threadId)
/**
* The text contents of the message.
@@ -130,7 +130,6 @@ private constructor(
*
* The following fields are required:
* ```java
- * .threadId()
* .content()
* .role()
* ```
@@ -154,7 +153,10 @@ private constructor(
additionalQueryParams = messageCreateParams.additionalQueryParams.toBuilder()
}
- fun threadId(threadId: String) = apply { this.threadId = threadId }
+ fun threadId(threadId: String?) = apply { this.threadId = threadId }
+
+ /** Alias for calling [Builder.threadId] with `threadId.orElse(null)`. */
+ fun threadId(threadId: Optional) = threadId(threadId.getOrNull())
/**
* Sets the entire request body.
@@ -378,7 +380,6 @@ private constructor(
*
* The following fields are required:
* ```java
- * .threadId()
* .content()
* .role()
* ```
@@ -387,7 +388,7 @@ private constructor(
*/
fun build(): MessageCreateParams =
MessageCreateParams(
- checkRequired("threadId", threadId),
+ threadId,
body.build(),
additionalHeaders.build(),
additionalQueryParams.build(),
@@ -398,7 +399,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> threadId
+ 0 -> threadId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageDeleteParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageDeleteParams.kt
index e2022510..9c79b7b3 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageDeleteParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageDeleteParams.kt
@@ -10,12 +10,13 @@ import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
import java.util.Objects
import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Deletes a message. */
class MessageDeleteParams
private constructor(
private val threadId: String,
- private val messageId: String,
+ private val messageId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
private val additionalBodyProperties: Map,
@@ -23,7 +24,7 @@ private constructor(
fun threadId(): String = threadId
- fun messageId(): String = messageId
+ fun messageId(): Optional = Optional.ofNullable(messageId)
fun _additionalBodyProperties(): Map = additionalBodyProperties
@@ -41,7 +42,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .messageId()
* ```
*/
@JvmStatic fun builder() = Builder()
@@ -67,7 +67,10 @@ private constructor(
fun threadId(threadId: String) = apply { this.threadId = threadId }
- fun messageId(messageId: String) = apply { this.messageId = messageId }
+ fun messageId(messageId: String?) = apply { this.messageId = messageId }
+
+ /** Alias for calling [Builder.messageId] with `messageId.orElse(null)`. */
+ fun messageId(messageId: Optional) = messageId(messageId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -197,7 +200,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .messageId()
* ```
*
* @throws IllegalStateException if any required field is unset.
@@ -205,7 +207,7 @@ private constructor(
fun build(): MessageDeleteParams =
MessageDeleteParams(
checkRequired("threadId", threadId),
- checkRequired("messageId", messageId),
+ messageId,
additionalHeaders.build(),
additionalQueryParams.build(),
additionalBodyProperties.toImmutable(),
@@ -218,7 +220,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
0 -> threadId
- 1 -> messageId
+ 1 -> messageId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPage.kt
index 14a9a44d..560ff950 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPage.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPage.kt
@@ -2,12 +2,12 @@
package com.openai.models.beta.threads.messages
+import com.openai.core.AutoPager
+import com.openai.core.Page
import com.openai.core.checkRequired
import com.openai.services.blocking.beta.threads.MessageService
import java.util.Objects
import java.util.Optional
-import java.util.stream.Stream
-import java.util.stream.StreamSupport
import kotlin.jvm.optionals.getOrNull
/** @see [MessageService.list] */
@@ -16,7 +16,7 @@ private constructor(
private val service: MessageService,
private val params: MessageListParams,
private val response: MessageListPageResponse,
-) {
+) : Page {
/**
* Delegates to [MessageListPageResponse], but gracefully handles missing data.
@@ -32,19 +32,16 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): MessageListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): Optional = getNextPageParams().map { service.list(it) }
+ override fun nextPage(): MessageListPage = service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPager = AutoPager.from(this)
/** The parameters that were used to request this page. */
fun params(): MessageListParams = params
@@ -113,25 +110,6 @@ private constructor(
)
}
- class AutoPager(private val firstPage: MessageListPage) : Iterable {
-
- override fun iterator(): Iterator = iterator {
- var page = firstPage
- var index = 0
- while (true) {
- while (index < page.data().size) {
- yield(page.data()[index++])
- }
- page = page.getNextPage().getOrNull() ?: break
- index = 0
- }
- }
-
- fun stream(): Stream {
- return StreamSupport.stream(spliterator(), false)
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPageAsync.kt
index fd1595e3..8b6a0d4e 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPageAsync.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListPageAsync.kt
@@ -2,22 +2,24 @@
package com.openai.models.beta.threads.messages
+import com.openai.core.AutoPagerAsync
+import com.openai.core.PageAsync
import com.openai.core.checkRequired
import com.openai.services.async.beta.threads.MessageServiceAsync
import java.util.Objects
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
-import java.util.function.Predicate
import kotlin.jvm.optionals.getOrNull
/** @see [MessageServiceAsync.list] */
class MessageListPageAsync
private constructor(
private val service: MessageServiceAsync,
+ private val streamHandlerExecutor: Executor,
private val params: MessageListParams,
private val response: MessageListPageResponse,
-) {
+) : PageAsync {
/**
* Delegates to [MessageListPageResponse], but gracefully handles missing data.
@@ -33,22 +35,17 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): MessageListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): CompletableFuture> =
- getNextPageParams()
- .map { service.list(it).thenApply { Optional.of(it) } }
- .orElseGet { CompletableFuture.completedFuture(Optional.empty()) }
+ override fun nextPage(): CompletableFuture =
+ service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPagerAsync = AutoPagerAsync.from(this, streamHandlerExecutor)
/** The parameters that were used to request this page. */
fun params(): MessageListParams = params
@@ -66,6 +63,7 @@ private constructor(
* The following fields are required:
* ```java
* .service()
+ * .streamHandlerExecutor()
* .params()
* .response()
* ```
@@ -77,18 +75,24 @@ private constructor(
class Builder internal constructor() {
private var service: MessageServiceAsync? = null
+ private var streamHandlerExecutor: Executor? = null
private var params: MessageListParams? = null
private var response: MessageListPageResponse? = null
@JvmSynthetic
internal fun from(messageListPageAsync: MessageListPageAsync) = apply {
service = messageListPageAsync.service
+ streamHandlerExecutor = messageListPageAsync.streamHandlerExecutor
params = messageListPageAsync.params
response = messageListPageAsync.response
}
fun service(service: MessageServiceAsync) = apply { this.service = service }
+ fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply {
+ this.streamHandlerExecutor = streamHandlerExecutor
+ }
+
/** The parameters that were used to request this page. */
fun params(params: MessageListParams) = apply { this.params = params }
@@ -103,6 +107,7 @@ private constructor(
* The following fields are required:
* ```java
* .service()
+ * .streamHandlerExecutor()
* .params()
* .response()
* ```
@@ -112,47 +117,22 @@ private constructor(
fun build(): MessageListPageAsync =
MessageListPageAsync(
checkRequired("service", service),
+ checkRequired("streamHandlerExecutor", streamHandlerExecutor),
checkRequired("params", params),
checkRequired("response", response),
)
}
- class AutoPager(private val firstPage: MessageListPageAsync) {
-
- fun forEach(action: Predicate, executor: Executor): CompletableFuture {
- fun CompletableFuture>.forEach(
- action: (Message) -> Boolean,
- executor: Executor,
- ): CompletableFuture =
- thenComposeAsync(
- { page ->
- page
- .filter { it.data().all(action) }
- .map { it.getNextPage().forEach(action, executor) }
- .orElseGet { CompletableFuture.completedFuture(null) }
- },
- executor,
- )
- return CompletableFuture.completedFuture(Optional.of(firstPage))
- .forEach(action::test, executor)
- }
-
- fun toList(executor: Executor): CompletableFuture> {
- val values = mutableListOf()
- return forEach(values::add, executor).thenApply { values }
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
- return /* spotless:off */ other is MessageListPageAsync && service == other.service && params == other.params && response == other.response /* spotless:on */
+ return /* spotless:off */ other is MessageListPageAsync && service == other.service && streamHandlerExecutor == other.streamHandlerExecutor && params == other.params && response == other.response /* spotless:on */
}
- override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, params, response) /* spotless:on */
+ override fun hashCode(): Int = /* spotless:off */ Objects.hash(service, streamHandlerExecutor, params, response) /* spotless:on */
override fun toString() =
- "MessageListPageAsync{service=$service, params=$params, response=$response}"
+ "MessageListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}"
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListParams.kt
index 0a1f8bbb..add2694a 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageListParams.kt
@@ -6,7 +6,6 @@ import com.fasterxml.jackson.annotation.JsonCreator
import com.openai.core.Enum
import com.openai.core.JsonField
import com.openai.core.Params
-import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import com.openai.errors.OpenAIInvalidDataException
@@ -17,7 +16,7 @@ import kotlin.jvm.optionals.getOrNull
/** Returns a list of messages for a given thread. */
class MessageListParams
private constructor(
- private val threadId: String,
+ private val threadId: String?,
private val after: String?,
private val before: String?,
private val limit: Long?,
@@ -27,7 +26,7 @@ private constructor(
private val additionalQueryParams: QueryParams,
) : Params {
- fun threadId(): String = threadId
+ fun threadId(): Optional = Optional.ofNullable(threadId)
/**
* A cursor for use in pagination. `after` is an object ID that defines your place in the list.
@@ -66,14 +65,9 @@ private constructor(
companion object {
- /**
- * Returns a mutable builder for constructing an instance of [MessageListParams].
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- */
+ @JvmStatic fun none(): MessageListParams = builder().build()
+
+ /** Returns a mutable builder for constructing an instance of [MessageListParams]. */
@JvmStatic fun builder() = Builder()
}
@@ -101,7 +95,10 @@ private constructor(
additionalQueryParams = messageListParams.additionalQueryParams.toBuilder()
}
- fun threadId(threadId: String) = apply { this.threadId = threadId }
+ fun threadId(threadId: String?) = apply { this.threadId = threadId }
+
+ /** Alias for calling [Builder.threadId] with `threadId.orElse(null)`. */
+ fun threadId(threadId: Optional) = threadId(threadId.getOrNull())
/**
* A cursor for use in pagination. `after` is an object ID that defines your place in the
@@ -258,17 +255,10 @@ private constructor(
* Returns an immutable instance of [MessageListParams].
*
* Further updates to this [Builder] will not mutate the returned instance.
- *
- * The following fields are required:
- * ```java
- * .threadId()
- * ```
- *
- * @throws IllegalStateException if any required field is unset.
*/
fun build(): MessageListParams =
MessageListParams(
- checkRequired("threadId", threadId),
+ threadId,
after,
before,
limit,
@@ -281,7 +271,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> threadId
+ 0 -> threadId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageRetrieveParams.kt
index fc521fbf..4c9cb093 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageRetrieveParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageRetrieveParams.kt
@@ -7,19 +7,21 @@ import com.openai.core.checkRequired
import com.openai.core.http.Headers
import com.openai.core.http.QueryParams
import java.util.Objects
+import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Retrieve a message. */
class MessageRetrieveParams
private constructor(
private val threadId: String,
- private val messageId: String,
+ private val messageId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
fun threadId(): String = threadId
- fun messageId(): String = messageId
+ fun messageId(): Optional = Optional.ofNullable(messageId)
fun _additionalHeaders(): Headers = additionalHeaders
@@ -35,7 +37,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .messageId()
* ```
*/
@JvmStatic fun builder() = Builder()
@@ -59,7 +60,10 @@ private constructor(
fun threadId(threadId: String) = apply { this.threadId = threadId }
- fun messageId(messageId: String) = apply { this.messageId = messageId }
+ fun messageId(messageId: String?) = apply { this.messageId = messageId }
+
+ /** Alias for calling [Builder.messageId] with `messageId.orElse(null)`. */
+ fun messageId(messageId: Optional) = messageId(messageId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -167,7 +171,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .messageId()
* ```
*
* @throws IllegalStateException if any required field is unset.
@@ -175,7 +178,7 @@ private constructor(
fun build(): MessageRetrieveParams =
MessageRetrieveParams(
checkRequired("threadId", threadId),
- checkRequired("messageId", messageId),
+ messageId,
additionalHeaders.build(),
additionalQueryParams.build(),
)
@@ -184,7 +187,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
0 -> threadId
- 1 -> messageId
+ 1 -> messageId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageUpdateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageUpdateParams.kt
index de35e85e..30271871 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageUpdateParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/messages/MessageUpdateParams.kt
@@ -25,7 +25,7 @@ import kotlin.jvm.optionals.getOrNull
class MessageUpdateParams
private constructor(
private val threadId: String,
- private val messageId: String,
+ private val messageId: String?,
private val body: Body,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
@@ -33,7 +33,7 @@ private constructor(
fun threadId(): String = threadId
- fun messageId(): String = messageId
+ fun messageId(): Optional = Optional.ofNullable(messageId)
/**
* Set of 16 key-value pairs that can be attached to an object. This can be useful for storing
@@ -71,7 +71,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .messageId()
* ```
*/
@JvmStatic fun builder() = Builder()
@@ -97,7 +96,10 @@ private constructor(
fun threadId(threadId: String) = apply { this.threadId = threadId }
- fun messageId(messageId: String) = apply { this.messageId = messageId }
+ fun messageId(messageId: String?) = apply { this.messageId = messageId }
+
+ /** Alias for calling [Builder.messageId] with `messageId.orElse(null)`. */
+ fun messageId(messageId: Optional) = messageId(messageId.getOrNull())
/**
* Sets the entire request body.
@@ -255,7 +257,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .messageId()
* ```
*
* @throws IllegalStateException if any required field is unset.
@@ -263,7 +264,7 @@ private constructor(
fun build(): MessageUpdateParams =
MessageUpdateParams(
checkRequired("threadId", threadId),
- checkRequired("messageId", messageId),
+ messageId,
body.build(),
additionalHeaders.build(),
additionalQueryParams.build(),
@@ -275,7 +276,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
0 -> threadId
- 1 -> messageId
+ 1 -> messageId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCancelParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCancelParams.kt
index cf442b6c..ccb81100 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCancelParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCancelParams.kt
@@ -10,12 +10,13 @@ import com.openai.core.http.QueryParams
import com.openai.core.toImmutable
import java.util.Objects
import java.util.Optional
+import kotlin.jvm.optionals.getOrNull
/** Cancels a run that is `in_progress`. */
class RunCancelParams
private constructor(
private val threadId: String,
- private val runId: String,
+ private val runId: String?,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
private val additionalBodyProperties: Map,
@@ -23,7 +24,7 @@ private constructor(
fun threadId(): String = threadId
- fun runId(): String = runId
+ fun runId(): Optional = Optional.ofNullable(runId)
fun _additionalBodyProperties(): Map = additionalBodyProperties
@@ -41,7 +42,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .runId()
* ```
*/
@JvmStatic fun builder() = Builder()
@@ -67,7 +67,10 @@ private constructor(
fun threadId(threadId: String) = apply { this.threadId = threadId }
- fun runId(runId: String) = apply { this.runId = runId }
+ fun runId(runId: String?) = apply { this.runId = runId }
+
+ /** Alias for calling [Builder.runId] with `runId.orElse(null)`. */
+ fun runId(runId: Optional) = runId(runId.getOrNull())
fun additionalHeaders(additionalHeaders: Headers) = apply {
this.additionalHeaders.clear()
@@ -197,7 +200,6 @@ private constructor(
* The following fields are required:
* ```java
* .threadId()
- * .runId()
* ```
*
* @throws IllegalStateException if any required field is unset.
@@ -205,7 +207,7 @@ private constructor(
fun build(): RunCancelParams =
RunCancelParams(
checkRequired("threadId", threadId),
- checkRequired("runId", runId),
+ runId,
additionalHeaders.build(),
additionalQueryParams.build(),
additionalBodyProperties.toImmutable(),
@@ -218,7 +220,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
0 -> threadId
- 1 -> runId
+ 1 -> runId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCreateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCreateParams.kt
index 3d44da70..02f16270 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCreateParams.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunCreateParams.kt
@@ -52,14 +52,14 @@ import kotlin.jvm.optionals.getOrNull
/** Create a run. */
class RunCreateParams
private constructor(
- private val threadId: String,
+ private val threadId: String?,
private val include: List?,
private val body: Body,
private val additionalHeaders: Headers,
private val additionalQueryParams: QueryParams,
) : Params {
- fun threadId(): String = threadId
+ fun threadId(): Optional = Optional.ofNullable(threadId)
/**
* A list of additional fields to include in the response. Currently the only supported value is
@@ -385,7 +385,6 @@ private constructor(
*
* The following fields are required:
* ```java
- * .threadId()
* .assistantId()
* ```
*/
@@ -410,7 +409,10 @@ private constructor(
additionalQueryParams = runCreateParams.additionalQueryParams.toBuilder()
}
- fun threadId(threadId: String) = apply { this.threadId = threadId }
+ fun threadId(threadId: String?) = apply { this.threadId = threadId }
+
+ /** Alias for calling [Builder.threadId] with `threadId.orElse(null)`. */
+ fun threadId(threadId: Optional) = threadId(threadId.getOrNull())
/**
* A list of additional fields to include in the response. Currently the only supported
@@ -1057,7 +1059,6 @@ private constructor(
*
* The following fields are required:
* ```java
- * .threadId()
* .assistantId()
* ```
*
@@ -1065,7 +1066,7 @@ private constructor(
*/
fun build(): RunCreateParams =
RunCreateParams(
- checkRequired("threadId", threadId),
+ threadId,
include?.toImmutable(),
body.build(),
additionalHeaders.build(),
@@ -1077,7 +1078,7 @@ private constructor(
fun _pathParam(index: Int): String =
when (index) {
- 0 -> threadId
+ 0 -> threadId ?: ""
else -> ""
}
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPage.kt
index 108f1287..206a0e6a 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPage.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPage.kt
@@ -2,12 +2,12 @@
package com.openai.models.beta.threads.runs
+import com.openai.core.AutoPager
+import com.openai.core.Page
import com.openai.core.checkRequired
import com.openai.services.blocking.beta.threads.RunService
import java.util.Objects
import java.util.Optional
-import java.util.stream.Stream
-import java.util.stream.StreamSupport
import kotlin.jvm.optionals.getOrNull
/** @see [RunService.list] */
@@ -16,7 +16,7 @@ private constructor(
private val service: RunService,
private val params: RunListParams,
private val response: RunListPageResponse,
-) {
+) : Page {
/**
* Delegates to [RunListPageResponse], but gracefully handles missing data.
@@ -32,19 +32,16 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): RunListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): Optional = getNextPageParams().map { service.list(it) }
+ override fun nextPage(): RunListPage = service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPager = AutoPager.from(this)
/** The parameters that were used to request this page. */
fun params(): RunListParams = params
@@ -113,25 +110,6 @@ private constructor(
)
}
- class AutoPager(private val firstPage: RunListPage) : Iterable {
-
- override fun iterator(): Iterator = iterator {
- var page = firstPage
- var index = 0
- while (true) {
- while (index < page.data().size) {
- yield(page.data()[index++])
- }
- page = page.getNextPage().getOrNull() ?: break
- index = 0
- }
- }
-
- fun stream(): Stream {
- return StreamSupport.stream(spliterator(), false)
- }
- }
-
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
diff --git a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPageAsync.kt
index ca329d17..e5e70466 100644
--- a/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPageAsync.kt
+++ b/openai-java-core/src/main/kotlin/com/openai/models/beta/threads/runs/RunListPageAsync.kt
@@ -2,22 +2,24 @@
package com.openai.models.beta.threads.runs
+import com.openai.core.AutoPagerAsync
+import com.openai.core.PageAsync
import com.openai.core.checkRequired
import com.openai.services.async.beta.threads.RunServiceAsync
import java.util.Objects
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
-import java.util.function.Predicate
import kotlin.jvm.optionals.getOrNull
/** @see [RunServiceAsync.list] */
class RunListPageAsync
private constructor(
private val service: RunServiceAsync,
+ private val streamHandlerExecutor: Executor,
private val params: RunListParams,
private val response: RunListPageResponse,
-) {
+) : PageAsync {
/**
* Delegates to [RunListPageResponse], but gracefully handles missing data.
@@ -33,22 +35,16 @@ private constructor(
*/
fun hasMore(): Optional = response._hasMore().getOptional("has_more")
- fun hasNextPage(): Boolean = data().isNotEmpty()
+ override fun items(): List = data()
- fun getNextPageParams(): Optional {
- if (!hasNextPage()) {
- return Optional.empty()
- }
+ override fun hasNextPage(): Boolean = items().isNotEmpty()
- return Optional.of(params.toBuilder().after(data().last()._id().getOptional("id")).build())
- }
+ fun nextPageParams(): RunListParams =
+ params.toBuilder().after(items().last()._id().getOptional("id")).build()
- fun getNextPage(): CompletableFuture> =
- getNextPageParams()
- .map { service.list(it).thenApply { Optional.of(it) } }
- .orElseGet { CompletableFuture.completedFuture(Optional.empty()) }
+ override fun nextPage(): CompletableFuture = service.list(nextPageParams())
- fun autoPager(): AutoPager = AutoPager(this)
+ fun autoPager(): AutoPagerAsync