diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5194126..7a22a65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,7 @@ on: pull_request: branches: - main + - next jobs: lint: diff --git a/.stats.yml b/.stats.yml index 4020eec..71c963a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 1 +configured_endpoints: 20 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-27d8d6da893c1cdd53b491ec05153df22b1e113965f253a1d6eb8d75b628173f.yml diff --git a/README.md b/README.md index a3cba54..9a3f708 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ The OpenAI Java SDK is similar to the OpenAI Kotlin SDK but with minor differenc ## Documentation -The REST API documentation can be foundĀ [on platform.openai.com](https://platform.openai.com/docs). +The REST API documentation can be foundĀ on [platform.openai.com](https://platform.openai.com/docs). --- @@ -83,6 +83,40 @@ ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() ChatCompletion chatCompletion = client.chat().completions().create(params); ``` +### Example: listing resources + +The OpenAI API provides a `list` method to get a paginated list of jobs. +You can retrieve the first page by: + +```java +import com.openai.models.FineTuningJob; +import com.openai.models.Page; + +FineTuningJobListPage page = client.fineTuning().jobs().list(); +for (FineTuningJob job : page.data()) { + System.out.println(job); +} +``` + +Use the `FineTuningJobListParams` builder to set parameters: + +```java +FineTuningJobListParams params = FineTuningJobListParams.builder() + .limit(20) + .build(); +FineTuningJobListPage page1 = client.fineTuning().jobs().list(params); + +// Using the `from` method of the builder you can reuse previous params values: +FineTuningJobListPage page2 = client.fineTuning().jobs().list(FineTuningJobListParams.builder() + .from(params) + .build()); + +// Or easily get params for the next page by using the helper `getNextPageParams`: +FineTuningJobListPage page3 = client.fineTuning().jobs().list(params.getNextPageParams(page2)); +``` + +See [Pagination](#pagination) below for more information on transparently working with lists of objects without worrying about fetching each page. + --- ## Requests @@ -146,6 +180,57 @@ JsonValue secret = chatCompletion._additionalProperties().get("secret_field"); --- +## 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. + +### Auto-pagination + +To iterate through all results across all pages, you can use `autoPager`, +which automatically handles fetching more pages for you: + +### Synchronous + +```java +// As an Iterable: +FineTuningJobListPage page = client.fineTuning().jobs().list(params); +for (FineTuningJob job : page.autoPager()) { + System.out.println(job); +}; + +// As a Stream: +client.fineTuning().jobs().list(params).autoPager().stream() + .limit(50) + .forEach(job -> System.out.println(job)); +``` + +### Asynchronous + +```java +// Using forEach, which returns CompletableFuture: +asyncClient.fineTuning().jobs().list(params).autoPager() + .forEach(job -> System.out.println(job), executor); +``` + +### 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. + +```java +FineTuningJobListPage page = client.fineTuning().jobs().list(params); +while (page != null) { + for (FineTuningJob job : page.data()) { + System.out.println(job); + } + + page = page.getNextPage().orElse(null); +} +``` + --- ## Error handling @@ -244,3 +329,7 @@ This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) con We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. We are keen for your feedback; please open an [issue](https://www.github.com/stainless-sdks/openai-java/issues) with questions, bugs, or suggestions. + +## Requirements + +This library requires Java 8 or later. 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 8a3b2f1..c277055 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 @@ -12,4 +12,14 @@ interface OpenAIClient { fun async(): OpenAIClientAsync fun chat(): ChatService + + fun files(): FileService + + fun moderations(): ModerationService + + fun models(): ModelService + + fun fineTuning(): FineTuningService + + fun batches(): BatchService } 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 dbf2fb8..6a8c8a8 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 @@ -12,4 +12,14 @@ interface OpenAIClientAsync { fun sync(): OpenAIClient fun chat(): ChatServiceAsync + + fun files(): FileServiceAsync + + fun moderations(): ModerationServiceAsync + + fun models(): ModelServiceAsync + + fun fineTuning(): FineTuningServiceAsync + + fun batches(): BatchServiceAsync } 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 6090aec..6212329 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 @@ -20,7 +20,31 @@ constructor( private val chat: ChatServiceAsync by lazy { ChatServiceAsyncImpl(clientOptions) } + private val files: FileServiceAsync by lazy { FileServiceAsyncImpl(clientOptions) } + + private val moderations: ModerationServiceAsync by lazy { + ModerationServiceAsyncImpl(clientOptions) + } + + private val models: ModelServiceAsync by lazy { ModelServiceAsyncImpl(clientOptions) } + + private val fineTuning: FineTuningServiceAsync by lazy { + FineTuningServiceAsyncImpl(clientOptions) + } + + private val batches: BatchServiceAsync by lazy { BatchServiceAsyncImpl(clientOptions) } + override fun sync(): OpenAIClient = sync override fun chat(): ChatServiceAsync = chat + + override fun files(): FileServiceAsync = files + + override fun moderations(): ModerationServiceAsync = moderations + + override fun models(): ModelServiceAsync = models + + override fun fineTuning(): FineTuningServiceAsync = fineTuning + + override fun batches(): BatchServiceAsync = batches } 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 182290d..22116ad 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 @@ -20,7 +20,27 @@ constructor( private val chat: ChatService by lazy { ChatServiceImpl(clientOptions) } + private val files: FileService by lazy { FileServiceImpl(clientOptions) } + + private val moderations: ModerationService by lazy { ModerationServiceImpl(clientOptions) } + + private val models: ModelService by lazy { ModelServiceImpl(clientOptions) } + + private val fineTuning: FineTuningService by lazy { FineTuningServiceImpl(clientOptions) } + + private val batches: BatchService by lazy { BatchServiceImpl(clientOptions) } + override fun async(): OpenAIClientAsync = async override fun chat(): ChatService = chat + + override fun files(): FileService = files + + override fun moderations(): ModerationService = moderations + + override fun models(): ModelService = models + + override fun fineTuning(): FineTuningService = fineTuning + + override fun batches(): BatchService = batches } diff --git a/openai-java-core/src/main/kotlin/com/openai/models/Batch.kt b/openai-java-core/src/main/kotlin/com/openai/models/Batch.kt new file mode 100644 index 0000000..6dadccf --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/Batch.kt @@ -0,0 +1,786 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects +import java.util.Optional + +@JsonDeserialize(builder = Batch.Builder::class) +@NoAutoDetect +class Batch +private constructor( + private val id: JsonField, + private val object_: JsonField, + private val endpoint: JsonField, + private val errors: JsonField, + private val inputFileId: JsonField, + private val completionWindow: JsonField, + private val status: JsonField, + private val outputFileId: JsonField, + private val errorFileId: JsonField, + private val createdAt: JsonField, + private val inProgressAt: JsonField, + private val expiresAt: JsonField, + private val finalizingAt: JsonField, + private val completedAt: JsonField, + private val failedAt: JsonField, + private val expiredAt: JsonField, + private val cancellingAt: JsonField, + private val cancelledAt: JsonField, + private val requestCounts: JsonField, + private val metadata: JsonValue, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + fun id(): String = id.getRequired("id") + + /** The object type, which is always `batch`. */ + fun object_(): Object = object_.getRequired("object") + + /** The OpenAI API endpoint used by the batch. */ + fun endpoint(): String = endpoint.getRequired("endpoint") + + fun errors(): Optional = Optional.ofNullable(errors.getNullable("errors")) + + /** The ID of the input file for the batch. */ + fun inputFileId(): String = inputFileId.getRequired("input_file_id") + + /** The time frame within which the batch should be processed. */ + fun completionWindow(): String = completionWindow.getRequired("completion_window") + + /** The current status of the batch. */ + fun status(): Status = status.getRequired("status") + + /** The ID of the file containing the outputs of successfully executed requests. */ + fun outputFileId(): Optional = + Optional.ofNullable(outputFileId.getNullable("output_file_id")) + + /** The ID of the file containing the outputs of requests with errors. */ + fun errorFileId(): Optional = + Optional.ofNullable(errorFileId.getNullable("error_file_id")) + + /** The Unix timestamp (in seconds) for when the batch was created. */ + fun createdAt(): Long = createdAt.getRequired("created_at") + + /** The Unix timestamp (in seconds) for when the batch started processing. */ + fun inProgressAt(): Optional = + Optional.ofNullable(inProgressAt.getNullable("in_progress_at")) + + /** The Unix timestamp (in seconds) for when the batch will expire. */ + fun expiresAt(): Optional = Optional.ofNullable(expiresAt.getNullable("expires_at")) + + /** The Unix timestamp (in seconds) for when the batch started finalizing. */ + fun finalizingAt(): Optional = + Optional.ofNullable(finalizingAt.getNullable("finalizing_at")) + + /** The Unix timestamp (in seconds) for when the batch was completed. */ + fun completedAt(): Optional = Optional.ofNullable(completedAt.getNullable("completed_at")) + + /** The Unix timestamp (in seconds) for when the batch failed. */ + fun failedAt(): Optional = Optional.ofNullable(failedAt.getNullable("failed_at")) + + /** The Unix timestamp (in seconds) for when the batch expired. */ + fun expiredAt(): Optional = Optional.ofNullable(expiredAt.getNullable("expired_at")) + + /** The Unix timestamp (in seconds) for when the batch started cancelling. */ + fun cancellingAt(): Optional = + Optional.ofNullable(cancellingAt.getNullable("cancelling_at")) + + /** The Unix timestamp (in seconds) for when the batch was cancelled. */ + fun cancelledAt(): Optional = Optional.ofNullable(cancelledAt.getNullable("cancelled_at")) + + /** The request counts for different statuses within the batch. */ + fun requestCounts(): Optional = + Optional.ofNullable(requestCounts.getNullable("request_counts")) + + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** The object type, which is always `batch`. */ + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + /** The OpenAI API endpoint used by the batch. */ + @JsonProperty("endpoint") @ExcludeMissing fun _endpoint() = endpoint + + @JsonProperty("errors") @ExcludeMissing fun _errors() = errors + + /** The ID of the input file for the batch. */ + @JsonProperty("input_file_id") @ExcludeMissing fun _inputFileId() = inputFileId + + /** The time frame within which the batch should be processed. */ + @JsonProperty("completion_window") @ExcludeMissing fun _completionWindow() = completionWindow + + /** The current status of the batch. */ + @JsonProperty("status") @ExcludeMissing fun _status() = status + + /** The ID of the file containing the outputs of successfully executed requests. */ + @JsonProperty("output_file_id") @ExcludeMissing fun _outputFileId() = outputFileId + + /** The ID of the file containing the outputs of requests with errors. */ + @JsonProperty("error_file_id") @ExcludeMissing fun _errorFileId() = errorFileId + + /** The Unix timestamp (in seconds) for when the batch was created. */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + /** The Unix timestamp (in seconds) for when the batch started processing. */ + @JsonProperty("in_progress_at") @ExcludeMissing fun _inProgressAt() = inProgressAt + + /** The Unix timestamp (in seconds) for when the batch will expire. */ + @JsonProperty("expires_at") @ExcludeMissing fun _expiresAt() = expiresAt + + /** The Unix timestamp (in seconds) for when the batch started finalizing. */ + @JsonProperty("finalizing_at") @ExcludeMissing fun _finalizingAt() = finalizingAt + + /** The Unix timestamp (in seconds) for when the batch was completed. */ + @JsonProperty("completed_at") @ExcludeMissing fun _completedAt() = completedAt + + /** The Unix timestamp (in seconds) for when the batch failed. */ + @JsonProperty("failed_at") @ExcludeMissing fun _failedAt() = failedAt + + /** The Unix timestamp (in seconds) for when the batch expired. */ + @JsonProperty("expired_at") @ExcludeMissing fun _expiredAt() = expiredAt + + /** The Unix timestamp (in seconds) for when the batch started cancelling. */ + @JsonProperty("cancelling_at") @ExcludeMissing fun _cancellingAt() = cancellingAt + + /** The Unix timestamp (in seconds) for when the batch was cancelled. */ + @JsonProperty("cancelled_at") @ExcludeMissing fun _cancelledAt() = cancelledAt + + /** The request counts for different statuses within the batch. */ + @JsonProperty("request_counts") @ExcludeMissing fun _requestCounts() = requestCounts + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful for storing + * additional information about the object in a structured format. Keys can be a maximum of 64 + * characters long and values can be a maxium of 512 characters long. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Batch = apply { + if (!validated) { + id() + object_() + endpoint() + errors().map { it.validate() } + inputFileId() + completionWindow() + status() + outputFileId() + errorFileId() + createdAt() + inProgressAt() + expiresAt() + finalizingAt() + completedAt() + failedAt() + expiredAt() + cancellingAt() + cancelledAt() + requestCounts().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Batch && + this.id == other.id && + this.object_ == other.object_ && + this.endpoint == other.endpoint && + this.errors == other.errors && + this.inputFileId == other.inputFileId && + this.completionWindow == other.completionWindow && + this.status == other.status && + this.outputFileId == other.outputFileId && + this.errorFileId == other.errorFileId && + this.createdAt == other.createdAt && + this.inProgressAt == other.inProgressAt && + this.expiresAt == other.expiresAt && + this.finalizingAt == other.finalizingAt && + this.completedAt == other.completedAt && + this.failedAt == other.failedAt && + this.expiredAt == other.expiredAt && + this.cancellingAt == other.cancellingAt && + this.cancelledAt == other.cancelledAt && + this.requestCounts == other.requestCounts && + this.metadata == other.metadata && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + object_, + endpoint, + errors, + inputFileId, + completionWindow, + status, + outputFileId, + errorFileId, + createdAt, + inProgressAt, + expiresAt, + finalizingAt, + completedAt, + failedAt, + expiredAt, + cancellingAt, + cancelledAt, + requestCounts, + metadata, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Batch{id=$id, object_=$object_, endpoint=$endpoint, errors=$errors, inputFileId=$inputFileId, completionWindow=$completionWindow, status=$status, outputFileId=$outputFileId, errorFileId=$errorFileId, createdAt=$createdAt, inProgressAt=$inProgressAt, expiresAt=$expiresAt, finalizingAt=$finalizingAt, completedAt=$completedAt, failedAt=$failedAt, expiredAt=$expiredAt, cancellingAt=$cancellingAt, cancelledAt=$cancelledAt, requestCounts=$requestCounts, metadata=$metadata, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var endpoint: JsonField = JsonMissing.of() + private var errors: JsonField = JsonMissing.of() + private var inputFileId: JsonField = JsonMissing.of() + private var completionWindow: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var outputFileId: JsonField = JsonMissing.of() + private var errorFileId: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var inProgressAt: JsonField = JsonMissing.of() + private var expiresAt: JsonField = JsonMissing.of() + private var finalizingAt: JsonField = JsonMissing.of() + private var completedAt: JsonField = JsonMissing.of() + private var failedAt: JsonField = JsonMissing.of() + private var expiredAt: JsonField = JsonMissing.of() + private var cancellingAt: JsonField = JsonMissing.of() + private var cancelledAt: JsonField = JsonMissing.of() + private var requestCounts: JsonField = JsonMissing.of() + private var metadata: JsonValue = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batch: Batch) = apply { + this.id = batch.id + this.object_ = batch.object_ + this.endpoint = batch.endpoint + this.errors = batch.errors + this.inputFileId = batch.inputFileId + this.completionWindow = batch.completionWindow + this.status = batch.status + this.outputFileId = batch.outputFileId + this.errorFileId = batch.errorFileId + this.createdAt = batch.createdAt + this.inProgressAt = batch.inProgressAt + this.expiresAt = batch.expiresAt + this.finalizingAt = batch.finalizingAt + this.completedAt = batch.completedAt + this.failedAt = batch.failedAt + this.expiredAt = batch.expiredAt + this.cancellingAt = batch.cancellingAt + this.cancelledAt = batch.cancelledAt + this.requestCounts = batch.requestCounts + this.metadata = batch.metadata + additionalProperties(batch.additionalProperties) + } + + fun id(id: String) = id(JsonField.of(id)) + + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** The object type, which is always `batch`. */ + fun object_(object_: Object) = object_(JsonField.of(object_)) + + /** The object type, which is always `batch`. */ + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + /** The OpenAI API endpoint used by the batch. */ + fun endpoint(endpoint: String) = endpoint(JsonField.of(endpoint)) + + /** The OpenAI API endpoint used by the batch. */ + @JsonProperty("endpoint") + @ExcludeMissing + fun endpoint(endpoint: JsonField) = apply { this.endpoint = endpoint } + + fun errors(errors: Errors) = errors(JsonField.of(errors)) + + @JsonProperty("errors") + @ExcludeMissing + fun errors(errors: JsonField) = apply { this.errors = errors } + + /** The ID of the input file for the batch. */ + fun inputFileId(inputFileId: String) = inputFileId(JsonField.of(inputFileId)) + + /** The ID of the input file for the batch. */ + @JsonProperty("input_file_id") + @ExcludeMissing + fun inputFileId(inputFileId: JsonField) = apply { this.inputFileId = inputFileId } + + /** The time frame within which the batch should be processed. */ + fun completionWindow(completionWindow: String) = + completionWindow(JsonField.of(completionWindow)) + + /** The time frame within which the batch should be processed. */ + @JsonProperty("completion_window") + @ExcludeMissing + fun completionWindow(completionWindow: JsonField) = apply { + this.completionWindow = completionWindow + } + + /** The current status of the batch. */ + fun status(status: Status) = status(JsonField.of(status)) + + /** The current status of the batch. */ + @JsonProperty("status") + @ExcludeMissing + fun status(status: JsonField) = apply { this.status = status } + + /** The ID of the file containing the outputs of successfully executed requests. */ + fun outputFileId(outputFileId: String) = outputFileId(JsonField.of(outputFileId)) + + /** The ID of the file containing the outputs of successfully executed requests. */ + @JsonProperty("output_file_id") + @ExcludeMissing + fun outputFileId(outputFileId: JsonField) = apply { + this.outputFileId = outputFileId + } + + /** The ID of the file containing the outputs of requests with errors. */ + fun errorFileId(errorFileId: String) = errorFileId(JsonField.of(errorFileId)) + + /** The ID of the file containing the outputs of requests with errors. */ + @JsonProperty("error_file_id") + @ExcludeMissing + fun errorFileId(errorFileId: JsonField) = apply { this.errorFileId = errorFileId } + + /** The Unix timestamp (in seconds) for when the batch was created. */ + fun createdAt(createdAt: Long) = createdAt(JsonField.of(createdAt)) + + /** The Unix timestamp (in seconds) for when the batch was created. */ + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** The Unix timestamp (in seconds) for when the batch started processing. */ + fun inProgressAt(inProgressAt: Long) = inProgressAt(JsonField.of(inProgressAt)) + + /** The Unix timestamp (in seconds) for when the batch started processing. */ + @JsonProperty("in_progress_at") + @ExcludeMissing + fun inProgressAt(inProgressAt: JsonField) = apply { this.inProgressAt = inProgressAt } + + /** The Unix timestamp (in seconds) for when the batch will expire. */ + fun expiresAt(expiresAt: Long) = expiresAt(JsonField.of(expiresAt)) + + /** The Unix timestamp (in seconds) for when the batch will expire. */ + @JsonProperty("expires_at") + @ExcludeMissing + fun expiresAt(expiresAt: JsonField) = apply { this.expiresAt = expiresAt } + + /** The Unix timestamp (in seconds) for when the batch started finalizing. */ + fun finalizingAt(finalizingAt: Long) = finalizingAt(JsonField.of(finalizingAt)) + + /** The Unix timestamp (in seconds) for when the batch started finalizing. */ + @JsonProperty("finalizing_at") + @ExcludeMissing + fun finalizingAt(finalizingAt: JsonField) = apply { this.finalizingAt = finalizingAt } + + /** The Unix timestamp (in seconds) for when the batch was completed. */ + fun completedAt(completedAt: Long) = completedAt(JsonField.of(completedAt)) + + /** The Unix timestamp (in seconds) for when the batch was completed. */ + @JsonProperty("completed_at") + @ExcludeMissing + fun completedAt(completedAt: JsonField) = apply { this.completedAt = completedAt } + + /** The Unix timestamp (in seconds) for when the batch failed. */ + fun failedAt(failedAt: Long) = failedAt(JsonField.of(failedAt)) + + /** The Unix timestamp (in seconds) for when the batch failed. */ + @JsonProperty("failed_at") + @ExcludeMissing + fun failedAt(failedAt: JsonField) = apply { this.failedAt = failedAt } + + /** The Unix timestamp (in seconds) for when the batch expired. */ + fun expiredAt(expiredAt: Long) = expiredAt(JsonField.of(expiredAt)) + + /** The Unix timestamp (in seconds) for when the batch expired. */ + @JsonProperty("expired_at") + @ExcludeMissing + fun expiredAt(expiredAt: JsonField) = apply { this.expiredAt = expiredAt } + + /** The Unix timestamp (in seconds) for when the batch started cancelling. */ + fun cancellingAt(cancellingAt: Long) = cancellingAt(JsonField.of(cancellingAt)) + + /** The Unix timestamp (in seconds) for when the batch started cancelling. */ + @JsonProperty("cancelling_at") + @ExcludeMissing + fun cancellingAt(cancellingAt: JsonField) = apply { this.cancellingAt = cancellingAt } + + /** The Unix timestamp (in seconds) for when the batch was cancelled. */ + fun cancelledAt(cancelledAt: Long) = cancelledAt(JsonField.of(cancelledAt)) + + /** The Unix timestamp (in seconds) for when the batch was cancelled. */ + @JsonProperty("cancelled_at") + @ExcludeMissing + fun cancelledAt(cancelledAt: JsonField) = apply { this.cancelledAt = cancelledAt } + + /** The request counts for different statuses within the batch. */ + fun requestCounts(requestCounts: BatchRequestCounts) = + requestCounts(JsonField.of(requestCounts)) + + /** The request counts for different statuses within the batch. */ + @JsonProperty("request_counts") + @ExcludeMissing + fun requestCounts(requestCounts: JsonField) = apply { + this.requestCounts = requestCounts + } + + /** + * Set of 16 key-value pairs that can be attached to an object. This can be useful for + * storing additional information about the object in a structured format. Keys can be a + * maximum of 64 characters long and values can be a maxium of 512 characters long. + */ + @JsonProperty("metadata") + @ExcludeMissing + fun metadata(metadata: JsonValue) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Batch = + Batch( + id, + object_, + endpoint, + errors, + inputFileId, + completionWindow, + status, + outputFileId, + errorFileId, + createdAt, + inProgressAt, + expiresAt, + finalizingAt, + completedAt, + failedAt, + expiredAt, + cancellingAt, + cancelledAt, + requestCounts, + metadata, + additionalProperties.toUnmodifiable(), + ) + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val BATCH = Object(JsonField.of("batch")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + BATCH, + } + + enum class Value { + BATCH, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + BATCH -> Value.BATCH + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + BATCH -> Known.BATCH + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + class Status + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Status && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val VALIDATING = Status(JsonField.of("validating")) + + @JvmField val FAILED = Status(JsonField.of("failed")) + + @JvmField val IN_PROGRESS = Status(JsonField.of("in_progress")) + + @JvmField val FINALIZING = Status(JsonField.of("finalizing")) + + @JvmField val COMPLETED = Status(JsonField.of("completed")) + + @JvmField val EXPIRED = Status(JsonField.of("expired")) + + @JvmField val CANCELLING = Status(JsonField.of("cancelling")) + + @JvmField val CANCELLED = Status(JsonField.of("cancelled")) + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + enum class Known { + VALIDATING, + FAILED, + IN_PROGRESS, + FINALIZING, + COMPLETED, + EXPIRED, + CANCELLING, + CANCELLED, + } + + enum class Value { + VALIDATING, + FAILED, + IN_PROGRESS, + FINALIZING, + COMPLETED, + EXPIRED, + CANCELLING, + CANCELLED, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + VALIDATING -> Value.VALIDATING + FAILED -> Value.FAILED + IN_PROGRESS -> Value.IN_PROGRESS + FINALIZING -> Value.FINALIZING + COMPLETED -> Value.COMPLETED + EXPIRED -> Value.EXPIRED + CANCELLING -> Value.CANCELLING + CANCELLED -> Value.CANCELLED + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + VALIDATING -> Known.VALIDATING + FAILED -> Known.FAILED + IN_PROGRESS -> Known.IN_PROGRESS + FINALIZING -> Known.FINALIZING + COMPLETED -> Known.COMPLETED + EXPIRED -> Known.EXPIRED + CANCELLING -> Known.CANCELLING + CANCELLED -> Known.CANCELLED + else -> throw OpenAIInvalidDataException("Unknown Status: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + @JsonDeserialize(builder = Errors.Builder::class) + @NoAutoDetect + class Errors + private constructor( + private val object_: JsonField, + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The object type, which is always `list`. */ + fun object_(): Optional = Optional.ofNullable(object_.getNullable("object")) + + fun data(): Optional> = Optional.ofNullable(data.getNullable("data")) + + /** The object type, which is always `list`. */ + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + @JsonProperty("data") @ExcludeMissing fun _data() = data + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Errors = apply { + if (!validated) { + object_() + data().map { it.forEach { it.validate() } } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Errors && + this.object_ == other.object_ && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + object_, + data, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Errors{object_=$object_, data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var object_: JsonField = JsonMissing.of() + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(errors: Errors) = apply { + this.object_ = errors.object_ + this.data = errors.data + additionalProperties(errors.additionalProperties) + } + + /** The object type, which is always `list`. */ + fun object_(object_: String) = object_(JsonField.of(object_)) + + /** The object type, which is always `list`. */ + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + @ExcludeMissing + fun data(data: JsonField>) = apply { this.data = data } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Errors = + Errors( + object_, + data.map { it.toUnmodifiable() }, + additionalProperties.toUnmodifiable(), + ) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchCancelParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchCancelParams.kt new file mode 100644 index 0000000..490e6a2 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchCancelParams.kt @@ -0,0 +1,155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class BatchCancelParams +constructor( + private val batchId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun batchId(): String = batchId + + @JvmSynthetic + internal fun getBody(): Optional> { + return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> batchId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchCancelParams && + this.batchId == other.batchId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + batchId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "BatchCancelParams{batchId=$batchId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var batchId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchCancelParams: BatchCancelParams) = apply { + this.batchId = batchCancelParams.batchId + additionalQueryParams(batchCancelParams.additionalQueryParams) + additionalHeaders(batchCancelParams.additionalHeaders) + additionalBodyProperties(batchCancelParams.additionalBodyProperties) + } + + fun batchId(batchId: String) = apply { this.batchId = batchId } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): BatchCancelParams = + BatchCancelParams( + checkNotNull(batchId) { "`batchId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchCreateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchCreateParams.kt new file mode 100644 index 0000000..864329c --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchCreateParams.kt @@ -0,0 +1,561 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class BatchCreateParams +constructor( + private val completionWindow: CompletionWindow, + private val endpoint: Endpoint, + private val inputFileId: String, + private val metadata: Metadata?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun completionWindow(): CompletionWindow = completionWindow + + fun endpoint(): Endpoint = endpoint + + fun inputFileId(): String = inputFileId + + fun metadata(): Optional = Optional.ofNullable(metadata) + + @JvmSynthetic + internal fun getBody(): BatchCreateBody { + return BatchCreateBody( + completionWindow, + endpoint, + inputFileId, + metadata, + additionalBodyProperties, + ) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + @JsonDeserialize(builder = BatchCreateBody.Builder::class) + @NoAutoDetect + class BatchCreateBody + internal constructor( + private val completionWindow: CompletionWindow?, + private val endpoint: Endpoint?, + private val inputFileId: String?, + private val metadata: Metadata?, + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + /** + * The time frame within which the batch should be processed. Currently only `24h` is + * supported. + */ + @JsonProperty("completion_window") + fun completionWindow(): CompletionWindow? = completionWindow + + /** + * The endpoint to be used for all requests in the batch. Currently `/v1/chat/completions`, + * `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches + * are also restricted to a maximum of 50,000 embedding inputs across all requests in the + * batch. + */ + @JsonProperty("endpoint") fun endpoint(): Endpoint? = endpoint + + /** + * The ID of an uploaded file that contains requests for the new batch. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to + * upload a file. + * + * Your input file must be formatted as a + * [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and + * must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, + * and can be up to 100 MB in size. + */ + @JsonProperty("input_file_id") fun inputFileId(): String? = inputFileId + + /** Optional custom metadata for the batch. */ + @JsonProperty("metadata") fun metadata(): Metadata? = metadata + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchCreateBody && + this.completionWindow == other.completionWindow && + this.endpoint == other.endpoint && + this.inputFileId == other.inputFileId && + this.metadata == other.metadata && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + completionWindow, + endpoint, + inputFileId, + metadata, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "BatchCreateBody{completionWindow=$completionWindow, endpoint=$endpoint, inputFileId=$inputFileId, metadata=$metadata, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var completionWindow: CompletionWindow? = null + private var endpoint: Endpoint? = null + private var inputFileId: String? = null + private var metadata: Metadata? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchCreateBody: BatchCreateBody) = apply { + this.completionWindow = batchCreateBody.completionWindow + this.endpoint = batchCreateBody.endpoint + this.inputFileId = batchCreateBody.inputFileId + this.metadata = batchCreateBody.metadata + additionalProperties(batchCreateBody.additionalProperties) + } + + /** + * The time frame within which the batch should be processed. Currently only `24h` is + * supported. + */ + @JsonProperty("completion_window") + fun completionWindow(completionWindow: CompletionWindow) = apply { + this.completionWindow = completionWindow + } + + /** + * The endpoint to be used for all requests in the batch. Currently + * `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. Note + * that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding + * inputs across all requests in the batch. + */ + @JsonProperty("endpoint") + fun endpoint(endpoint: Endpoint) = apply { this.endpoint = endpoint } + + /** + * The ID of an uploaded file that contains requests for the new batch. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for + * how to upload a file. + * + * Your input file must be formatted as a + * [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and + * must be uploaded with the purpose `batch`. The file can contain up to 50,000 + * requests, and can be up to 100 MB in size. + */ + @JsonProperty("input_file_id") + fun inputFileId(inputFileId: String) = apply { this.inputFileId = inputFileId } + + /** Optional custom metadata for the batch. */ + @JsonProperty("metadata") + fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BatchCreateBody = + BatchCreateBody( + checkNotNull(completionWindow) { + "`completionWindow` is required but was not set" + }, + checkNotNull(endpoint) { "`endpoint` is required but was not set" }, + checkNotNull(inputFileId) { "`inputFileId` is required but was not set" }, + metadata, + additionalProperties.toUnmodifiable(), + ) + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchCreateParams && + this.completionWindow == other.completionWindow && + this.endpoint == other.endpoint && + this.inputFileId == other.inputFileId && + this.metadata == other.metadata && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + completionWindow, + endpoint, + inputFileId, + metadata, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "BatchCreateParams{completionWindow=$completionWindow, endpoint=$endpoint, inputFileId=$inputFileId, metadata=$metadata, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var completionWindow: CompletionWindow? = null + private var endpoint: Endpoint? = null + private var inputFileId: String? = null + private var metadata: Metadata? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchCreateParams: BatchCreateParams) = apply { + this.completionWindow = batchCreateParams.completionWindow + this.endpoint = batchCreateParams.endpoint + this.inputFileId = batchCreateParams.inputFileId + this.metadata = batchCreateParams.metadata + additionalQueryParams(batchCreateParams.additionalQueryParams) + additionalHeaders(batchCreateParams.additionalHeaders) + additionalBodyProperties(batchCreateParams.additionalBodyProperties) + } + + /** + * The time frame within which the batch should be processed. Currently only `24h` is + * supported. + */ + fun completionWindow(completionWindow: CompletionWindow) = apply { + this.completionWindow = completionWindow + } + + /** + * The endpoint to be used for all requests in the batch. Currently `/v1/chat/completions`, + * `/v1/embeddings`, and `/v1/completions` are supported. Note that `/v1/embeddings` batches + * are also restricted to a maximum of 50,000 embedding inputs across all requests in the + * batch. + */ + fun endpoint(endpoint: Endpoint) = apply { this.endpoint = endpoint } + + /** + * The ID of an uploaded file that contains requests for the new batch. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to + * upload a file. + * + * Your input file must be formatted as a + * [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and + * must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, + * and can be up to 100 MB in size. + */ + fun inputFileId(inputFileId: String) = apply { this.inputFileId = inputFileId } + + /** Optional custom metadata for the batch. */ + fun metadata(metadata: Metadata) = apply { this.metadata = metadata } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): BatchCreateParams = + BatchCreateParams( + checkNotNull(completionWindow) { "`completionWindow` is required but was not set" }, + checkNotNull(endpoint) { "`endpoint` is required but was not set" }, + checkNotNull(inputFileId) { "`inputFileId` is required but was not set" }, + metadata, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } + + class CompletionWindow + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CompletionWindow && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val _24H = CompletionWindow(JsonField.of("24h")) + + @JvmStatic fun of(value: String) = CompletionWindow(JsonField.of(value)) + } + + enum class Known { + _24H, + } + + enum class Value { + _24H, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + _24H -> Value._24H + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + _24H -> Known._24H + else -> throw OpenAIInvalidDataException("Unknown CompletionWindow: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + class Endpoint + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Endpoint && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val V1_CHAT_COMPLETIONS = Endpoint(JsonField.of("/v1/chat/completions")) + + @JvmField val V1_EMBEDDINGS = Endpoint(JsonField.of("/v1/embeddings")) + + @JvmField val V1_COMPLETIONS = Endpoint(JsonField.of("/v1/completions")) + + @JvmStatic fun of(value: String) = Endpoint(JsonField.of(value)) + } + + enum class Known { + V1_CHAT_COMPLETIONS, + V1_EMBEDDINGS, + V1_COMPLETIONS, + } + + enum class Value { + V1_CHAT_COMPLETIONS, + V1_EMBEDDINGS, + V1_COMPLETIONS, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + V1_CHAT_COMPLETIONS -> Value.V1_CHAT_COMPLETIONS + V1_EMBEDDINGS -> Value.V1_EMBEDDINGS + V1_COMPLETIONS -> Value.V1_COMPLETIONS + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + V1_CHAT_COMPLETIONS -> Known.V1_CHAT_COMPLETIONS + V1_EMBEDDINGS -> Known.V1_EMBEDDINGS + V1_COMPLETIONS -> Known.V1_COMPLETIONS + else -> throw OpenAIInvalidDataException("Unknown Endpoint: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + /** Optional custom metadata for the batch. */ + @JsonDeserialize(builder = Metadata.Builder::class) + @NoAutoDetect + class Metadata + private constructor( + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = Objects.hash(additionalProperties) + } + return hashCode + } + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties(metadata.additionalProperties) + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchError.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchError.kt new file mode 100644 index 0000000..944d1a9 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchError.kt @@ -0,0 +1,180 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import java.util.Objects +import java.util.Optional + +@JsonDeserialize(builder = BatchError.Builder::class) +@NoAutoDetect +class BatchError +private constructor( + private val code: JsonField, + private val message: JsonField, + private val param: JsonField, + private val line: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** An error code identifying the error type. */ + fun code(): Optional = Optional.ofNullable(code.getNullable("code")) + + /** A human-readable message providing more details about the error. */ + fun message(): Optional = Optional.ofNullable(message.getNullable("message")) + + /** The name of the parameter that caused the error, if applicable. */ + fun param(): Optional = Optional.ofNullable(param.getNullable("param")) + + /** The line number of the input file where the error occurred, if applicable. */ + fun line(): Optional = Optional.ofNullable(line.getNullable("line")) + + /** An error code identifying the error type. */ + @JsonProperty("code") @ExcludeMissing fun _code() = code + + /** A human-readable message providing more details about the error. */ + @JsonProperty("message") @ExcludeMissing fun _message() = message + + /** The name of the parameter that caused the error, if applicable. */ + @JsonProperty("param") @ExcludeMissing fun _param() = param + + /** The line number of the input file where the error occurred, if applicable. */ + @JsonProperty("line") @ExcludeMissing fun _line() = line + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): BatchError = apply { + if (!validated) { + code() + message() + param() + line() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchError && + this.code == other.code && + this.message == other.message && + this.param == other.param && + this.line == other.line && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + code, + message, + param, + line, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "BatchError{code=$code, message=$message, param=$param, line=$line, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var code: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var param: JsonField = JsonMissing.of() + private var line: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchError: BatchError) = apply { + this.code = batchError.code + this.message = batchError.message + this.param = batchError.param + this.line = batchError.line + additionalProperties(batchError.additionalProperties) + } + + /** An error code identifying the error type. */ + fun code(code: String) = code(JsonField.of(code)) + + /** An error code identifying the error type. */ + @JsonProperty("code") + @ExcludeMissing + fun code(code: JsonField) = apply { this.code = code } + + /** A human-readable message providing more details about the error. */ + fun message(message: String) = message(JsonField.of(message)) + + /** A human-readable message providing more details about the error. */ + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + /** The name of the parameter that caused the error, if applicable. */ + fun param(param: String) = param(JsonField.of(param)) + + /** The name of the parameter that caused the error, if applicable. */ + @JsonProperty("param") + @ExcludeMissing + fun param(param: JsonField) = apply { this.param = param } + + /** The line number of the input file where the error occurred, if applicable. */ + fun line(line: Long) = line(JsonField.of(line)) + + /** The line number of the input file where the error occurred, if applicable. */ + @JsonProperty("line") + @ExcludeMissing + fun line(line: JsonField) = apply { this.line = line } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BatchError = + BatchError( + code, + message, + param, + line, + additionalProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchListPage.kt new file mode 100644 index 0000000..1062af7 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchListPage.kt @@ -0,0 +1,179 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.blocking.BatchService +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class BatchListPage +private constructor( + private val batchesService: BatchService, + private val params: BatchListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchListPage && + this.batchesService == other.batchesService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + batchesService, + params, + response, + ) + } + + override fun toString() = + "BatchListPage{batchesService=$batchesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of(BatchListParams.builder().from(params).after(data().last().id()).build()) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { batchesService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(batchesService: BatchService, params: BatchListParams, response: Response) = + BatchListPage( + batchesService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "BatchListPage.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + 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().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchListPageAsync.kt new file mode 100644 index 0000000..5aa0554 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchListPageAsync.kt @@ -0,0 +1,189 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +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 + +class BatchListPageAsync +private constructor( + private val batchesService: BatchServiceAsync, + private val params: BatchListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchListPageAsync && + this.batchesService == other.batchesService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + batchesService, + params, + response, + ) + } + + override fun toString() = + "BatchListPageAsync{batchesService=$batchesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of(BatchListParams.builder().from(params).after(data().last().id()).build()) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { batchesService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(batchesService: BatchServiceAsync, params: BatchListParams, response: Response) = + BatchListPageAsync( + batchesService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "BatchListPageAsync.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + 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 } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchListParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchListParams.kt new file mode 100644 index 0000000..f20038e --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchListParams.kt @@ -0,0 +1,170 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class BatchListParams +constructor( + private val after: String?, + private val limit: Long?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun after(): Optional = Optional.ofNullable(after) + + fun limit(): Optional = Optional.ofNullable(limit) + + @JvmSynthetic + internal fun getQueryParams(): Map> { + val params = mutableMapOf>() + this.after?.let { params.put("after", listOf(it.toString())) } + this.limit?.let { params.put("limit", listOf(it.toString())) } + params.putAll(additionalQueryParams) + return params.toUnmodifiable() + } + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchListParams && + this.after == other.after && + this.limit == other.limit && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + after, + limit, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "BatchListParams{after=$after, limit=$limit, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var after: String? = null + private var limit: Long? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchListParams: BatchListParams) = apply { + this.after = batchListParams.after + this.limit = batchListParams.limit + additionalQueryParams(batchListParams.additionalQueryParams) + additionalHeaders(batchListParams.additionalHeaders) + additionalBodyProperties(batchListParams.additionalBodyProperties) + } + + /** + * A cursor for use in pagination. `after` is an object ID that defines your place in the + * list. For instance, if you make a list request and receive 100 objects, ending with + * obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page + * of the list. + */ + fun after(after: String) = apply { this.after = after } + + /** + * A limit on the number of objects to be returned. Limit can range between 1 and 100, and + * the default is 20. + */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): BatchListParams = + BatchListParams( + after, + limit, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchRequestCounts.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchRequestCounts.kt new file mode 100644 index 0000000..9ca2ae0 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchRequestCounts.kt @@ -0,0 +1,159 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import java.util.Objects + +/** The request counts for different statuses within the batch. */ +@JsonDeserialize(builder = BatchRequestCounts.Builder::class) +@NoAutoDetect +class BatchRequestCounts +private constructor( + private val total: JsonField, + private val completed: JsonField, + private val failed: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** Total number of requests in the batch. */ + fun total(): Long = total.getRequired("total") + + /** Number of requests that have been completed successfully. */ + fun completed(): Long = completed.getRequired("completed") + + /** Number of requests that have failed. */ + fun failed(): Long = failed.getRequired("failed") + + /** Total number of requests in the batch. */ + @JsonProperty("total") @ExcludeMissing fun _total() = total + + /** Number of requests that have been completed successfully. */ + @JsonProperty("completed") @ExcludeMissing fun _completed() = completed + + /** Number of requests that have failed. */ + @JsonProperty("failed") @ExcludeMissing fun _failed() = failed + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): BatchRequestCounts = apply { + if (!validated) { + total() + completed() + failed() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchRequestCounts && + this.total == other.total && + this.completed == other.completed && + this.failed == other.failed && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + total, + completed, + failed, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "BatchRequestCounts{total=$total, completed=$completed, failed=$failed, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var total: JsonField = JsonMissing.of() + private var completed: JsonField = JsonMissing.of() + private var failed: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchRequestCounts: BatchRequestCounts) = apply { + this.total = batchRequestCounts.total + this.completed = batchRequestCounts.completed + this.failed = batchRequestCounts.failed + additionalProperties(batchRequestCounts.additionalProperties) + } + + /** Total number of requests in the batch. */ + fun total(total: Long) = total(JsonField.of(total)) + + /** Total number of requests in the batch. */ + @JsonProperty("total") + @ExcludeMissing + fun total(total: JsonField) = apply { this.total = total } + + /** Number of requests that have been completed successfully. */ + fun completed(completed: Long) = completed(JsonField.of(completed)) + + /** Number of requests that have been completed successfully. */ + @JsonProperty("completed") + @ExcludeMissing + fun completed(completed: JsonField) = apply { this.completed = completed } + + /** Number of requests that have failed. */ + fun failed(failed: Long) = failed(JsonField.of(failed)) + + /** Number of requests that have failed. */ + @JsonProperty("failed") + @ExcludeMissing + fun failed(failed: JsonField) = apply { this.failed = failed } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): BatchRequestCounts = + BatchRequestCounts( + total, + completed, + failed, + additionalProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/BatchRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/BatchRetrieveParams.kt new file mode 100644 index 0000000..ddcbd9f --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/BatchRetrieveParams.kt @@ -0,0 +1,149 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects + +class BatchRetrieveParams +constructor( + private val batchId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun batchId(): String = batchId + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> batchId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchRetrieveParams && + this.batchId == other.batchId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + batchId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "BatchRetrieveParams{batchId=$batchId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var batchId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(batchRetrieveParams: BatchRetrieveParams) = apply { + this.batchId = batchRetrieveParams.batchId + additionalQueryParams(batchRetrieveParams.additionalQueryParams) + additionalHeaders(batchRetrieveParams.additionalHeaders) + additionalBodyProperties(batchRetrieveParams.additionalBodyProperties) + } + + fun batchId(batchId: String) = apply { this.batchId = batchId } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): BatchRetrieveParams = + BatchRetrieveParams( + checkNotNull(batchId) { "`batchId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileContentParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileContentParams.kt new file mode 100644 index 0000000..b9e4c74 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileContentParams.kt @@ -0,0 +1,149 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects + +class FileContentParams +constructor( + private val fileId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fileId(): String = fileId + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fileId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileContentParams && + this.fileId == other.fileId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fileId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FileContentParams{fileId=$fileId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fileId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileContentParams: FileContentParams) = apply { + this.fileId = fileContentParams.fileId + additionalQueryParams(fileContentParams.additionalQueryParams) + additionalHeaders(fileContentParams.additionalHeaders) + additionalBodyProperties(fileContentParams.additionalBodyProperties) + } + + fun fileId(fileId: String) = apply { this.fileId = fileId } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FileContentParams = + FileContentParams( + checkNotNull(fileId) { "`fileId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileCreateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileCreateParams.kt new file mode 100644 index 0000000..bc0c34f --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileCreateParams.kt @@ -0,0 +1,310 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ContentTypes +import com.openai.core.Enum +import com.openai.core.JsonField +import com.openai.core.JsonValue +import com.openai.core.MultipartFormValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import com.openai.models.* +import java.util.Objects +import org.apache.hc.core5.http.ContentType + +class FileCreateParams +constructor( + private val file: MultipartFormValue, + private val purpose: MultipartFormValue, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, +) { + + fun file(): MultipartFormValue = file + + fun purpose(): MultipartFormValue = purpose + + @JvmSynthetic + internal fun getBody(): Array?> { + return arrayOf(file, purpose) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + @JsonDeserialize(builder = FileCreateBody.Builder::class) + @NoAutoDetect + class FileCreateBody + internal constructor( + private val file: ByteArray?, + private val purpose: Purpose?, + ) { + + private var hashCode: Int = 0 + + /** The File object (not file name) to be uploaded. */ + fun file(): ByteArray? = file + + /** + * The intended purpose of the uploaded file. + * + * Use "assistants" for + * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + * [Message](https://platform.openai.com/docs/api-reference/messages) files, "vision" for + * Assistants image file inputs, "batch" for + * [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for + * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). + */ + fun purpose(): Purpose? = purpose + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileCreateBody && + this.file == other.file && + this.purpose == other.purpose + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = Objects.hash(file, purpose) + } + return hashCode + } + + override fun toString() = "FileCreateBody{file=$file, purpose=$purpose}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var file: ByteArray? = null + private var purpose: Purpose? = null + + @JvmSynthetic + internal fun from(fileCreateBody: FileCreateBody) = apply { + this.file = fileCreateBody.file + this.purpose = fileCreateBody.purpose + } + + /** The File object (not file name) to be uploaded. */ + fun file(file: ByteArray) = apply { this.file = file } + + /** + * The intended purpose of the uploaded file. + * + * Use "assistants" for + * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + * [Message](https://platform.openai.com/docs/api-reference/messages) files, "vision" + * for Assistants image file inputs, "batch" for + * [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for + * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). + */ + fun purpose(purpose: Purpose) = apply { this.purpose = purpose } + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileCreateParams && + this.file == other.file && + this.purpose == other.purpose && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders + } + + override fun hashCode(): Int { + return Objects.hash( + file, + purpose, + additionalQueryParams, + additionalHeaders, + ) + } + + override fun toString() = + "FileCreateParams{file=$file, purpose=$purpose, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var file: MultipartFormValue? = null + private var purpose: MultipartFormValue? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + + @JvmSynthetic + internal fun from(fileCreateParams: FileCreateParams) = apply { + this.file = fileCreateParams.file + this.purpose = fileCreateParams.purpose + additionalQueryParams(fileCreateParams.additionalQueryParams) + additionalHeaders(fileCreateParams.additionalHeaders) + } + + /** The File object (not file name) to be uploaded. */ + fun file( + content: ByteArray, + filename: String? = null, + contentType: ContentType = ContentTypes.DefaultBinary + ) = apply { + this.file = MultipartFormValue.fromByteArray("file", content, contentType, filename) + } + + /** + * The intended purpose of the uploaded file. + * + * Use "assistants" for + * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + * [Message](https://platform.openai.com/docs/api-reference/messages) files, "vision" for + * Assistants image file inputs, "batch" for + * [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for + * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). + */ + fun purpose(purpose: Purpose, contentType: ContentType = ContentTypes.DefaultText) = apply { + this.purpose = MultipartFormValue.fromEnum("purpose", purpose, contentType) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun build(): FileCreateParams = + FileCreateParams( + checkNotNull(file) { "`file` is required but was not set" }, + checkNotNull(purpose) { "`purpose` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + ) + } + + class Purpose + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Purpose && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val ASSISTANTS = Purpose(JsonField.of("assistants")) + + @JvmField val BATCH = Purpose(JsonField.of("batch")) + + @JvmField val FINE_TUNE = Purpose(JsonField.of("fine-tune")) + + @JvmField val VISION = Purpose(JsonField.of("vision")) + + @JvmStatic fun of(value: String) = Purpose(JsonField.of(value)) + } + + enum class Known { + ASSISTANTS, + BATCH, + FINE_TUNE, + VISION, + } + + enum class Value { + ASSISTANTS, + BATCH, + FINE_TUNE, + VISION, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + ASSISTANTS -> Value.ASSISTANTS + BATCH -> Value.BATCH + FINE_TUNE -> Value.FINE_TUNE + VISION -> Value.VISION + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + ASSISTANTS -> Known.ASSISTANTS + BATCH -> Known.BATCH + FINE_TUNE -> Known.FINE_TUNE + VISION -> Known.VISION + else -> throw OpenAIInvalidDataException("Unknown Purpose: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileDeleteParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileDeleteParams.kt new file mode 100644 index 0000000..1b4e10c --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileDeleteParams.kt @@ -0,0 +1,155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FileDeleteParams +constructor( + private val fileId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fileId(): String = fileId + + @JvmSynthetic + internal fun getBody(): Optional> { + return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fileId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileDeleteParams && + this.fileId == other.fileId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fileId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FileDeleteParams{fileId=$fileId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fileId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileDeleteParams: FileDeleteParams) = apply { + this.fileId = fileDeleteParams.fileId + additionalQueryParams(fileDeleteParams.additionalQueryParams) + additionalHeaders(fileDeleteParams.additionalHeaders) + additionalBodyProperties(fileDeleteParams.additionalBodyProperties) + } + + fun fileId(fileId: String) = apply { this.fileId = fileId } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FileDeleteParams = + FileDeleteParams( + checkNotNull(fileId) { "`fileId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileDeleted.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileDeleted.kt new file mode 100644 index 0000000..86585b2 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileDeleted.kt @@ -0,0 +1,198 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects + +@JsonDeserialize(builder = FileDeleted.Builder::class) +@NoAutoDetect +class FileDeleted +private constructor( + private val id: JsonField, + private val object_: JsonField, + private val deleted: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + fun id(): String = id.getRequired("id") + + fun object_(): Object = object_.getRequired("object") + + fun deleted(): Boolean = deleted.getRequired("deleted") + + @JsonProperty("id") @ExcludeMissing fun _id() = id + + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + @JsonProperty("deleted") @ExcludeMissing fun _deleted() = deleted + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FileDeleted = apply { + if (!validated) { + id() + object_() + deleted() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileDeleted && + this.id == other.id && + this.object_ == other.object_ && + this.deleted == other.deleted && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + object_, + deleted, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FileDeleted{id=$id, object_=$object_, deleted=$deleted, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var deleted: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileDeleted: FileDeleted) = apply { + this.id = fileDeleted.id + this.object_ = fileDeleted.object_ + this.deleted = fileDeleted.deleted + additionalProperties(fileDeleted.additionalProperties) + } + + fun id(id: String) = id(JsonField.of(id)) + + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + fun object_(object_: Object) = object_(JsonField.of(object_)) + + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun deleted(deleted: Boolean) = deleted(JsonField.of(deleted)) + + @JsonProperty("deleted") + @ExcludeMissing + fun deleted(deleted: JsonField) = apply { this.deleted = deleted } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FileDeleted = + FileDeleted( + id, + object_, + deleted, + additionalProperties.toUnmodifiable(), + ) + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val FILE = Object(JsonField.of("file")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + FILE, + } + + enum class Value { + FILE, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + FILE -> Value.FILE + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + FILE -> Known.FILE + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileListPage.kt new file mode 100644 index 0000000..aef6b87 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileListPage.kt @@ -0,0 +1,201 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.blocking.FileService +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class FileListPage +private constructor( + private val filesService: FileService, + private val params: FileListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun object_(): String = response().object_() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileListPage && + this.filesService == other.filesService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + filesService, + params, + response, + ) + } + + override fun toString() = + "FileListPage{filesService=$filesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): Optional { + return getNextPageParams().map { filesService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(filesService: FileService, params: FileListParams, response: Response) = + FileListPage( + filesService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val object_: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun object_(): String = object_.getRequired("object") + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("object") + fun _object_(): Optional> = Optional.ofNullable(object_) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash( + data, + object_, + additionalProperties, + ) + } + + override fun toString() = + "FileListPage.Response{data=$data, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.object_ = page.object_ + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun object_(object_: String) = object_(JsonField.of(object_)) + + @JsonProperty("object") + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + object_, + additionalProperties.toUnmodifiable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: FileListPage, + ) : 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().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileListPageAsync.kt new file mode 100644 index 0000000..5218914 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileListPageAsync.kt @@ -0,0 +1,211 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.async.FileServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class FileListPageAsync +private constructor( + private val filesService: FileServiceAsync, + private val params: FileListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun object_(): String = response().object_() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileListPageAsync && + this.filesService == other.filesService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + filesService, + params, + response, + ) + } + + override fun toString() = + "FileListPageAsync{filesService=$filesService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { filesService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(filesService: FileServiceAsync, params: FileListParams, response: Response) = + FileListPageAsync( + filesService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val object_: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun object_(): String = object_.getRequired("object") + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("object") + fun _object_(): Optional> = Optional.ofNullable(object_) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash( + data, + object_, + additionalProperties, + ) + } + + override fun toString() = + "FileListPageAsync.Response{data=$data, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.object_ = page.object_ + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun object_(object_: String) = object_(JsonField.of(object_)) + + @JsonProperty("object") + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + object_, + additionalProperties.toUnmodifiable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: FileListPageAsync, + ) { + + fun forEach(action: Predicate, executor: Executor): CompletableFuture { + fun CompletableFuture>.forEach( + action: (FileObject) -> 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 } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileListParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileListParams.kt new file mode 100644 index 0000000..4530364 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileListParams.kt @@ -0,0 +1,150 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FileListParams +constructor( + private val purpose: String?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun purpose(): Optional = Optional.ofNullable(purpose) + + @JvmSynthetic + internal fun getQueryParams(): Map> { + val params = mutableMapOf>() + this.purpose?.let { params.put("purpose", listOf(it.toString())) } + params.putAll(additionalQueryParams) + return params.toUnmodifiable() + } + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileListParams && + this.purpose == other.purpose && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + purpose, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FileListParams{purpose=$purpose, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var purpose: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileListParams: FileListParams) = apply { + this.purpose = fileListParams.purpose + additionalQueryParams(fileListParams.additionalQueryParams) + additionalHeaders(fileListParams.additionalHeaders) + additionalBodyProperties(fileListParams.additionalBodyProperties) + } + + /** Only return files with the given purpose. */ + fun purpose(purpose: String) = apply { this.purpose = purpose } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FileListParams = + FileListParams( + purpose, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileObject.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileObject.kt new file mode 100644 index 0000000..8eea382 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileObject.kt @@ -0,0 +1,506 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects +import java.util.Optional + +/** The `File` object represents a document that has been uploaded to OpenAI. */ +@JsonDeserialize(builder = FileObject.Builder::class) +@NoAutoDetect +class FileObject +private constructor( + private val id: JsonField, + private val bytes: JsonField, + private val createdAt: JsonField, + private val filename: JsonField, + private val object_: JsonField, + private val purpose: JsonField, + private val status: JsonField, + private val statusDetails: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The file identifier, which can be referenced in the API endpoints. */ + fun id(): String = id.getRequired("id") + + /** The size of the file, in bytes. */ + fun bytes(): Long = bytes.getRequired("bytes") + + /** The Unix timestamp (in seconds) for when the file was created. */ + fun createdAt(): Long = createdAt.getRequired("created_at") + + /** The name of the file. */ + fun filename(): String = filename.getRequired("filename") + + /** The object type, which is always `file`. */ + fun object_(): Object = object_.getRequired("object") + + /** + * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, + * `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. + */ + fun purpose(): Purpose = purpose.getRequired("purpose") + + /** + * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or + * `error`. + */ + fun status(): Status = status.getRequired("status") + + /** + * Deprecated. For details on why a fine-tuning training file failed validation, see the `error` + * field on `fine_tuning.job`. + */ + fun statusDetails(): Optional = + Optional.ofNullable(statusDetails.getNullable("status_details")) + + /** The file identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** The size of the file, in bytes. */ + @JsonProperty("bytes") @ExcludeMissing fun _bytes() = bytes + + /** The Unix timestamp (in seconds) for when the file was created. */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + /** The name of the file. */ + @JsonProperty("filename") @ExcludeMissing fun _filename() = filename + + /** The object type, which is always `file`. */ + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + /** + * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, + * `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. + */ + @JsonProperty("purpose") @ExcludeMissing fun _purpose() = purpose + + /** + * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or + * `error`. + */ + @JsonProperty("status") @ExcludeMissing fun _status() = status + + /** + * Deprecated. For details on why a fine-tuning training file failed validation, see the `error` + * field on `fine_tuning.job`. + */ + @JsonProperty("status_details") @ExcludeMissing fun _statusDetails() = statusDetails + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FileObject = apply { + if (!validated) { + id() + bytes() + createdAt() + filename() + object_() + purpose() + status() + statusDetails() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileObject && + this.id == other.id && + this.bytes == other.bytes && + this.createdAt == other.createdAt && + this.filename == other.filename && + this.object_ == other.object_ && + this.purpose == other.purpose && + this.status == other.status && + this.statusDetails == other.statusDetails && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + bytes, + createdAt, + filename, + object_, + purpose, + status, + statusDetails, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FileObject{id=$id, bytes=$bytes, createdAt=$createdAt, filename=$filename, object_=$object_, purpose=$purpose, status=$status, statusDetails=$statusDetails, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var bytes: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var filename: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var purpose: JsonField = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var statusDetails: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileObject: FileObject) = apply { + this.id = fileObject.id + this.bytes = fileObject.bytes + this.createdAt = fileObject.createdAt + this.filename = fileObject.filename + this.object_ = fileObject.object_ + this.purpose = fileObject.purpose + this.status = fileObject.status + this.statusDetails = fileObject.statusDetails + additionalProperties(fileObject.additionalProperties) + } + + /** The file identifier, which can be referenced in the API endpoints. */ + fun id(id: String) = id(JsonField.of(id)) + + /** The file identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** The size of the file, in bytes. */ + fun bytes(bytes: Long) = bytes(JsonField.of(bytes)) + + /** The size of the file, in bytes. */ + @JsonProperty("bytes") + @ExcludeMissing + fun bytes(bytes: JsonField) = apply { this.bytes = bytes } + + /** The Unix timestamp (in seconds) for when the file was created. */ + fun createdAt(createdAt: Long) = createdAt(JsonField.of(createdAt)) + + /** The Unix timestamp (in seconds) for when the file was created. */ + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** The name of the file. */ + fun filename(filename: String) = filename(JsonField.of(filename)) + + /** The name of the file. */ + @JsonProperty("filename") + @ExcludeMissing + fun filename(filename: JsonField) = apply { this.filename = filename } + + /** The object type, which is always `file`. */ + fun object_(object_: Object) = object_(JsonField.of(object_)) + + /** The object type, which is always `file`. */ + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + /** + * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, + * `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. + */ + fun purpose(purpose: Purpose) = purpose(JsonField.of(purpose)) + + /** + * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, + * `batch`, `batch_output`, `fine-tune`, `fine-tune-results` and `vision`. + */ + @JsonProperty("purpose") + @ExcludeMissing + fun purpose(purpose: JsonField) = apply { this.purpose = purpose } + + /** + * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, + * or `error`. + */ + fun status(status: Status) = status(JsonField.of(status)) + + /** + * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, + * or `error`. + */ + @JsonProperty("status") + @ExcludeMissing + fun status(status: JsonField) = apply { this.status = status } + + /** + * Deprecated. For details on why a fine-tuning training file failed validation, see the + * `error` field on `fine_tuning.job`. + */ + fun statusDetails(statusDetails: String) = statusDetails(JsonField.of(statusDetails)) + + /** + * Deprecated. For details on why a fine-tuning training file failed validation, see the + * `error` field on `fine_tuning.job`. + */ + @JsonProperty("status_details") + @ExcludeMissing + fun statusDetails(statusDetails: JsonField) = apply { + this.statusDetails = statusDetails + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FileObject = + FileObject( + id, + bytes, + createdAt, + filename, + object_, + purpose, + status, + statusDetails, + additionalProperties.toUnmodifiable(), + ) + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val FILE = Object(JsonField.of("file")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + FILE, + } + + enum class Value { + FILE, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + FILE -> Value.FILE + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + FILE -> Known.FILE + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + class Purpose + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Purpose && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val ASSISTANTS = Purpose(JsonField.of("assistants")) + + @JvmField val ASSISTANTS_OUTPUT = Purpose(JsonField.of("assistants_output")) + + @JvmField val BATCH = Purpose(JsonField.of("batch")) + + @JvmField val BATCH_OUTPUT = Purpose(JsonField.of("batch_output")) + + @JvmField val FINE_TUNE = Purpose(JsonField.of("fine-tune")) + + @JvmField val FINE_TUNE_RESULTS = Purpose(JsonField.of("fine-tune-results")) + + @JvmField val VISION = Purpose(JsonField.of("vision")) + + @JvmStatic fun of(value: String) = Purpose(JsonField.of(value)) + } + + enum class Known { + ASSISTANTS, + ASSISTANTS_OUTPUT, + BATCH, + BATCH_OUTPUT, + FINE_TUNE, + FINE_TUNE_RESULTS, + VISION, + } + + enum class Value { + ASSISTANTS, + ASSISTANTS_OUTPUT, + BATCH, + BATCH_OUTPUT, + FINE_TUNE, + FINE_TUNE_RESULTS, + VISION, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + ASSISTANTS -> Value.ASSISTANTS + ASSISTANTS_OUTPUT -> Value.ASSISTANTS_OUTPUT + BATCH -> Value.BATCH + BATCH_OUTPUT -> Value.BATCH_OUTPUT + FINE_TUNE -> Value.FINE_TUNE + FINE_TUNE_RESULTS -> Value.FINE_TUNE_RESULTS + VISION -> Value.VISION + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + ASSISTANTS -> Known.ASSISTANTS + ASSISTANTS_OUTPUT -> Known.ASSISTANTS_OUTPUT + BATCH -> Known.BATCH + BATCH_OUTPUT -> Known.BATCH_OUTPUT + FINE_TUNE -> Known.FINE_TUNE + FINE_TUNE_RESULTS -> Known.FINE_TUNE_RESULTS + VISION -> Known.VISION + else -> throw OpenAIInvalidDataException("Unknown Purpose: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + class Status + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Status && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val UPLOADED = Status(JsonField.of("uploaded")) + + @JvmField val PROCESSED = Status(JsonField.of("processed")) + + @JvmField val ERROR = Status(JsonField.of("error")) + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + enum class Known { + UPLOADED, + PROCESSED, + ERROR, + } + + enum class Value { + UPLOADED, + PROCESSED, + ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + UPLOADED -> Value.UPLOADED + PROCESSED -> Value.PROCESSED + ERROR -> Value.ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + UPLOADED -> Known.UPLOADED + PROCESSED -> Known.PROCESSED + ERROR -> Known.ERROR + else -> throw OpenAIInvalidDataException("Unknown Status: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FileRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FileRetrieveParams.kt new file mode 100644 index 0000000..d8373d6 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FileRetrieveParams.kt @@ -0,0 +1,149 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects + +class FileRetrieveParams +constructor( + private val fileId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fileId(): String = fileId + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fileId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FileRetrieveParams && + this.fileId == other.fileId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fileId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FileRetrieveParams{fileId=$fileId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fileId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fileRetrieveParams: FileRetrieveParams) = apply { + this.fileId = fileRetrieveParams.fileId + additionalQueryParams(fileRetrieveParams.additionalQueryParams) + additionalHeaders(fileRetrieveParams.additionalHeaders) + additionalBodyProperties(fileRetrieveParams.additionalBodyProperties) + } + + fun fileId(fileId: String) = apply { this.fileId = fileId } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FileRetrieveParams = + FileRetrieveParams( + checkNotNull(fileId) { "`fileId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJob.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJob.kt new file mode 100644 index 0000000..bd0de8d --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJob.kt @@ -0,0 +1,1194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.openai.core.BaseDeserializer +import com.openai.core.BaseSerializer +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.getOrThrow +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects +import java.util.Optional + +/** + * The `fine_tuning.job` object represents a fine-tuning job that has been created through the API. + */ +@JsonDeserialize(builder = FineTuningJob.Builder::class) +@NoAutoDetect +class FineTuningJob +private constructor( + private val id: JsonField, + private val createdAt: JsonField, + private val error: JsonField, + private val fineTunedModel: JsonField, + private val finishedAt: JsonField, + private val hyperparameters: JsonField, + private val model: JsonField, + private val object_: JsonField, + private val organizationId: JsonField, + private val resultFiles: JsonField>, + private val status: JsonField, + private val trainedTokens: JsonField, + private val trainingFile: JsonField, + private val validationFile: JsonField, + private val integrations: JsonField>, + private val seed: JsonField, + private val estimatedFinish: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The object identifier, which can be referenced in the API endpoints. */ + fun id(): String = id.getRequired("id") + + /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ + fun createdAt(): Long = createdAt.getRequired("created_at") + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on the cause of + * the failure. + */ + fun error(): Optional = Optional.ofNullable(error.getNullable("error")) + + /** + * The name of the fine-tuned model that is being created. The value will be null if the + * fine-tuning job is still running. + */ + fun fineTunedModel(): Optional = + Optional.ofNullable(fineTunedModel.getNullable("fine_tuned_model")) + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be + * null if the fine-tuning job is still running. + */ + fun finishedAt(): Optional = Optional.ofNullable(finishedAt.getNullable("finished_at")) + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. + */ + fun hyperparameters(): Hyperparameters = hyperparameters.getRequired("hyperparameters") + + /** The base model that is being fine-tuned. */ + fun model(): String = model.getRequired("model") + + /** The object type, which is always "fine_tuning.job". */ + fun object_(): Object = object_.getRequired("object") + + /** The organization that owns the fine-tuning job. */ + fun organizationId(): String = organizationId.getRequired("organization_id") + + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with + * the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + fun resultFiles(): List = resultFiles.getRequired("result_files") + + /** + * The current status of the fine-tuning job, which can be either `validating_files`, `queued`, + * `running`, `succeeded`, `failed`, or `cancelled`. + */ + fun status(): Status = status.getRequired("status") + + /** + * The total number of billable tokens processed by this fine-tuning job. The value will be null + * if the fine-tuning job is still running. + */ + fun trainedTokens(): Optional = + Optional.ofNullable(trainedTokens.getNullable("trained_tokens")) + + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + fun trainingFile(): String = trainingFile.getRequired("training_file") + + /** + * The file ID used for validation. You can retrieve the validation results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + fun validationFile(): Optional = + Optional.ofNullable(validationFile.getNullable("validation_file")) + + /** A list of integrations to enable for this fine-tuning job. */ + fun integrations(): Optional> = + Optional.ofNullable(integrations.getNullable("integrations")) + + /** The seed used for the fine-tuning job. */ + fun seed(): Long = seed.getRequired("seed") + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The + * value will be null if the fine-tuning job is not running. + */ + fun estimatedFinish(): Optional = + Optional.ofNullable(estimatedFinish.getNullable("estimated_finish")) + + /** The object identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on the cause of + * the failure. + */ + @JsonProperty("error") @ExcludeMissing fun _error() = error + + /** + * The name of the fine-tuned model that is being created. The value will be null if the + * fine-tuning job is still running. + */ + @JsonProperty("fine_tuned_model") @ExcludeMissing fun _fineTunedModel() = fineTunedModel + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be + * null if the fine-tuning job is still running. + */ + @JsonProperty("finished_at") @ExcludeMissing fun _finishedAt() = finishedAt + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. + */ + @JsonProperty("hyperparameters") @ExcludeMissing fun _hyperparameters() = hyperparameters + + /** The base model that is being fine-tuned. */ + @JsonProperty("model") @ExcludeMissing fun _model() = model + + /** The object type, which is always "fine_tuning.job". */ + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + /** The organization that owns the fine-tuning job. */ + @JsonProperty("organization_id") @ExcludeMissing fun _organizationId() = organizationId + + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with + * the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + @JsonProperty("result_files") @ExcludeMissing fun _resultFiles() = resultFiles + + /** + * The current status of the fine-tuning job, which can be either `validating_files`, `queued`, + * `running`, `succeeded`, `failed`, or `cancelled`. + */ + @JsonProperty("status") @ExcludeMissing fun _status() = status + + /** + * The total number of billable tokens processed by this fine-tuning job. The value will be null + * if the fine-tuning job is still running. + */ + @JsonProperty("trained_tokens") @ExcludeMissing fun _trainedTokens() = trainedTokens + + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + @JsonProperty("training_file") @ExcludeMissing fun _trainingFile() = trainingFile + + /** + * The file ID used for validation. You can retrieve the validation results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + @JsonProperty("validation_file") @ExcludeMissing fun _validationFile() = validationFile + + /** A list of integrations to enable for this fine-tuning job. */ + @JsonProperty("integrations") @ExcludeMissing fun _integrations() = integrations + + /** The seed used for the fine-tuning job. */ + @JsonProperty("seed") @ExcludeMissing fun _seed() = seed + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The + * value will be null if the fine-tuning job is not running. + */ + @JsonProperty("estimated_finish") @ExcludeMissing fun _estimatedFinish() = estimatedFinish + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FineTuningJob = apply { + if (!validated) { + id() + createdAt() + error().map { it.validate() } + fineTunedModel() + finishedAt() + hyperparameters().validate() + model() + object_() + organizationId() + resultFiles() + status() + trainedTokens() + trainingFile() + validationFile() + integrations().map { it.forEach { it.validate() } } + seed() + estimatedFinish() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJob && + this.id == other.id && + this.createdAt == other.createdAt && + this.error == other.error && + this.fineTunedModel == other.fineTunedModel && + this.finishedAt == other.finishedAt && + this.hyperparameters == other.hyperparameters && + this.model == other.model && + this.object_ == other.object_ && + this.organizationId == other.organizationId && + this.resultFiles == other.resultFiles && + this.status == other.status && + this.trainedTokens == other.trainedTokens && + this.trainingFile == other.trainingFile && + this.validationFile == other.validationFile && + this.integrations == other.integrations && + this.seed == other.seed && + this.estimatedFinish == other.estimatedFinish && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + createdAt, + error, + fineTunedModel, + finishedAt, + hyperparameters, + model, + object_, + organizationId, + resultFiles, + status, + trainedTokens, + trainingFile, + validationFile, + integrations, + seed, + estimatedFinish, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FineTuningJob{id=$id, createdAt=$createdAt, error=$error, fineTunedModel=$fineTunedModel, finishedAt=$finishedAt, hyperparameters=$hyperparameters, model=$model, object_=$object_, organizationId=$organizationId, resultFiles=$resultFiles, status=$status, trainedTokens=$trainedTokens, trainingFile=$trainingFile, validationFile=$validationFile, integrations=$integrations, seed=$seed, estimatedFinish=$estimatedFinish, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var error: JsonField = JsonMissing.of() + private var fineTunedModel: JsonField = JsonMissing.of() + private var finishedAt: JsonField = JsonMissing.of() + private var hyperparameters: JsonField = JsonMissing.of() + private var model: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var organizationId: JsonField = JsonMissing.of() + private var resultFiles: JsonField> = JsonMissing.of() + private var status: JsonField = JsonMissing.of() + private var trainedTokens: JsonField = JsonMissing.of() + private var trainingFile: JsonField = JsonMissing.of() + private var validationFile: JsonField = JsonMissing.of() + private var integrations: JsonField> = + JsonMissing.of() + private var seed: JsonField = JsonMissing.of() + private var estimatedFinish: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJob: FineTuningJob) = apply { + this.id = fineTuningJob.id + this.createdAt = fineTuningJob.createdAt + this.error = fineTuningJob.error + this.fineTunedModel = fineTuningJob.fineTunedModel + this.finishedAt = fineTuningJob.finishedAt + this.hyperparameters = fineTuningJob.hyperparameters + this.model = fineTuningJob.model + this.object_ = fineTuningJob.object_ + this.organizationId = fineTuningJob.organizationId + this.resultFiles = fineTuningJob.resultFiles + this.status = fineTuningJob.status + this.trainedTokens = fineTuningJob.trainedTokens + this.trainingFile = fineTuningJob.trainingFile + this.validationFile = fineTuningJob.validationFile + this.integrations = fineTuningJob.integrations + this.seed = fineTuningJob.seed + this.estimatedFinish = fineTuningJob.estimatedFinish + additionalProperties(fineTuningJob.additionalProperties) + } + + /** The object identifier, which can be referenced in the API endpoints. */ + fun id(id: String) = id(JsonField.of(id)) + + /** The object identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ + fun createdAt(createdAt: Long) = createdAt(JsonField.of(createdAt)) + + /** The Unix timestamp (in seconds) for when the fine-tuning job was created. */ + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on the cause + * of the failure. + */ + fun error(error: Error) = error(JsonField.of(error)) + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on the cause + * of the failure. + */ + @JsonProperty("error") + @ExcludeMissing + fun error(error: JsonField) = apply { this.error = error } + + /** + * The name of the fine-tuned model that is being created. The value will be null if the + * fine-tuning job is still running. + */ + fun fineTunedModel(fineTunedModel: String) = fineTunedModel(JsonField.of(fineTunedModel)) + + /** + * The name of the fine-tuned model that is being created. The value will be null if the + * fine-tuning job is still running. + */ + @JsonProperty("fine_tuned_model") + @ExcludeMissing + fun fineTunedModel(fineTunedModel: JsonField) = apply { + this.fineTunedModel = fineTunedModel + } + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will + * be null if the fine-tuning job is still running. + */ + fun finishedAt(finishedAt: Long) = finishedAt(JsonField.of(finishedAt)) + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will + * be null if the fine-tuning job is still running. + */ + @JsonProperty("finished_at") + @ExcludeMissing + fun finishedAt(finishedAt: JsonField) = apply { this.finishedAt = finishedAt } + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more + * details. + */ + fun hyperparameters(hyperparameters: Hyperparameters) = + hyperparameters(JsonField.of(hyperparameters)) + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more + * details. + */ + @JsonProperty("hyperparameters") + @ExcludeMissing + fun hyperparameters(hyperparameters: JsonField) = apply { + this.hyperparameters = hyperparameters + } + + /** The base model that is being fine-tuned. */ + fun model(model: String) = model(JsonField.of(model)) + + /** The base model that is being fine-tuned. */ + @JsonProperty("model") + @ExcludeMissing + fun model(model: JsonField) = apply { this.model = model } + + /** The object type, which is always "fine_tuning.job". */ + fun object_(object_: Object) = object_(JsonField.of(object_)) + + /** The object type, which is always "fine_tuning.job". */ + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + /** The organization that owns the fine-tuning job. */ + fun organizationId(organizationId: String) = organizationId(JsonField.of(organizationId)) + + /** The organization that owns the fine-tuning job. */ + @JsonProperty("organization_id") + @ExcludeMissing + fun organizationId(organizationId: JsonField) = apply { + this.organizationId = organizationId + } + + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results + * with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + fun resultFiles(resultFiles: List) = resultFiles(JsonField.of(resultFiles)) + + /** + * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results + * with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + @JsonProperty("result_files") + @ExcludeMissing + fun resultFiles(resultFiles: JsonField>) = apply { + this.resultFiles = resultFiles + } + + /** + * The current status of the fine-tuning job, which can be either `validating_files`, + * `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + fun status(status: Status) = status(JsonField.of(status)) + + /** + * The current status of the fine-tuning job, which can be either `validating_files`, + * `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + */ + @JsonProperty("status") + @ExcludeMissing + fun status(status: JsonField) = apply { this.status = status } + + /** + * The total number of billable tokens processed by this fine-tuning job. The value will be + * null if the fine-tuning job is still running. + */ + fun trainedTokens(trainedTokens: Long) = trainedTokens(JsonField.of(trainedTokens)) + + /** + * The total number of billable tokens processed by this fine-tuning job. The value will be + * null if the fine-tuning job is still running. + */ + @JsonProperty("trained_tokens") + @ExcludeMissing + fun trainedTokens(trainedTokens: JsonField) = apply { + this.trainedTokens = trainedTokens + } + + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + fun trainingFile(trainingFile: String) = trainingFile(JsonField.of(trainingFile)) + + /** + * The file ID used for training. You can retrieve the training data with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + @JsonProperty("training_file") + @ExcludeMissing + fun trainingFile(trainingFile: JsonField) = apply { + this.trainingFile = trainingFile + } + + /** + * The file ID used for validation. You can retrieve the validation results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + fun validationFile(validationFile: String) = validationFile(JsonField.of(validationFile)) + + /** + * The file ID used for validation. You can retrieve the validation results with the + * [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + */ + @JsonProperty("validation_file") + @ExcludeMissing + fun validationFile(validationFile: JsonField) = apply { + this.validationFile = validationFile + } + + /** A list of integrations to enable for this fine-tuning job. */ + fun integrations(integrations: List) = + integrations(JsonField.of(integrations)) + + /** A list of integrations to enable for this fine-tuning job. */ + @JsonProperty("integrations") + @ExcludeMissing + fun integrations(integrations: JsonField>) = + apply { + this.integrations = integrations + } + + /** The seed used for the fine-tuning job. */ + fun seed(seed: Long) = seed(JsonField.of(seed)) + + /** The seed used for the fine-tuning job. */ + @JsonProperty("seed") + @ExcludeMissing + fun seed(seed: JsonField) = apply { this.seed = seed } + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The + * value will be null if the fine-tuning job is not running. + */ + fun estimatedFinish(estimatedFinish: Long) = estimatedFinish(JsonField.of(estimatedFinish)) + + /** + * The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The + * value will be null if the fine-tuning job is not running. + */ + @JsonProperty("estimated_finish") + @ExcludeMissing + fun estimatedFinish(estimatedFinish: JsonField) = apply { + this.estimatedFinish = estimatedFinish + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FineTuningJob = + FineTuningJob( + id, + createdAt, + error, + fineTunedModel, + finishedAt, + hyperparameters, + model, + object_, + organizationId, + resultFiles.map { it.toUnmodifiable() }, + status, + trainedTokens, + trainingFile, + validationFile, + integrations.map { it.toUnmodifiable() }, + seed, + estimatedFinish, + additionalProperties.toUnmodifiable(), + ) + } + + /** + * For fine-tuning jobs that have `failed`, this will contain more information on the cause of + * the failure. + */ + @JsonDeserialize(builder = Error.Builder::class) + @NoAutoDetect + class Error + private constructor( + private val code: JsonField, + private val message: JsonField, + private val param: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** A machine-readable error code. */ + fun code(): String = code.getRequired("code") + + /** A human-readable error message. */ + fun message(): String = message.getRequired("message") + + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. This field + * will be null if the failure was not parameter-specific. + */ + fun param(): Optional = Optional.ofNullable(param.getNullable("param")) + + /** A machine-readable error code. */ + @JsonProperty("code") @ExcludeMissing fun _code() = code + + /** A human-readable error message. */ + @JsonProperty("message") @ExcludeMissing fun _message() = message + + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. This field + * will be null if the failure was not parameter-specific. + */ + @JsonProperty("param") @ExcludeMissing fun _param() = param + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Error = apply { + if (!validated) { + code() + message() + param() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Error && + this.code == other.code && + this.message == other.message && + this.param == other.param && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + code, + message, + param, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Error{code=$code, message=$message, param=$param, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var code: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var param: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(error: Error) = apply { + this.code = error.code + this.message = error.message + this.param = error.param + additionalProperties(error.additionalProperties) + } + + /** A machine-readable error code. */ + fun code(code: String) = code(JsonField.of(code)) + + /** A machine-readable error code. */ + @JsonProperty("code") + @ExcludeMissing + fun code(code: JsonField) = apply { this.code = code } + + /** A human-readable error message. */ + fun message(message: String) = message(JsonField.of(message)) + + /** A human-readable error message. */ + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. This + * field will be null if the failure was not parameter-specific. + */ + fun param(param: String) = param(JsonField.of(param)) + + /** + * The parameter that was invalid, usually `training_file` or `validation_file`. This + * field will be null if the failure was not parameter-specific. + */ + @JsonProperty("param") + @ExcludeMissing + fun param(param: JsonField) = apply { this.param = param } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Error = + Error( + code, + message, + param, + additionalProperties.toUnmodifiable(), + ) + } + } + + /** + * The hyperparameters used for the fine-tuning job. See the + * [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. + */ + @JsonDeserialize(builder = Hyperparameters.Builder::class) + @NoAutoDetect + class Hyperparameters + private constructor( + private val nEpochs: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through + * the training dataset. "auto" decides the optimal number of epochs based on the size of + * the dataset. If setting the number manually, we support any number between 1 and 50 + * epochs. + */ + fun nEpochs(): NEpochs = nEpochs.getRequired("n_epochs") + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through + * the training dataset. "auto" decides the optimal number of epochs based on the size of + * the dataset. If setting the number manually, we support any number between 1 and 50 + * epochs. + */ + @JsonProperty("n_epochs") @ExcludeMissing fun _nEpochs() = nEpochs + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Hyperparameters = apply { + if (!validated) { + nEpochs() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Hyperparameters && + this.nEpochs == other.nEpochs && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = Objects.hash(nEpochs, additionalProperties) + } + return hashCode + } + + override fun toString() = + "Hyperparameters{nEpochs=$nEpochs, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var nEpochs: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(hyperparameters: Hyperparameters) = apply { + this.nEpochs = hyperparameters.nEpochs + additionalProperties(hyperparameters.additionalProperties) + } + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. "auto" decides the optimal number of epochs based on + * the size of the dataset. If setting the number manually, we support any number + * between 1 and 50 epochs. + */ + fun nEpochs(nEpochs: NEpochs) = nEpochs(JsonField.of(nEpochs)) + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. "auto" decides the optimal number of epochs based on + * the size of the dataset. If setting the number manually, we support any number + * between 1 and 50 epochs. + */ + @JsonProperty("n_epochs") + @ExcludeMissing + fun nEpochs(nEpochs: JsonField) = apply { this.nEpochs = nEpochs } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Hyperparameters = + Hyperparameters(nEpochs, additionalProperties.toUnmodifiable()) + } + + @JsonDeserialize(using = NEpochs.Deserializer::class) + @JsonSerialize(using = NEpochs.Serializer::class) + class NEpochs + private constructor( + private val unionMember0: UnionMember0? = null, + private val long: Long? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun unionMember0(): Optional = Optional.ofNullable(unionMember0) + + fun long(): Optional = Optional.ofNullable(long) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isLong(): Boolean = long != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asLong(): Long = long.getOrThrow("long") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + long != null -> visitor.visitLong(long) + else -> visitor.unknown(_json) + } + } + + fun validate(): NEpochs = apply { + if (!validated) { + if (unionMember0 == null && long == null) { + throw OpenAIInvalidDataException("Unknown NEpochs: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is NEpochs && + this.unionMember0 == other.unionMember0 && + this.long == other.long + } + + override fun hashCode(): Int { + return Objects.hash(unionMember0, long) + } + + override fun toString(): String { + return when { + unionMember0 != null -> "NEpochs{unionMember0=$unionMember0}" + long != null -> "NEpochs{long=$long}" + _json != null -> "NEpochs{_unknown=$_json}" + else -> throw IllegalStateException("Invalid NEpochs") + } + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + NEpochs(unionMember0 = unionMember0) + + @JvmStatic fun ofLong(long: Long) = NEpochs(long = long) + } + + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitLong(long: Long): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown NEpochs: $json") + } + } + + class Deserializer : BaseDeserializer(NEpochs::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): NEpochs { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return NEpochs(unionMember0 = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef())?.let { + return NEpochs(long = it, _json = json) + } + + return NEpochs(_json = json) + } + } + + class Serializer : BaseSerializer(NEpochs::class) { + + override fun serialize( + value: NEpochs, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.unionMember0 != null -> generator.writeObject(value.unionMember0) + value.long != null -> generator.writeObject(value.long) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid NEpochs") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val AUTO = UnionMember0(JsonField.of("auto")) + + @JvmStatic fun of(value: String) = UnionMember0(JsonField.of(value)) + } + + enum class Known { + AUTO, + } + + enum class Value { + AUTO, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + else -> throw OpenAIInvalidDataException("Unknown UnionMember0: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + } + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val FINE_TUNING_JOB = Object(JsonField.of("fine_tuning.job")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + FINE_TUNING_JOB, + } + + enum class Value { + FINE_TUNING_JOB, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + FINE_TUNING_JOB -> Value.FINE_TUNING_JOB + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + FINE_TUNING_JOB -> Known.FINE_TUNING_JOB + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + class Status + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Status && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val VALIDATING_FILES = Status(JsonField.of("validating_files")) + + @JvmField val QUEUED = Status(JsonField.of("queued")) + + @JvmField val RUNNING = Status(JsonField.of("running")) + + @JvmField val SUCCEEDED = Status(JsonField.of("succeeded")) + + @JvmField val FAILED = Status(JsonField.of("failed")) + + @JvmField val CANCELLED = Status(JsonField.of("cancelled")) + + @JvmStatic fun of(value: String) = Status(JsonField.of(value)) + } + + enum class Known { + VALIDATING_FILES, + QUEUED, + RUNNING, + SUCCEEDED, + FAILED, + CANCELLED, + } + + enum class Value { + VALIDATING_FILES, + QUEUED, + RUNNING, + SUCCEEDED, + FAILED, + CANCELLED, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + VALIDATING_FILES -> Value.VALIDATING_FILES + QUEUED -> Value.QUEUED + RUNNING -> Value.RUNNING + SUCCEEDED -> Value.SUCCEEDED + FAILED -> Value.FAILED + CANCELLED -> Value.CANCELLED + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + VALIDATING_FILES -> Known.VALIDATING_FILES + QUEUED -> Known.QUEUED + RUNNING -> Known.RUNNING + SUCCEEDED -> Known.SUCCEEDED + FAILED -> Known.FAILED + CANCELLED -> Known.CANCELLED + else -> throw OpenAIInvalidDataException("Unknown Status: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCancelParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCancelParams.kt new file mode 100644 index 0000000..9748344 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCancelParams.kt @@ -0,0 +1,157 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FineTuningJobCancelParams +constructor( + private val fineTuningJobId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fineTuningJobId(): String = fineTuningJobId + + @JvmSynthetic + internal fun getBody(): Optional> { + return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fineTuningJobId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCancelParams && + this.fineTuningJobId == other.fineTuningJobId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fineTuningJobId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FineTuningJobCancelParams{fineTuningJobId=$fineTuningJobId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fineTuningJobId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobCancelParams: FineTuningJobCancelParams) = apply { + this.fineTuningJobId = fineTuningJobCancelParams.fineTuningJobId + additionalQueryParams(fineTuningJobCancelParams.additionalQueryParams) + additionalHeaders(fineTuningJobCancelParams.additionalHeaders) + additionalBodyProperties(fineTuningJobCancelParams.additionalBodyProperties) + } + + fun fineTuningJobId(fineTuningJobId: String) = apply { + this.fineTuningJobId = fineTuningJobId + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FineTuningJobCancelParams = + FineTuningJobCancelParams( + checkNotNull(fineTuningJobId) { "`fineTuningJobId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpoint.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpoint.kt new file mode 100644 index 0000000..b2ebfc1 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpoint.kt @@ -0,0 +1,532 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects +import java.util.Optional + +/** + * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that + * is ready to use. + */ +@JsonDeserialize(builder = FineTuningJobCheckpoint.Builder::class) +@NoAutoDetect +class FineTuningJobCheckpoint +private constructor( + private val id: JsonField, + private val createdAt: JsonField, + private val fineTunedModelCheckpoint: JsonField, + private val stepNumber: JsonField, + private val metrics: JsonField, + private val fineTuningJobId: JsonField, + private val object_: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The checkpoint identifier, which can be referenced in the API endpoints. */ + fun id(): String = id.getRequired("id") + + /** The Unix timestamp (in seconds) for when the checkpoint was created. */ + fun createdAt(): Long = createdAt.getRequired("created_at") + + /** The name of the fine-tuned checkpoint model that is created. */ + fun fineTunedModelCheckpoint(): String = + fineTunedModelCheckpoint.getRequired("fine_tuned_model_checkpoint") + + /** The step number that the checkpoint was created at. */ + fun stepNumber(): Long = stepNumber.getRequired("step_number") + + /** Metrics at the step number during the fine-tuning job. */ + fun metrics(): Metrics = metrics.getRequired("metrics") + + /** The name of the fine-tuning job that this checkpoint was created from. */ + fun fineTuningJobId(): String = fineTuningJobId.getRequired("fine_tuning_job_id") + + /** The object type, which is always "fine_tuning.job.checkpoint". */ + fun object_(): Object = object_.getRequired("object") + + /** The checkpoint identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** The Unix timestamp (in seconds) for when the checkpoint was created. */ + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + /** The name of the fine-tuned checkpoint model that is created. */ + @JsonProperty("fine_tuned_model_checkpoint") + @ExcludeMissing + fun _fineTunedModelCheckpoint() = fineTunedModelCheckpoint + + /** The step number that the checkpoint was created at. */ + @JsonProperty("step_number") @ExcludeMissing fun _stepNumber() = stepNumber + + /** Metrics at the step number during the fine-tuning job. */ + @JsonProperty("metrics") @ExcludeMissing fun _metrics() = metrics + + /** The name of the fine-tuning job that this checkpoint was created from. */ + @JsonProperty("fine_tuning_job_id") @ExcludeMissing fun _fineTuningJobId() = fineTuningJobId + + /** The object type, which is always "fine_tuning.job.checkpoint". */ + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FineTuningJobCheckpoint = apply { + if (!validated) { + id() + createdAt() + fineTunedModelCheckpoint() + stepNumber() + metrics().validate() + fineTuningJobId() + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCheckpoint && + this.id == other.id && + this.createdAt == other.createdAt && + this.fineTunedModelCheckpoint == other.fineTunedModelCheckpoint && + this.stepNumber == other.stepNumber && + this.metrics == other.metrics && + this.fineTuningJobId == other.fineTuningJobId && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + createdAt, + fineTunedModelCheckpoint, + stepNumber, + metrics, + fineTuningJobId, + object_, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FineTuningJobCheckpoint{id=$id, createdAt=$createdAt, fineTunedModelCheckpoint=$fineTunedModelCheckpoint, stepNumber=$stepNumber, metrics=$metrics, fineTuningJobId=$fineTuningJobId, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var fineTunedModelCheckpoint: JsonField = JsonMissing.of() + private var stepNumber: JsonField = JsonMissing.of() + private var metrics: JsonField = JsonMissing.of() + private var fineTuningJobId: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobCheckpoint: FineTuningJobCheckpoint) = apply { + this.id = fineTuningJobCheckpoint.id + this.createdAt = fineTuningJobCheckpoint.createdAt + this.fineTunedModelCheckpoint = fineTuningJobCheckpoint.fineTunedModelCheckpoint + this.stepNumber = fineTuningJobCheckpoint.stepNumber + this.metrics = fineTuningJobCheckpoint.metrics + this.fineTuningJobId = fineTuningJobCheckpoint.fineTuningJobId + this.object_ = fineTuningJobCheckpoint.object_ + additionalProperties(fineTuningJobCheckpoint.additionalProperties) + } + + /** The checkpoint identifier, which can be referenced in the API endpoints. */ + fun id(id: String) = id(JsonField.of(id)) + + /** The checkpoint identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** The Unix timestamp (in seconds) for when the checkpoint was created. */ + fun createdAt(createdAt: Long) = createdAt(JsonField.of(createdAt)) + + /** The Unix timestamp (in seconds) for when the checkpoint was created. */ + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + /** The name of the fine-tuned checkpoint model that is created. */ + fun fineTunedModelCheckpoint(fineTunedModelCheckpoint: String) = + fineTunedModelCheckpoint(JsonField.of(fineTunedModelCheckpoint)) + + /** The name of the fine-tuned checkpoint model that is created. */ + @JsonProperty("fine_tuned_model_checkpoint") + @ExcludeMissing + fun fineTunedModelCheckpoint(fineTunedModelCheckpoint: JsonField) = apply { + this.fineTunedModelCheckpoint = fineTunedModelCheckpoint + } + + /** The step number that the checkpoint was created at. */ + fun stepNumber(stepNumber: Long) = stepNumber(JsonField.of(stepNumber)) + + /** The step number that the checkpoint was created at. */ + @JsonProperty("step_number") + @ExcludeMissing + fun stepNumber(stepNumber: JsonField) = apply { this.stepNumber = stepNumber } + + /** Metrics at the step number during the fine-tuning job. */ + fun metrics(metrics: Metrics) = metrics(JsonField.of(metrics)) + + /** Metrics at the step number during the fine-tuning job. */ + @JsonProperty("metrics") + @ExcludeMissing + fun metrics(metrics: JsonField) = apply { this.metrics = metrics } + + /** The name of the fine-tuning job that this checkpoint was created from. */ + fun fineTuningJobId(fineTuningJobId: String) = + fineTuningJobId(JsonField.of(fineTuningJobId)) + + /** The name of the fine-tuning job that this checkpoint was created from. */ + @JsonProperty("fine_tuning_job_id") + @ExcludeMissing + fun fineTuningJobId(fineTuningJobId: JsonField) = apply { + this.fineTuningJobId = fineTuningJobId + } + + /** The object type, which is always "fine_tuning.job.checkpoint". */ + fun object_(object_: Object) = object_(JsonField.of(object_)) + + /** The object type, which is always "fine_tuning.job.checkpoint". */ + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FineTuningJobCheckpoint = + FineTuningJobCheckpoint( + id, + createdAt, + fineTunedModelCheckpoint, + stepNumber, + metrics, + fineTuningJobId, + object_, + additionalProperties.toUnmodifiable(), + ) + } + + /** Metrics at the step number during the fine-tuning job. */ + @JsonDeserialize(builder = Metrics.Builder::class) + @NoAutoDetect + class Metrics + private constructor( + private val step: JsonField, + private val trainLoss: JsonField, + private val trainMeanTokenAccuracy: JsonField, + private val validLoss: JsonField, + private val validMeanTokenAccuracy: JsonField, + private val fullValidLoss: JsonField, + private val fullValidMeanTokenAccuracy: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + fun step(): Optional = Optional.ofNullable(step.getNullable("step")) + + fun trainLoss(): Optional = Optional.ofNullable(trainLoss.getNullable("train_loss")) + + fun trainMeanTokenAccuracy(): Optional = + Optional.ofNullable(trainMeanTokenAccuracy.getNullable("train_mean_token_accuracy")) + + fun validLoss(): Optional = Optional.ofNullable(validLoss.getNullable("valid_loss")) + + fun validMeanTokenAccuracy(): Optional = + Optional.ofNullable(validMeanTokenAccuracy.getNullable("valid_mean_token_accuracy")) + + fun fullValidLoss(): Optional = + Optional.ofNullable(fullValidLoss.getNullable("full_valid_loss")) + + fun fullValidMeanTokenAccuracy(): Optional = + Optional.ofNullable( + fullValidMeanTokenAccuracy.getNullable("full_valid_mean_token_accuracy") + ) + + @JsonProperty("step") @ExcludeMissing fun _step() = step + + @JsonProperty("train_loss") @ExcludeMissing fun _trainLoss() = trainLoss + + @JsonProperty("train_mean_token_accuracy") + @ExcludeMissing + fun _trainMeanTokenAccuracy() = trainMeanTokenAccuracy + + @JsonProperty("valid_loss") @ExcludeMissing fun _validLoss() = validLoss + + @JsonProperty("valid_mean_token_accuracy") + @ExcludeMissing + fun _validMeanTokenAccuracy() = validMeanTokenAccuracy + + @JsonProperty("full_valid_loss") @ExcludeMissing fun _fullValidLoss() = fullValidLoss + + @JsonProperty("full_valid_mean_token_accuracy") + @ExcludeMissing + fun _fullValidMeanTokenAccuracy() = fullValidMeanTokenAccuracy + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Metrics = apply { + if (!validated) { + step() + trainLoss() + trainMeanTokenAccuracy() + validLoss() + validMeanTokenAccuracy() + fullValidLoss() + fullValidMeanTokenAccuracy() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metrics && + this.step == other.step && + this.trainLoss == other.trainLoss && + this.trainMeanTokenAccuracy == other.trainMeanTokenAccuracy && + this.validLoss == other.validLoss && + this.validMeanTokenAccuracy == other.validMeanTokenAccuracy && + this.fullValidLoss == other.fullValidLoss && + this.fullValidMeanTokenAccuracy == other.fullValidMeanTokenAccuracy && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + step, + trainLoss, + trainMeanTokenAccuracy, + validLoss, + validMeanTokenAccuracy, + fullValidLoss, + fullValidMeanTokenAccuracy, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Metrics{step=$step, trainLoss=$trainLoss, trainMeanTokenAccuracy=$trainMeanTokenAccuracy, validLoss=$validLoss, validMeanTokenAccuracy=$validMeanTokenAccuracy, fullValidLoss=$fullValidLoss, fullValidMeanTokenAccuracy=$fullValidMeanTokenAccuracy, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var step: JsonField = JsonMissing.of() + private var trainLoss: JsonField = JsonMissing.of() + private var trainMeanTokenAccuracy: JsonField = JsonMissing.of() + private var validLoss: JsonField = JsonMissing.of() + private var validMeanTokenAccuracy: JsonField = JsonMissing.of() + private var fullValidLoss: JsonField = JsonMissing.of() + private var fullValidMeanTokenAccuracy: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metrics: Metrics) = apply { + this.step = metrics.step + this.trainLoss = metrics.trainLoss + this.trainMeanTokenAccuracy = metrics.trainMeanTokenAccuracy + this.validLoss = metrics.validLoss + this.validMeanTokenAccuracy = metrics.validMeanTokenAccuracy + this.fullValidLoss = metrics.fullValidLoss + this.fullValidMeanTokenAccuracy = metrics.fullValidMeanTokenAccuracy + additionalProperties(metrics.additionalProperties) + } + + fun step(step: Double) = step(JsonField.of(step)) + + @JsonProperty("step") + @ExcludeMissing + fun step(step: JsonField) = apply { this.step = step } + + fun trainLoss(trainLoss: Double) = trainLoss(JsonField.of(trainLoss)) + + @JsonProperty("train_loss") + @ExcludeMissing + fun trainLoss(trainLoss: JsonField) = apply { this.trainLoss = trainLoss } + + fun trainMeanTokenAccuracy(trainMeanTokenAccuracy: Double) = + trainMeanTokenAccuracy(JsonField.of(trainMeanTokenAccuracy)) + + @JsonProperty("train_mean_token_accuracy") + @ExcludeMissing + fun trainMeanTokenAccuracy(trainMeanTokenAccuracy: JsonField) = apply { + this.trainMeanTokenAccuracy = trainMeanTokenAccuracy + } + + fun validLoss(validLoss: Double) = validLoss(JsonField.of(validLoss)) + + @JsonProperty("valid_loss") + @ExcludeMissing + fun validLoss(validLoss: JsonField) = apply { this.validLoss = validLoss } + + fun validMeanTokenAccuracy(validMeanTokenAccuracy: Double) = + validMeanTokenAccuracy(JsonField.of(validMeanTokenAccuracy)) + + @JsonProperty("valid_mean_token_accuracy") + @ExcludeMissing + fun validMeanTokenAccuracy(validMeanTokenAccuracy: JsonField) = apply { + this.validMeanTokenAccuracy = validMeanTokenAccuracy + } + + fun fullValidLoss(fullValidLoss: Double) = fullValidLoss(JsonField.of(fullValidLoss)) + + @JsonProperty("full_valid_loss") + @ExcludeMissing + fun fullValidLoss(fullValidLoss: JsonField) = apply { + this.fullValidLoss = fullValidLoss + } + + fun fullValidMeanTokenAccuracy(fullValidMeanTokenAccuracy: Double) = + fullValidMeanTokenAccuracy(JsonField.of(fullValidMeanTokenAccuracy)) + + @JsonProperty("full_valid_mean_token_accuracy") + @ExcludeMissing + fun fullValidMeanTokenAccuracy(fullValidMeanTokenAccuracy: JsonField) = apply { + this.fullValidMeanTokenAccuracy = fullValidMeanTokenAccuracy + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Metrics = + Metrics( + step, + trainLoss, + trainMeanTokenAccuracy, + validLoss, + validMeanTokenAccuracy, + fullValidLoss, + fullValidMeanTokenAccuracy, + additionalProperties.toUnmodifiable(), + ) + } + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField + val FINE_TUNING_JOB_CHECKPOINT = Object(JsonField.of("fine_tuning.job.checkpoint")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + FINE_TUNING_JOB_CHECKPOINT, + } + + enum class Value { + FINE_TUNING_JOB_CHECKPOINT, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + FINE_TUNING_JOB_CHECKPOINT -> Value.FINE_TUNING_JOB_CHECKPOINT + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + FINE_TUNING_JOB_CHECKPOINT -> Known.FINE_TUNING_JOB_CHECKPOINT + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListPage.kt new file mode 100644 index 0000000..4ec5f3c --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListPage.kt @@ -0,0 +1,188 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.blocking.fineTuning.jobs.CheckpointService +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class FineTuningJobCheckpointListPage +private constructor( + private val checkpointsService: CheckpointService, + private val params: FineTuningJobCheckpointListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCheckpointListPage && + this.checkpointsService == other.checkpointsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + checkpointsService, + params, + response, + ) + } + + override fun toString() = + "FineTuningJobCheckpointListPage{checkpointsService=$checkpointsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + FineTuningJobCheckpointListParams.builder() + .from(params) + .after(data().last().id()) + .build() + ) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { checkpointsService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + checkpointsService: CheckpointService, + params: FineTuningJobCheckpointListParams, + response: Response + ) = + FineTuningJobCheckpointListPage( + checkpointsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "FineTuningJobCheckpointListPage.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + private val firstPage: FineTuningJobCheckpointListPage, + ) : 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().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListPageAsync.kt new file mode 100644 index 0000000..64d4865 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListPageAsync.kt @@ -0,0 +1,201 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.async.fineTuning.jobs.CheckpointServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class FineTuningJobCheckpointListPageAsync +private constructor( + private val checkpointsService: CheckpointServiceAsync, + private val params: FineTuningJobCheckpointListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCheckpointListPageAsync && + this.checkpointsService == other.checkpointsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + checkpointsService, + params, + response, + ) + } + + override fun toString() = + "FineTuningJobCheckpointListPageAsync{checkpointsService=$checkpointsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + FineTuningJobCheckpointListParams.builder() + .from(params) + .after(data().last().id()) + .build() + ) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { checkpointsService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + checkpointsService: CheckpointServiceAsync, + params: FineTuningJobCheckpointListParams, + response: Response + ) = + FineTuningJobCheckpointListPageAsync( + checkpointsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "FineTuningJobCheckpointListPageAsync.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + private val firstPage: FineTuningJobCheckpointListPageAsync, + ) { + + fun forEach( + action: Predicate, + executor: Executor + ): CompletableFuture { + fun CompletableFuture>.forEach( + action: (FineTuningJobCheckpoint) -> 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 } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListParams.kt new file mode 100644 index 0000000..74f7f24 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCheckpointListParams.kt @@ -0,0 +1,182 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FineTuningJobCheckpointListParams +constructor( + private val fineTuningJobId: String, + private val after: String?, + private val limit: Long?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fineTuningJobId(): String = fineTuningJobId + + fun after(): Optional = Optional.ofNullable(after) + + fun limit(): Optional = Optional.ofNullable(limit) + + @JvmSynthetic + internal fun getQueryParams(): Map> { + val params = mutableMapOf>() + this.after?.let { params.put("after", listOf(it.toString())) } + this.limit?.let { params.put("limit", listOf(it.toString())) } + params.putAll(additionalQueryParams) + return params.toUnmodifiable() + } + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fineTuningJobId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCheckpointListParams && + this.fineTuningJobId == other.fineTuningJobId && + this.after == other.after && + this.limit == other.limit && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fineTuningJobId, + after, + limit, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FineTuningJobCheckpointListParams{fineTuningJobId=$fineTuningJobId, after=$after, limit=$limit, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fineTuningJobId: String? = null + private var after: String? = null + private var limit: Long? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobCheckpointListParams: FineTuningJobCheckpointListParams) = + apply { + this.fineTuningJobId = fineTuningJobCheckpointListParams.fineTuningJobId + this.after = fineTuningJobCheckpointListParams.after + this.limit = fineTuningJobCheckpointListParams.limit + additionalQueryParams(fineTuningJobCheckpointListParams.additionalQueryParams) + additionalHeaders(fineTuningJobCheckpointListParams.additionalHeaders) + additionalBodyProperties(fineTuningJobCheckpointListParams.additionalBodyProperties) + } + + fun fineTuningJobId(fineTuningJobId: String) = apply { + this.fineTuningJobId = fineTuningJobId + } + + /** Identifier for the last checkpoint ID from the previous pagination request. */ + fun after(after: String) = apply { this.after = after } + + /** Number of checkpoints to retrieve. */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FineTuningJobCheckpointListParams = + FineTuningJobCheckpointListParams( + checkNotNull(fineTuningJobId) { "`fineTuningJobId` is required but was not set" }, + after, + limit, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCreateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCreateParams.kt new file mode 100644 index 0000000..6c65347 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobCreateParams.kt @@ -0,0 +1,1680 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.openai.core.BaseDeserializer +import com.openai.core.BaseSerializer +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.getOrThrow +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FineTuningJobCreateParams +constructor( + private val model: Model, + private val trainingFile: String, + private val hyperparameters: Hyperparameters?, + private val integrations: List?, + private val seed: Long?, + private val suffix: String?, + private val validationFile: String?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun model(): Model = model + + fun trainingFile(): String = trainingFile + + fun hyperparameters(): Optional = Optional.ofNullable(hyperparameters) + + fun integrations(): Optional> = Optional.ofNullable(integrations) + + fun seed(): Optional = Optional.ofNullable(seed) + + fun suffix(): Optional = Optional.ofNullable(suffix) + + fun validationFile(): Optional = Optional.ofNullable(validationFile) + + @JvmSynthetic + internal fun getBody(): FineTuningJobCreateBody { + return FineTuningJobCreateBody( + model, + trainingFile, + hyperparameters, + integrations, + seed, + suffix, + validationFile, + additionalBodyProperties, + ) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + @JsonDeserialize(builder = FineTuningJobCreateBody.Builder::class) + @NoAutoDetect + class FineTuningJobCreateBody + internal constructor( + private val model: Model?, + private val trainingFile: String?, + private val hyperparameters: Hyperparameters?, + private val integrations: List?, + private val seed: Long?, + private val suffix: String?, + private val validationFile: String?, + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + @JsonProperty("model") fun model(): Model? = model + + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to + * upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload your file + * with the purpose `fine-tune`. + * + * The contents of the file should differ depending on if the model uses the + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * format. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more + * details. + */ + @JsonProperty("training_file") fun trainingFile(): String? = trainingFile + + /** The hyperparameters used for the fine-tuning job. */ + @JsonProperty("hyperparameters") fun hyperparameters(): Hyperparameters? = hyperparameters + + /** A list of integrations to enable for your fine-tuning job. */ + @JsonProperty("integrations") fun integrations(): List? = integrations + + /** + * The seed controls the reproducibility of the job. Passing in the same seed and job + * parameters should produce the same results, but may differ in rare cases. If a seed is + * not specified, one will be generated for you. + */ + @JsonProperty("seed") fun seed(): Long? = seed + + /** + * A string of up to 18 characters that will be added to your fine-tuned model name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + */ + @JsonProperty("suffix") fun suffix(): String? = suffix + + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics periodically + * during fine-tuning. These metrics can be viewed in the fine-tuning results file. The same + * data should not be present in both train and validation files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with the + * purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more + * details. + */ + @JsonProperty("validation_file") fun validationFile(): String? = validationFile + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCreateBody && + this.model == other.model && + this.trainingFile == other.trainingFile && + this.hyperparameters == other.hyperparameters && + this.integrations == other.integrations && + this.seed == other.seed && + this.suffix == other.suffix && + this.validationFile == other.validationFile && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + model, + trainingFile, + hyperparameters, + integrations, + seed, + suffix, + validationFile, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FineTuningJobCreateBody{model=$model, trainingFile=$trainingFile, hyperparameters=$hyperparameters, integrations=$integrations, seed=$seed, suffix=$suffix, validationFile=$validationFile, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var model: Model? = null + private var trainingFile: String? = null + private var hyperparameters: Hyperparameters? = null + private var integrations: List? = null + private var seed: Long? = null + private var suffix: String? = null + private var validationFile: String? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobCreateBody: FineTuningJobCreateBody) = apply { + this.model = fineTuningJobCreateBody.model + this.trainingFile = fineTuningJobCreateBody.trainingFile + this.hyperparameters = fineTuningJobCreateBody.hyperparameters + this.integrations = fineTuningJobCreateBody.integrations + this.seed = fineTuningJobCreateBody.seed + this.suffix = fineTuningJobCreateBody.suffix + this.validationFile = fineTuningJobCreateBody.validationFile + additionalProperties(fineTuningJobCreateBody.additionalProperties) + } + + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + @JsonProperty("model") fun model(model: Model) = apply { this.model = model } + + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for + * how to upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload your + * file with the purpose `fine-tune`. + * + * The contents of the file should differ depending on if the model uses the + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * format. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for + * more details. + */ + @JsonProperty("training_file") + fun trainingFile(trainingFile: String) = apply { this.trainingFile = trainingFile } + + /** The hyperparameters used for the fine-tuning job. */ + @JsonProperty("hyperparameters") + fun hyperparameters(hyperparameters: Hyperparameters) = apply { + this.hyperparameters = hyperparameters + } + + /** A list of integrations to enable for your fine-tuning job. */ + @JsonProperty("integrations") + fun integrations(integrations: List) = apply { + this.integrations = integrations + } + + /** + * The seed controls the reproducibility of the job. Passing in the same seed and job + * parameters should produce the same results, but may differ in rare cases. If a seed + * is not specified, one will be generated for you. + */ + @JsonProperty("seed") fun seed(seed: Long) = apply { this.seed = seed } + + /** + * A string of up to 18 characters that will be added to your fine-tuned model name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + */ + @JsonProperty("suffix") fun suffix(suffix: String) = apply { this.suffix = suffix } + + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics + * periodically during fine-tuning. These metrics can be viewed in the fine-tuning + * results file. The same data should not be present in both train and validation files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with the + * purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for + * more details. + */ + @JsonProperty("validation_file") + fun validationFile(validationFile: String) = apply { + this.validationFile = validationFile + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FineTuningJobCreateBody = + FineTuningJobCreateBody( + checkNotNull(model) { "`model` is required but was not set" }, + checkNotNull(trainingFile) { "`trainingFile` is required but was not set" }, + hyperparameters, + integrations?.toUnmodifiable(), + seed, + suffix, + validationFile, + additionalProperties.toUnmodifiable(), + ) + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobCreateParams && + this.model == other.model && + this.trainingFile == other.trainingFile && + this.hyperparameters == other.hyperparameters && + this.integrations == other.integrations && + this.seed == other.seed && + this.suffix == other.suffix && + this.validationFile == other.validationFile && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + model, + trainingFile, + hyperparameters, + integrations, + seed, + suffix, + validationFile, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FineTuningJobCreateParams{model=$model, trainingFile=$trainingFile, hyperparameters=$hyperparameters, integrations=$integrations, seed=$seed, suffix=$suffix, validationFile=$validationFile, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var model: Model? = null + private var trainingFile: String? = null + private var hyperparameters: Hyperparameters? = null + private var integrations: MutableList = mutableListOf() + private var seed: Long? = null + private var suffix: String? = null + private var validationFile: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobCreateParams: FineTuningJobCreateParams) = apply { + this.model = fineTuningJobCreateParams.model + this.trainingFile = fineTuningJobCreateParams.trainingFile + this.hyperparameters = fineTuningJobCreateParams.hyperparameters + this.integrations(fineTuningJobCreateParams.integrations ?: listOf()) + this.seed = fineTuningJobCreateParams.seed + this.suffix = fineTuningJobCreateParams.suffix + this.validationFile = fineTuningJobCreateParams.validationFile + additionalQueryParams(fineTuningJobCreateParams.additionalQueryParams) + additionalHeaders(fineTuningJobCreateParams.additionalHeaders) + additionalBodyProperties(fineTuningJobCreateParams.additionalBodyProperties) + } + + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + fun model(model: Model) = apply { this.model = model } + + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + fun model(string: String) = apply { this.model = Model.ofString(string) } + + /** + * The name of the model to fine-tune. You can select one of the + * [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + */ + fun model(unionMember1: Model.UnionMember1) = apply { + this.model = Model.ofUnionMember1(unionMember1) + } + + /** + * The ID of an uploaded file that contains training data. + * + * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to + * upload a file. + * + * Your dataset must be formatted as a JSONL file. Additionally, you must upload your file + * with the purpose `fine-tune`. + * + * The contents of the file should differ depending on if the model uses the + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * format. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more + * details. + */ + fun trainingFile(trainingFile: String) = apply { this.trainingFile = trainingFile } + + /** The hyperparameters used for the fine-tuning job. */ + fun hyperparameters(hyperparameters: Hyperparameters) = apply { + this.hyperparameters = hyperparameters + } + + /** A list of integrations to enable for your fine-tuning job. */ + fun integrations(integrations: List) = apply { + this.integrations.clear() + this.integrations.addAll(integrations) + } + + /** A list of integrations to enable for your fine-tuning job. */ + fun addIntegration(integration: Integration) = apply { this.integrations.add(integration) } + + /** + * The seed controls the reproducibility of the job. Passing in the same seed and job + * parameters should produce the same results, but may differ in rare cases. If a seed is + * not specified, one will be generated for you. + */ + fun seed(seed: Long) = apply { this.seed = seed } + + /** + * A string of up to 18 characters that will be added to your fine-tuned model name. + * + * For example, a `suffix` of "custom-model-name" would produce a model name like + * `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + */ + fun suffix(suffix: String) = apply { this.suffix = suffix } + + /** + * The ID of an uploaded file that contains validation data. + * + * If you provide this file, the data is used to generate validation metrics periodically + * during fine-tuning. These metrics can be viewed in the fine-tuning results file. The same + * data should not be present in both train and validation files. + * + * Your dataset must be formatted as a JSONL file. You must upload your file with the + * purpose `fine-tune`. + * + * See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more + * details. + */ + fun validationFile(validationFile: String) = apply { this.validationFile = validationFile } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FineTuningJobCreateParams = + FineTuningJobCreateParams( + checkNotNull(model) { "`model` is required but was not set" }, + checkNotNull(trainingFile) { "`trainingFile` is required but was not set" }, + hyperparameters, + if (integrations.size == 0) null else integrations.toUnmodifiable(), + seed, + suffix, + validationFile, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } + + @JsonDeserialize(using = Model.Deserializer::class) + @JsonSerialize(using = Model.Serializer::class) + class Model + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + } + + fun validate(): Model = apply { + if (!validated) { + if (string == null && unionMember1 == null) { + throw OpenAIInvalidDataException("Unknown Model: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Model && + this.string == other.string && + this.unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int { + return Objects.hash(string, unionMember1) + } + + override fun toString(): String { + return when { + string != null -> "Model{string=$string}" + unionMember1 != null -> "Model{unionMember1=$unionMember1}" + _json != null -> "Model{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Model") + } + } + + companion object { + + @JvmStatic fun ofString(string: String) = Model(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = Model(unionMember1 = unionMember1) + } + + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown Model: $json") + } + } + + class Deserializer : BaseDeserializer(Model::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Model { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return Model(string = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef())?.let { + return Model(unionMember1 = it, _json = json) + } + + return Model(_json = json) + } + } + + class Serializer : BaseSerializer(Model::class) { + + override fun serialize( + value: Model, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Model") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val BABBAGE_002 = UnionMember1(JsonField.of("babbage-002")) + + @JvmField val DAVINCI_002 = UnionMember1(JsonField.of("davinci-002")) + + @JvmField val GPT_3_5_TURBO = UnionMember1(JsonField.of("gpt-3.5-turbo")) + + @JvmStatic fun of(value: String) = UnionMember1(JsonField.of(value)) + } + + enum class Known { + BABBAGE_002, + DAVINCI_002, + GPT_3_5_TURBO, + } + + enum class Value { + BABBAGE_002, + DAVINCI_002, + GPT_3_5_TURBO, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + BABBAGE_002 -> Value.BABBAGE_002 + DAVINCI_002 -> Value.DAVINCI_002 + GPT_3_5_TURBO -> Value.GPT_3_5_TURBO + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + BABBAGE_002 -> Known.BABBAGE_002 + DAVINCI_002 -> Known.DAVINCI_002 + GPT_3_5_TURBO -> Known.GPT_3_5_TURBO + else -> throw OpenAIInvalidDataException("Unknown UnionMember1: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + } + + /** The hyperparameters used for the fine-tuning job. */ + @JsonDeserialize(builder = Hyperparameters.Builder::class) + @NoAutoDetect + class Hyperparameters + private constructor( + private val batchSize: BatchSize?, + private val learningRateMultiplier: LearningRateMultiplier?, + private val nEpochs: NEpochs?, + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + /** + * Number of examples in each batch. A larger batch size means that model parameters are + * updated less frequently, but with lower variance. + */ + @JsonProperty("batch_size") fun batchSize(): BatchSize? = batchSize + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + * overfitting. + */ + @JsonProperty("learning_rate_multiplier") + fun learningRateMultiplier(): LearningRateMultiplier? = learningRateMultiplier + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through + * the training dataset. + */ + @JsonProperty("n_epochs") fun nEpochs(): NEpochs? = nEpochs + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Hyperparameters && + this.batchSize == other.batchSize && + this.learningRateMultiplier == other.learningRateMultiplier && + this.nEpochs == other.nEpochs && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + batchSize, + learningRateMultiplier, + nEpochs, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Hyperparameters{batchSize=$batchSize, learningRateMultiplier=$learningRateMultiplier, nEpochs=$nEpochs, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var batchSize: BatchSize? = null + private var learningRateMultiplier: LearningRateMultiplier? = null + private var nEpochs: NEpochs? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(hyperparameters: Hyperparameters) = apply { + this.batchSize = hyperparameters.batchSize + this.learningRateMultiplier = hyperparameters.learningRateMultiplier + this.nEpochs = hyperparameters.nEpochs + additionalProperties(hyperparameters.additionalProperties) + } + + /** + * Number of examples in each batch. A larger batch size means that model parameters are + * updated less frequently, but with lower variance. + */ + @JsonProperty("batch_size") + fun batchSize(batchSize: BatchSize) = apply { this.batchSize = batchSize } + + /** + * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid + * overfitting. + */ + @JsonProperty("learning_rate_multiplier") + fun learningRateMultiplier(learningRateMultiplier: LearningRateMultiplier) = apply { + this.learningRateMultiplier = learningRateMultiplier + } + + /** + * The number of epochs to train the model for. An epoch refers to one full cycle + * through the training dataset. + */ + @JsonProperty("n_epochs") + fun nEpochs(nEpochs: NEpochs) = apply { this.nEpochs = nEpochs } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Hyperparameters = + Hyperparameters( + batchSize, + learningRateMultiplier, + nEpochs, + additionalProperties.toUnmodifiable(), + ) + } + + @JsonDeserialize(using = BatchSize.Deserializer::class) + @JsonSerialize(using = BatchSize.Serializer::class) + class BatchSize + private constructor( + private val unionMember0: UnionMember0? = null, + private val long: Long? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun unionMember0(): Optional = Optional.ofNullable(unionMember0) + + fun long(): Optional = Optional.ofNullable(long) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isLong(): Boolean = long != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asLong(): Long = long.getOrThrow("long") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + long != null -> visitor.visitLong(long) + else -> visitor.unknown(_json) + } + } + + fun validate(): BatchSize = apply { + if (!validated) { + if (unionMember0 == null && long == null) { + throw OpenAIInvalidDataException("Unknown BatchSize: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is BatchSize && + this.unionMember0 == other.unionMember0 && + this.long == other.long + } + + override fun hashCode(): Int { + return Objects.hash(unionMember0, long) + } + + override fun toString(): String { + return when { + unionMember0 != null -> "BatchSize{unionMember0=$unionMember0}" + long != null -> "BatchSize{long=$long}" + _json != null -> "BatchSize{_unknown=$_json}" + else -> throw IllegalStateException("Invalid BatchSize") + } + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + BatchSize(unionMember0 = unionMember0) + + @JvmStatic fun ofLong(long: Long) = BatchSize(long = long) + } + + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitLong(long: Long): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown BatchSize: $json") + } + } + + class Deserializer : BaseDeserializer(BatchSize::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): BatchSize { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return BatchSize(unionMember0 = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef())?.let { + return BatchSize(long = it, _json = json) + } + + return BatchSize(_json = json) + } + } + + class Serializer : BaseSerializer(BatchSize::class) { + + override fun serialize( + value: BatchSize, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.unionMember0 != null -> generator.writeObject(value.unionMember0) + value.long != null -> generator.writeObject(value.long) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid BatchSize") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val AUTO = UnionMember0(JsonField.of("auto")) + + @JvmStatic fun of(value: String) = UnionMember0(JsonField.of(value)) + } + + enum class Known { + AUTO, + } + + enum class Value { + AUTO, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + else -> throw OpenAIInvalidDataException("Unknown UnionMember0: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + } + + @JsonDeserialize(using = LearningRateMultiplier.Deserializer::class) + @JsonSerialize(using = LearningRateMultiplier.Serializer::class) + class LearningRateMultiplier + private constructor( + private val unionMember0: UnionMember0? = null, + private val double: Double? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun unionMember0(): Optional = Optional.ofNullable(unionMember0) + + fun double(): Optional = Optional.ofNullable(double) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isDouble(): Boolean = double != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asDouble(): Double = double.getOrThrow("double") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + double != null -> visitor.visitDouble(double) + else -> visitor.unknown(_json) + } + } + + fun validate(): LearningRateMultiplier = apply { + if (!validated) { + if (unionMember0 == null && double == null) { + throw OpenAIInvalidDataException("Unknown LearningRateMultiplier: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is LearningRateMultiplier && + this.unionMember0 == other.unionMember0 && + this.double == other.double + } + + override fun hashCode(): Int { + return Objects.hash(unionMember0, double) + } + + override fun toString(): String { + return when { + unionMember0 != null -> "LearningRateMultiplier{unionMember0=$unionMember0}" + double != null -> "LearningRateMultiplier{double=$double}" + _json != null -> "LearningRateMultiplier{_unknown=$_json}" + else -> throw IllegalStateException("Invalid LearningRateMultiplier") + } + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + LearningRateMultiplier(unionMember0 = unionMember0) + + @JvmStatic fun ofDouble(double: Double) = LearningRateMultiplier(double = double) + } + + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitDouble(double: Double): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown LearningRateMultiplier: $json") + } + } + + class Deserializer : + BaseDeserializer(LearningRateMultiplier::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): LearningRateMultiplier { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return LearningRateMultiplier(unionMember0 = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef())?.let { + return LearningRateMultiplier(double = it, _json = json) + } + + return LearningRateMultiplier(_json = json) + } + } + + class Serializer : + BaseSerializer(LearningRateMultiplier::class) { + + override fun serialize( + value: LearningRateMultiplier, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.unionMember0 != null -> generator.writeObject(value.unionMember0) + value.double != null -> generator.writeObject(value.double) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid LearningRateMultiplier") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val AUTO = UnionMember0(JsonField.of("auto")) + + @JvmStatic fun of(value: String) = UnionMember0(JsonField.of(value)) + } + + enum class Known { + AUTO, + } + + enum class Value { + AUTO, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + else -> throw OpenAIInvalidDataException("Unknown UnionMember0: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + } + + @JsonDeserialize(using = NEpochs.Deserializer::class) + @JsonSerialize(using = NEpochs.Serializer::class) + class NEpochs + private constructor( + private val unionMember0: UnionMember0? = null, + private val long: Long? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun unionMember0(): Optional = Optional.ofNullable(unionMember0) + + fun long(): Optional = Optional.ofNullable(long) + + fun isUnionMember0(): Boolean = unionMember0 != null + + fun isLong(): Boolean = long != null + + fun asUnionMember0(): UnionMember0 = unionMember0.getOrThrow("unionMember0") + + fun asLong(): Long = long.getOrThrow("long") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + unionMember0 != null -> visitor.visitUnionMember0(unionMember0) + long != null -> visitor.visitLong(long) + else -> visitor.unknown(_json) + } + } + + fun validate(): NEpochs = apply { + if (!validated) { + if (unionMember0 == null && long == null) { + throw OpenAIInvalidDataException("Unknown NEpochs: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is NEpochs && + this.unionMember0 == other.unionMember0 && + this.long == other.long + } + + override fun hashCode(): Int { + return Objects.hash(unionMember0, long) + } + + override fun toString(): String { + return when { + unionMember0 != null -> "NEpochs{unionMember0=$unionMember0}" + long != null -> "NEpochs{long=$long}" + _json != null -> "NEpochs{_unknown=$_json}" + else -> throw IllegalStateException("Invalid NEpochs") + } + } + + companion object { + + @JvmStatic + fun ofUnionMember0(unionMember0: UnionMember0) = + NEpochs(unionMember0 = unionMember0) + + @JvmStatic fun ofLong(long: Long) = NEpochs(long = long) + } + + interface Visitor { + + fun visitUnionMember0(unionMember0: UnionMember0): T + + fun visitLong(long: Long): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown NEpochs: $json") + } + } + + class Deserializer : BaseDeserializer(NEpochs::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): NEpochs { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return NEpochs(unionMember0 = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef())?.let { + return NEpochs(long = it, _json = json) + } + + return NEpochs(_json = json) + } + } + + class Serializer : BaseSerializer(NEpochs::class) { + + override fun serialize( + value: NEpochs, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.unionMember0 != null -> generator.writeObject(value.unionMember0) + value.long != null -> generator.writeObject(value.long) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid NEpochs") + } + } + } + + class UnionMember0 + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember0 && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val AUTO = UnionMember0(JsonField.of("auto")) + + @JvmStatic fun of(value: String) = UnionMember0(JsonField.of(value)) + } + + enum class Known { + AUTO, + } + + enum class Value { + AUTO, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + AUTO -> Value.AUTO + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + AUTO -> Known.AUTO + else -> throw OpenAIInvalidDataException("Unknown UnionMember0: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + } + } + + @JsonDeserialize(builder = Integration.Builder::class) + @NoAutoDetect + class Integration + private constructor( + private val type: Type?, + private val wandb: Wandb?, + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) is + * supported. + */ + @JsonProperty("type") fun type(): Type? = type + + /** + * The settings for your integration with Weights and Biases. This payload specifies the + * project that metrics will be sent to. Optionally, you can set an explicit display name + * for your run, add tags to your run, and set a default entity (team, username, etc) to be + * associated with your run. + */ + @JsonProperty("wandb") fun wandb(): Wandb? = wandb + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Integration && + this.type == other.type && + this.wandb == other.wandb && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + type, + wandb, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Integration{type=$type, wandb=$wandb, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: Type? = null + private var wandb: Wandb? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(integration: Integration) = apply { + this.type = integration.type + this.wandb = integration.wandb + additionalProperties(integration.additionalProperties) + } + + /** + * The type of integration to enable. Currently, only "wandb" (Weights and Biases) is + * supported. + */ + @JsonProperty("type") fun type(type: Type) = apply { this.type = type } + + /** + * The settings for your integration with Weights and Biases. This payload specifies the + * project that metrics will be sent to. Optionally, you can set an explicit display + * name for your run, add tags to your run, and set a default entity (team, username, + * etc) to be associated with your run. + */ + @JsonProperty("wandb") fun wandb(wandb: Wandb) = apply { this.wandb = wandb } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Integration = + Integration( + checkNotNull(type) { "`type` is required but was not set" }, + checkNotNull(wandb) { "`wandb` is required but was not set" }, + additionalProperties.toUnmodifiable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val WANDB = Type(JsonField.of("wandb")) + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + WANDB, + } + + enum class Value { + WANDB, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + WANDB -> Value.WANDB + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + WANDB -> Known.WANDB + else -> throw OpenAIInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + /** + * The settings for your integration with Weights and Biases. This payload specifies the + * project that metrics will be sent to. Optionally, you can set an explicit display name + * for your run, add tags to your run, and set a default entity (team, username, etc) to be + * associated with your run. + */ + @JsonDeserialize(builder = Wandb.Builder::class) + @NoAutoDetect + class Wandb + private constructor( + private val project: String?, + private val name: String?, + private val entity: String?, + private val tags: List?, + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + /** The name of the project that the new run will be created under. */ + @JsonProperty("project") fun project(): String? = project + + /** + * A display name to set for the run. If not set, we will use the Job ID as the name. + */ + @JsonProperty("name") fun name(): String? = name + + /** + * The entity to use for the run. This allows you to set the team or username of the + * WandB user that you would like associated with the run. If not set, the default + * entity for the registered WandB API key is used. + */ + @JsonProperty("entity") fun entity(): String? = entity + + /** + * A list of tags to be attached to the newly created run. These tags are passed through + * directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", + * "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + @JsonProperty("tags") fun tags(): List? = tags + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Wandb && + this.project == other.project && + this.name == other.name && + this.entity == other.entity && + this.tags == other.tags && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + project, + name, + entity, + tags, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Wandb{project=$project, name=$name, entity=$entity, tags=$tags, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var project: String? = null + private var name: String? = null + private var entity: String? = null + private var tags: List? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(wandb: Wandb) = apply { + this.project = wandb.project + this.name = wandb.name + this.entity = wandb.entity + this.tags = wandb.tags + additionalProperties(wandb.additionalProperties) + } + + /** The name of the project that the new run will be created under. */ + @JsonProperty("project") + fun project(project: String) = apply { this.project = project } + + /** + * A display name to set for the run. If not set, we will use the Job ID as the + * name. + */ + @JsonProperty("name") fun name(name: String) = apply { this.name = name } + + /** + * The entity to use for the run. This allows you to set the team or username of the + * WandB user that you would like associated with the run. If not set, the default + * entity for the registered WandB API key is used. + */ + @JsonProperty("entity") fun entity(entity: String) = apply { this.entity = entity } + + /** + * A list of tags to be attached to the newly created run. These tags are passed + * through directly to WandB. Some default tags are generated by OpenAI: + * "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + @JsonProperty("tags") fun tags(tags: List) = apply { this.tags = tags } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = + apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Wandb = + Wandb( + checkNotNull(project) { "`project` is required but was not set" }, + name, + entity, + tags?.toUnmodifiable(), + additionalProperties.toUnmodifiable(), + ) + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobEvent.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobEvent.kt new file mode 100644 index 0000000..1e1384a --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobEvent.kt @@ -0,0 +1,296 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects + +/** Fine-tuning job event object */ +@JsonDeserialize(builder = FineTuningJobEvent.Builder::class) +@NoAutoDetect +class FineTuningJobEvent +private constructor( + private val id: JsonField, + private val createdAt: JsonField, + private val level: JsonField, + private val message: JsonField, + private val object_: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + fun id(): String = id.getRequired("id") + + fun createdAt(): Long = createdAt.getRequired("created_at") + + fun level(): Level = level.getRequired("level") + + fun message(): String = message.getRequired("message") + + fun object_(): Object = object_.getRequired("object") + + @JsonProperty("id") @ExcludeMissing fun _id() = id + + @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt + + @JsonProperty("level") @ExcludeMissing fun _level() = level + + @JsonProperty("message") @ExcludeMissing fun _message() = message + + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FineTuningJobEvent = apply { + if (!validated) { + id() + createdAt() + level() + message() + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobEvent && + this.id == other.id && + this.createdAt == other.createdAt && + this.level == other.level && + this.message == other.message && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + createdAt, + level, + message, + object_, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FineTuningJobEvent{id=$id, createdAt=$createdAt, level=$level, message=$message, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var createdAt: JsonField = JsonMissing.of() + private var level: JsonField = JsonMissing.of() + private var message: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobEvent: FineTuningJobEvent) = apply { + this.id = fineTuningJobEvent.id + this.createdAt = fineTuningJobEvent.createdAt + this.level = fineTuningJobEvent.level + this.message = fineTuningJobEvent.message + this.object_ = fineTuningJobEvent.object_ + additionalProperties(fineTuningJobEvent.additionalProperties) + } + + fun id(id: String) = id(JsonField.of(id)) + + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + fun createdAt(createdAt: Long) = createdAt(JsonField.of(createdAt)) + + @JsonProperty("created_at") + @ExcludeMissing + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun level(level: Level) = level(JsonField.of(level)) + + @JsonProperty("level") + @ExcludeMissing + fun level(level: JsonField) = apply { this.level = level } + + fun message(message: String) = message(JsonField.of(message)) + + @JsonProperty("message") + @ExcludeMissing + fun message(message: JsonField) = apply { this.message = message } + + fun object_(object_: Object) = object_(JsonField.of(object_)) + + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FineTuningJobEvent = + FineTuningJobEvent( + id, + createdAt, + level, + message, + object_, + additionalProperties.toUnmodifiable(), + ) + } + + class Level + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Level && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val INFO = Level(JsonField.of("info")) + + @JvmField val WARN = Level(JsonField.of("warn")) + + @JvmField val ERROR = Level(JsonField.of("error")) + + @JvmStatic fun of(value: String) = Level(JsonField.of(value)) + } + + enum class Known { + INFO, + WARN, + ERROR, + } + + enum class Value { + INFO, + WARN, + ERROR, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + INFO -> Value.INFO + WARN -> Value.WARN + ERROR -> Value.ERROR + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + INFO -> Known.INFO + WARN -> Known.WARN + ERROR -> Known.ERROR + else -> throw OpenAIInvalidDataException("Unknown Level: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val FINE_TUNING_JOB_EVENT = Object(JsonField.of("fine_tuning.job.event")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + FINE_TUNING_JOB_EVENT, + } + + enum class Value { + FINE_TUNING_JOB_EVENT, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + FINE_TUNING_JOB_EVENT -> Value.FINE_TUNING_JOB_EVENT + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + FINE_TUNING_JOB_EVENT -> Known.FINE_TUNING_JOB_EVENT + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsPage.kt new file mode 100644 index 0000000..e3bb7a5 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsPage.kt @@ -0,0 +1,181 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.blocking.fineTuning.JobService +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class FineTuningJobListEventsPage +private constructor( + private val jobsService: JobService, + private val params: FineTuningJobListEventsParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobListEventsPage && + this.jobsService == other.jobsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + jobsService, + params, + response, + ) + } + + override fun toString() = + "FineTuningJobListEventsPage{jobsService=$jobsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + FineTuningJobListEventsParams.builder().from(params).after(data().last().id()).build() + ) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { jobsService.listEvents(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(jobsService: JobService, params: FineTuningJobListEventsParams, response: Response) = + FineTuningJobListEventsPage( + jobsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "FineTuningJobListEventsPage.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + private val firstPage: FineTuningJobListEventsPage, + ) : 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().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsPageAsync.kt new file mode 100644 index 0000000..6b86f4f --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsPageAsync.kt @@ -0,0 +1,198 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.async.fineTuning.JobServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class FineTuningJobListEventsPageAsync +private constructor( + private val jobsService: JobServiceAsync, + private val params: FineTuningJobListEventsParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobListEventsPageAsync && + this.jobsService == other.jobsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + jobsService, + params, + response, + ) + } + + override fun toString() = + "FineTuningJobListEventsPageAsync{jobsService=$jobsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + FineTuningJobListEventsParams.builder().from(params).after(data().last().id()).build() + ) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { jobsService.listEvents(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of( + jobsService: JobServiceAsync, + params: FineTuningJobListEventsParams, + response: Response + ) = + FineTuningJobListEventsPageAsync( + jobsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "FineTuningJobListEventsPageAsync.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + private val firstPage: FineTuningJobListEventsPageAsync, + ) { + + fun forEach( + action: Predicate, + executor: Executor + ): CompletableFuture { + fun CompletableFuture>.forEach( + action: (FineTuningJobEvent) -> 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 } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsParams.kt new file mode 100644 index 0000000..069de27 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListEventsParams.kt @@ -0,0 +1,181 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FineTuningJobListEventsParams +constructor( + private val fineTuningJobId: String, + private val after: String?, + private val limit: Long?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fineTuningJobId(): String = fineTuningJobId + + fun after(): Optional = Optional.ofNullable(after) + + fun limit(): Optional = Optional.ofNullable(limit) + + @JvmSynthetic + internal fun getQueryParams(): Map> { + val params = mutableMapOf>() + this.after?.let { params.put("after", listOf(it.toString())) } + this.limit?.let { params.put("limit", listOf(it.toString())) } + params.putAll(additionalQueryParams) + return params.toUnmodifiable() + } + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fineTuningJobId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobListEventsParams && + this.fineTuningJobId == other.fineTuningJobId && + this.after == other.after && + this.limit == other.limit && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fineTuningJobId, + after, + limit, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FineTuningJobListEventsParams{fineTuningJobId=$fineTuningJobId, after=$after, limit=$limit, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fineTuningJobId: String? = null + private var after: String? = null + private var limit: Long? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobListEventsParams: FineTuningJobListEventsParams) = apply { + this.fineTuningJobId = fineTuningJobListEventsParams.fineTuningJobId + this.after = fineTuningJobListEventsParams.after + this.limit = fineTuningJobListEventsParams.limit + additionalQueryParams(fineTuningJobListEventsParams.additionalQueryParams) + additionalHeaders(fineTuningJobListEventsParams.additionalHeaders) + additionalBodyProperties(fineTuningJobListEventsParams.additionalBodyProperties) + } + + fun fineTuningJobId(fineTuningJobId: String) = apply { + this.fineTuningJobId = fineTuningJobId + } + + /** Identifier for the last event from the previous pagination request. */ + fun after(after: String) = apply { this.after = after } + + /** Number of events to retrieve. */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FineTuningJobListEventsParams = + FineTuningJobListEventsParams( + checkNotNull(fineTuningJobId) { "`fineTuningJobId` is required but was not set" }, + after, + limit, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListPage.kt new file mode 100644 index 0000000..ab04b6b --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListPage.kt @@ -0,0 +1,181 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.blocking.fineTuning.JobService +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class FineTuningJobListPage +private constructor( + private val jobsService: JobService, + private val params: FineTuningJobListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobListPage && + this.jobsService == other.jobsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + jobsService, + params, + response, + ) + } + + override fun toString() = + "FineTuningJobListPage{jobsService=$jobsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + FineTuningJobListParams.builder().from(params).after(data().last().id()).build() + ) + } + + fun getNextPage(): Optional { + return getNextPageParams().map { jobsService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(jobsService: JobService, params: FineTuningJobListParams, response: Response) = + FineTuningJobListPage( + jobsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "FineTuningJobListPage.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + private val firstPage: FineTuningJobListPage, + ) : 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().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListPageAsync.kt new file mode 100644 index 0000000..7e48ca4 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListPageAsync.kt @@ -0,0 +1,191 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.async.fineTuning.JobServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class FineTuningJobListPageAsync +private constructor( + private val jobsService: JobServiceAsync, + private val params: FineTuningJobListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobListPageAsync && + this.jobsService == other.jobsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + jobsService, + params, + response, + ) + } + + override fun toString() = + "FineTuningJobListPageAsync{jobsService=$jobsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + if (!hasNextPage()) { + return Optional.empty() + } + + return Optional.of( + FineTuningJobListParams.builder().from(params).after(data().last().id()).build() + ) + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { jobsService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(jobsService: JobServiceAsync, params: FineTuningJobListParams, response: Response) = + FineTuningJobListPageAsync( + jobsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash(data, additionalProperties) + } + + override fun toString() = + "FineTuningJobListPageAsync.Response{data=$data, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = Response(data, additionalProperties.toUnmodifiable()) + } + } + + class AutoPager + constructor( + private val firstPage: FineTuningJobListPageAsync, + ) { + + fun forEach(action: Predicate, executor: Executor): CompletableFuture { + fun CompletableFuture>.forEach( + action: (FineTuningJob) -> 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 } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListParams.kt new file mode 100644 index 0000000..a076064 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobListParams.kt @@ -0,0 +1,162 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class FineTuningJobListParams +constructor( + private val after: String?, + private val limit: Long?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun after(): Optional = Optional.ofNullable(after) + + fun limit(): Optional = Optional.ofNullable(limit) + + @JvmSynthetic + internal fun getQueryParams(): Map> { + val params = mutableMapOf>() + this.after?.let { params.put("after", listOf(it.toString())) } + this.limit?.let { params.put("limit", listOf(it.toString())) } + params.putAll(additionalQueryParams) + return params.toUnmodifiable() + } + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobListParams && + this.after == other.after && + this.limit == other.limit && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + after, + limit, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FineTuningJobListParams{after=$after, limit=$limit, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var after: String? = null + private var limit: Long? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobListParams: FineTuningJobListParams) = apply { + this.after = fineTuningJobListParams.after + this.limit = fineTuningJobListParams.limit + additionalQueryParams(fineTuningJobListParams.additionalQueryParams) + additionalHeaders(fineTuningJobListParams.additionalHeaders) + additionalBodyProperties(fineTuningJobListParams.additionalBodyProperties) + } + + /** Identifier for the last job from the previous pagination request. */ + fun after(after: String) = apply { this.after = after } + + /** Number of fine-tuning jobs to retrieve. */ + fun limit(limit: Long) = apply { this.limit = limit } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FineTuningJobListParams = + FineTuningJobListParams( + after, + limit, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobRetrieveParams.kt new file mode 100644 index 0000000..c61bd9c --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobRetrieveParams.kt @@ -0,0 +1,151 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects + +class FineTuningJobRetrieveParams +constructor( + private val fineTuningJobId: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun fineTuningJobId(): String = fineTuningJobId + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> fineTuningJobId + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobRetrieveParams && + this.fineTuningJobId == other.fineTuningJobId && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + fineTuningJobId, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "FineTuningJobRetrieveParams{fineTuningJobId=$fineTuningJobId, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var fineTuningJobId: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobRetrieveParams: FineTuningJobRetrieveParams) = apply { + this.fineTuningJobId = fineTuningJobRetrieveParams.fineTuningJobId + additionalQueryParams(fineTuningJobRetrieveParams.additionalQueryParams) + additionalHeaders(fineTuningJobRetrieveParams.additionalHeaders) + additionalBodyProperties(fineTuningJobRetrieveParams.additionalBodyProperties) + } + + fun fineTuningJobId(fineTuningJobId: String) = apply { + this.fineTuningJobId = fineTuningJobId + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): FineTuningJobRetrieveParams = + FineTuningJobRetrieveParams( + checkNotNull(fineTuningJobId) { "`fineTuningJobId` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobWandbIntegration.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobWandbIntegration.kt new file mode 100644 index 0000000..8e447ed --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobWandbIntegration.kt @@ -0,0 +1,217 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import java.util.Objects +import java.util.Optional + +/** + * The settings for your integration with Weights and Biases. This payload specifies the project + * that metrics will be sent to. Optionally, you can set an explicit display name for your run, add + * tags to your run, and set a default entity (team, username, etc) to be associated with your run. + */ +@JsonDeserialize(builder = FineTuningJobWandbIntegration.Builder::class) +@NoAutoDetect +class FineTuningJobWandbIntegration +private constructor( + private val project: JsonField, + private val name: JsonField, + private val entity: JsonField, + private val tags: JsonField>, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The name of the project that the new run will be created under. */ + fun project(): String = project.getRequired("project") + + /** A display name to set for the run. If not set, we will use the Job ID as the name. */ + fun name(): Optional = Optional.ofNullable(name.getNullable("name")) + + /** + * The entity to use for the run. This allows you to set the team or username of the WandB user + * that you would like associated with the run. If not set, the default entity for the + * registered WandB API key is used. + */ + fun entity(): Optional = Optional.ofNullable(entity.getNullable("entity")) + + /** + * A list of tags to be attached to the newly created run. These tags are passed through + * directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", + * "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + fun tags(): Optional> = Optional.ofNullable(tags.getNullable("tags")) + + /** The name of the project that the new run will be created under. */ + @JsonProperty("project") @ExcludeMissing fun _project() = project + + /** A display name to set for the run. If not set, we will use the Job ID as the name. */ + @JsonProperty("name") @ExcludeMissing fun _name() = name + + /** + * The entity to use for the run. This allows you to set the team or username of the WandB user + * that you would like associated with the run. If not set, the default entity for the + * registered WandB API key is used. + */ + @JsonProperty("entity") @ExcludeMissing fun _entity() = entity + + /** + * A list of tags to be attached to the newly created run. These tags are passed through + * directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", + * "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + @JsonProperty("tags") @ExcludeMissing fun _tags() = tags + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FineTuningJobWandbIntegration = apply { + if (!validated) { + project() + name() + entity() + tags() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobWandbIntegration && + this.project == other.project && + this.name == other.name && + this.entity == other.entity && + this.tags == other.tags && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + project, + name, + entity, + tags, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FineTuningJobWandbIntegration{project=$project, name=$name, entity=$entity, tags=$tags, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var project: JsonField = JsonMissing.of() + private var name: JsonField = JsonMissing.of() + private var entity: JsonField = JsonMissing.of() + private var tags: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(fineTuningJobWandbIntegration: FineTuningJobWandbIntegration) = apply { + this.project = fineTuningJobWandbIntegration.project + this.name = fineTuningJobWandbIntegration.name + this.entity = fineTuningJobWandbIntegration.entity + this.tags = fineTuningJobWandbIntegration.tags + additionalProperties(fineTuningJobWandbIntegration.additionalProperties) + } + + /** The name of the project that the new run will be created under. */ + fun project(project: String) = project(JsonField.of(project)) + + /** The name of the project that the new run will be created under. */ + @JsonProperty("project") + @ExcludeMissing + fun project(project: JsonField) = apply { this.project = project } + + /** A display name to set for the run. If not set, we will use the Job ID as the name. */ + fun name(name: String) = name(JsonField.of(name)) + + /** A display name to set for the run. If not set, we will use the Job ID as the name. */ + @JsonProperty("name") + @ExcludeMissing + fun name(name: JsonField) = apply { this.name = name } + + /** + * The entity to use for the run. This allows you to set the team or username of the WandB + * user that you would like associated with the run. If not set, the default entity for the + * registered WandB API key is used. + */ + fun entity(entity: String) = entity(JsonField.of(entity)) + + /** + * The entity to use for the run. This allows you to set the team or username of the WandB + * user that you would like associated with the run. If not set, the default entity for the + * registered WandB API key is used. + */ + @JsonProperty("entity") + @ExcludeMissing + fun entity(entity: JsonField) = apply { this.entity = entity } + + /** + * A list of tags to be attached to the newly created run. These tags are passed through + * directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", + * "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + fun tags(tags: List) = tags(JsonField.of(tags)) + + /** + * A list of tags to be attached to the newly created run. These tags are passed through + * directly to WandB. Some default tags are generated by OpenAI: "openai/finetune", + * "openai/{base-model}", "openai/{ftjob-abcdef}". + */ + @JsonProperty("tags") + @ExcludeMissing + fun tags(tags: JsonField>) = apply { this.tags = tags } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FineTuningJobWandbIntegration = + FineTuningJobWandbIntegration( + project, + name, + entity, + tags.map { it.toUnmodifiable() }, + additionalProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobWandbIntegrationObject.kt b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobWandbIntegrationObject.kt new file mode 100644 index 0000000..1d87764 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/FineTuningJobWandbIntegrationObject.kt @@ -0,0 +1,213 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects + +@JsonDeserialize(builder = FineTuningJobWandbIntegrationObject.Builder::class) +@NoAutoDetect +class FineTuningJobWandbIntegrationObject +private constructor( + private val type: JsonField, + private val wandb: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The type of the integration being enabled for the fine-tuning job */ + fun type(): Type = type.getRequired("type") + + /** + * The settings for your integration with Weights and Biases. This payload specifies the project + * that metrics will be sent to. Optionally, you can set an explicit display name for your run, + * add tags to your run, and set a default entity (team, username, etc) to be associated with + * your run. + */ + fun wandb(): FineTuningJobWandbIntegration = wandb.getRequired("wandb") + + /** The type of the integration being enabled for the fine-tuning job */ + @JsonProperty("type") @ExcludeMissing fun _type() = type + + /** + * The settings for your integration with Weights and Biases. This payload specifies the project + * that metrics will be sent to. Optionally, you can set an explicit display name for your run, + * add tags to your run, and set a default entity (team, username, etc) to be associated with + * your run. + */ + @JsonProperty("wandb") @ExcludeMissing fun _wandb() = wandb + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): FineTuningJobWandbIntegrationObject = apply { + if (!validated) { + type() + wandb().validate() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is FineTuningJobWandbIntegrationObject && + this.type == other.type && + this.wandb == other.wandb && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + type, + wandb, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "FineTuningJobWandbIntegrationObject{type=$type, wandb=$wandb, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var type: JsonField = JsonMissing.of() + private var wandb: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from( + fineTuningJobWandbIntegrationObject: FineTuningJobWandbIntegrationObject + ) = apply { + this.type = fineTuningJobWandbIntegrationObject.type + this.wandb = fineTuningJobWandbIntegrationObject.wandb + additionalProperties(fineTuningJobWandbIntegrationObject.additionalProperties) + } + + /** The type of the integration being enabled for the fine-tuning job */ + fun type(type: Type) = type(JsonField.of(type)) + + /** The type of the integration being enabled for the fine-tuning job */ + @JsonProperty("type") + @ExcludeMissing + fun type(type: JsonField) = apply { this.type = type } + + /** + * The settings for your integration with Weights and Biases. This payload specifies the + * project that metrics will be sent to. Optionally, you can set an explicit display name + * for your run, add tags to your run, and set a default entity (team, username, etc) to be + * associated with your run. + */ + fun wandb(wandb: FineTuningJobWandbIntegration) = wandb(JsonField.of(wandb)) + + /** + * The settings for your integration with Weights and Biases. This payload specifies the + * project that metrics will be sent to. Optionally, you can set an explicit display name + * for your run, add tags to your run, and set a default entity (team, username, etc) to be + * associated with your run. + */ + @JsonProperty("wandb") + @ExcludeMissing + fun wandb(wandb: JsonField) = apply { this.wandb = wandb } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): FineTuningJobWandbIntegrationObject = + FineTuningJobWandbIntegrationObject( + type, + wandb, + additionalProperties.toUnmodifiable(), + ) + } + + class Type + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Type && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val WANDB = Type(JsonField.of("wandb")) + + @JvmStatic fun of(value: String) = Type(JsonField.of(value)) + } + + enum class Known { + WANDB, + } + + enum class Value { + WANDB, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + WANDB -> Value.WANDB + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + WANDB -> Known.WANDB + else -> throw OpenAIInvalidDataException("Unknown Type: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/Model.kt b/openai-java-core/src/main/kotlin/com/openai/models/Model.kt new file mode 100644 index 0000000..f6d5b8b --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/Model.kt @@ -0,0 +1,232 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import java.util.Objects + +/** Describes an OpenAI model offering that can be used with the API. */ +@JsonDeserialize(builder = Model.Builder::class) +@NoAutoDetect +class Model +private constructor( + private val id: JsonField, + private val created: JsonField, + private val object_: JsonField, + private val ownedBy: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The model identifier, which can be referenced in the API endpoints. */ + fun id(): String = id.getRequired("id") + + /** The Unix timestamp (in seconds) when the model was created. */ + fun created(): Long = created.getRequired("created") + + /** The object type, which is always "model". */ + fun object_(): Object = object_.getRequired("object") + + /** The organization that owns the model. */ + fun ownedBy(): String = ownedBy.getRequired("owned_by") + + /** The model identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** The Unix timestamp (in seconds) when the model was created. */ + @JsonProperty("created") @ExcludeMissing fun _created() = created + + /** The object type, which is always "model". */ + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + /** The organization that owns the model. */ + @JsonProperty("owned_by") @ExcludeMissing fun _ownedBy() = ownedBy + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Model = apply { + if (!validated) { + id() + created() + object_() + ownedBy() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Model && + this.id == other.id && + this.created == other.created && + this.object_ == other.object_ && + this.ownedBy == other.ownedBy && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + created, + object_, + ownedBy, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Model{id=$id, created=$created, object_=$object_, ownedBy=$ownedBy, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var created: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var ownedBy: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(model: Model) = apply { + this.id = model.id + this.created = model.created + this.object_ = model.object_ + this.ownedBy = model.ownedBy + additionalProperties(model.additionalProperties) + } + + /** The model identifier, which can be referenced in the API endpoints. */ + fun id(id: String) = id(JsonField.of(id)) + + /** The model identifier, which can be referenced in the API endpoints. */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** The Unix timestamp (in seconds) when the model was created. */ + fun created(created: Long) = created(JsonField.of(created)) + + /** The Unix timestamp (in seconds) when the model was created. */ + @JsonProperty("created") + @ExcludeMissing + fun created(created: JsonField) = apply { this.created = created } + + /** The object type, which is always "model". */ + fun object_(object_: Object) = object_(JsonField.of(object_)) + + /** The object type, which is always "model". */ + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + /** The organization that owns the model. */ + fun ownedBy(ownedBy: String) = ownedBy(JsonField.of(ownedBy)) + + /** The organization that owns the model. */ + @JsonProperty("owned_by") + @ExcludeMissing + fun ownedBy(ownedBy: JsonField) = apply { this.ownedBy = ownedBy } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Model = + Model( + id, + created, + object_, + ownedBy, + additionalProperties.toUnmodifiable(), + ) + } + + class Object + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Object && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField val MODEL = Object(JsonField.of("model")) + + @JvmStatic fun of(value: String) = Object(JsonField.of(value)) + } + + enum class Known { + MODEL, + } + + enum class Value { + MODEL, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + MODEL -> Value.MODEL + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + MODEL -> Known.MODEL + else -> throw OpenAIInvalidDataException("Unknown Object: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModelDeleteParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModelDeleteParams.kt new file mode 100644 index 0000000..548889f --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModelDeleteParams.kt @@ -0,0 +1,155 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class ModelDeleteParams +constructor( + private val model: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun model(): String = model + + @JvmSynthetic + internal fun getBody(): Optional> { + return Optional.ofNullable(additionalBodyProperties.ifEmpty { null }) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> model + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelDeleteParams && + this.model == other.model && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + model, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "ModelDeleteParams{model=$model, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var model: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelDeleteParams: ModelDeleteParams) = apply { + this.model = modelDeleteParams.model + additionalQueryParams(modelDeleteParams.additionalQueryParams) + additionalHeaders(modelDeleteParams.additionalHeaders) + additionalBodyProperties(modelDeleteParams.additionalBodyProperties) + } + + fun model(model: String) = apply { this.model = model } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): ModelDeleteParams = + ModelDeleteParams( + checkNotNull(model) { "`model` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModelDeleted.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModelDeleted.kt new file mode 100644 index 0000000..6ef99c8 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModelDeleted.kt @@ -0,0 +1,144 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import java.util.Objects + +@JsonDeserialize(builder = ModelDeleted.Builder::class) +@NoAutoDetect +class ModelDeleted +private constructor( + private val id: JsonField, + private val deleted: JsonField, + private val object_: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + fun id(): String = id.getRequired("id") + + fun deleted(): Boolean = deleted.getRequired("deleted") + + fun object_(): String = object_.getRequired("object") + + @JsonProperty("id") @ExcludeMissing fun _id() = id + + @JsonProperty("deleted") @ExcludeMissing fun _deleted() = deleted + + @JsonProperty("object") @ExcludeMissing fun _object_() = object_ + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): ModelDeleted = apply { + if (!validated) { + id() + deleted() + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelDeleted && + this.id == other.id && + this.deleted == other.deleted && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + deleted, + object_, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "ModelDeleted{id=$id, deleted=$deleted, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var deleted: JsonField = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelDeleted: ModelDeleted) = apply { + this.id = modelDeleted.id + this.deleted = modelDeleted.deleted + this.object_ = modelDeleted.object_ + additionalProperties(modelDeleted.additionalProperties) + } + + fun id(id: String) = id(JsonField.of(id)) + + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + fun deleted(deleted: Boolean) = deleted(JsonField.of(deleted)) + + @JsonProperty("deleted") + @ExcludeMissing + fun deleted(deleted: JsonField) = apply { this.deleted = deleted } + + fun object_(object_: String) = object_(JsonField.of(object_)) + + @JsonProperty("object") + @ExcludeMissing + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): ModelDeleted = + ModelDeleted( + id, + deleted, + object_, + additionalProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModelListPage.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModelListPage.kt new file mode 100644 index 0000000..04bf169 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModelListPage.kt @@ -0,0 +1,201 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.blocking.ModelService +import java.util.Objects +import java.util.Optional +import java.util.stream.Stream +import java.util.stream.StreamSupport + +class ModelListPage +private constructor( + private val modelsService: ModelService, + private val params: ModelListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun object_(): String = response().object_() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelListPage && + this.modelsService == other.modelsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + modelsService, + params, + response, + ) + } + + override fun toString() = + "ModelListPage{modelsService=$modelsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): Optional { + return getNextPageParams().map { modelsService.list(it) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(modelsService: ModelService, params: ModelListParams, response: Response) = + ModelListPage( + modelsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val object_: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun object_(): String = object_.getRequired("object") + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("object") + fun _object_(): Optional> = Optional.ofNullable(object_) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash( + data, + object_, + additionalProperties, + ) + } + + override fun toString() = + "ModelListPage.Response{data=$data, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.object_ = page.object_ + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun object_(object_: String) = object_(JsonField.of(object_)) + + @JsonProperty("object") + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + object_, + additionalProperties.toUnmodifiable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: ModelListPage, + ) : 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().orElse(null) ?: break + index = 0 + } + } + + fun stream(): Stream { + return StreamSupport.stream(spliterator(), false) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModelListPageAsync.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModelListPageAsync.kt new file mode 100644 index 0000000..53ed040 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModelListPageAsync.kt @@ -0,0 +1,211 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.services.async.ModelServiceAsync +import java.util.Objects +import java.util.Optional +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import java.util.function.Predicate + +class ModelListPageAsync +private constructor( + private val modelsService: ModelServiceAsync, + private val params: ModelListParams, + private val response: Response, +) { + + fun response(): Response = response + + fun data(): List = response().data() + + fun object_(): String = response().object_() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelListPageAsync && + this.modelsService == other.modelsService && + this.params == other.params && + this.response == other.response + } + + override fun hashCode(): Int { + return Objects.hash( + modelsService, + params, + response, + ) + } + + override fun toString() = + "ModelListPageAsync{modelsService=$modelsService, params=$params, response=$response}" + + fun hasNextPage(): Boolean { + return !data().isEmpty() + } + + fun getNextPageParams(): Optional { + return Optional.empty() + } + + fun getNextPage(): CompletableFuture> { + return getNextPageParams() + .map { modelsService.list(it).thenApply { Optional.of(it) } } + .orElseGet { CompletableFuture.completedFuture(Optional.empty()) } + } + + fun autoPager(): AutoPager = AutoPager(this) + + companion object { + + @JvmStatic + fun of(modelsService: ModelServiceAsync, params: ModelListParams, response: Response) = + ModelListPageAsync( + modelsService, + params, + response, + ) + } + + @JsonDeserialize(builder = Response.Builder::class) + @NoAutoDetect + class Response + constructor( + private val data: JsonField>, + private val object_: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + fun data(): List = data.getNullable("data") ?: listOf() + + fun object_(): String = object_.getRequired("object") + + @JsonProperty("data") + fun _data(): Optional>> = Optional.ofNullable(data) + + @JsonProperty("object") + fun _object_(): Optional> = Optional.ofNullable(object_) + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Response = apply { + if (!validated) { + data().map { it.validate() } + object_() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Response && + this.data == other.data && + this.object_ == other.object_ && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + return Objects.hash( + data, + object_, + additionalProperties, + ) + } + + override fun toString() = + "ModelListPageAsync.Response{data=$data, object_=$object_, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var data: JsonField> = JsonMissing.of() + private var object_: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(page: Response) = apply { + this.data = page.data + this.object_ = page.object_ + this.additionalProperties.putAll(page.additionalProperties) + } + + fun data(data: List) = data(JsonField.of(data)) + + @JsonProperty("data") + fun data(data: JsonField>) = apply { this.data = data } + + fun object_(object_: String) = object_(JsonField.of(object_)) + + @JsonProperty("object") + fun object_(object_: JsonField) = apply { this.object_ = object_ } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun build() = + Response( + data, + object_, + additionalProperties.toUnmodifiable(), + ) + } + } + + class AutoPager + constructor( + private val firstPage: ModelListPageAsync, + ) { + + fun forEach(action: Predicate, executor: Executor): CompletableFuture { + fun CompletableFuture>.forEach( + action: (Model) -> 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 } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModelListParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModelListParams.kt new file mode 100644 index 0000000..9a2fa3b --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModelListParams.kt @@ -0,0 +1,132 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects + +class ModelListParams +constructor( + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelListParams && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "ModelListParams{additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelListParams: ModelListParams) = apply { + additionalQueryParams(modelListParams.additionalQueryParams) + additionalHeaders(modelListParams.additionalHeaders) + additionalBodyProperties(modelListParams.additionalBodyProperties) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): ModelListParams = + ModelListParams( + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModelRetrieveParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModelRetrieveParams.kt new file mode 100644 index 0000000..e94b218 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModelRetrieveParams.kt @@ -0,0 +1,149 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import com.openai.models.* +import java.util.Objects + +class ModelRetrieveParams +constructor( + private val model: String, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun model(): String = model + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + fun getPathParam(index: Int): String { + return when (index) { + 0 -> model + else -> "" + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModelRetrieveParams && + this.model == other.model && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + model, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "ModelRetrieveParams{model=$model, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var model: String? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(modelRetrieveParams: ModelRetrieveParams) = apply { + this.model = modelRetrieveParams.model + additionalQueryParams(modelRetrieveParams.additionalQueryParams) + additionalHeaders(modelRetrieveParams.additionalHeaders) + additionalBodyProperties(modelRetrieveParams.additionalBodyProperties) + } + + fun model(model: String) = apply { this.model = model } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): ModelRetrieveParams = + ModelRetrieveParams( + checkNotNull(model) { "`model` is required but was not set" }, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/Moderation.kt b/openai-java-core/src/main/kotlin/com/openai/models/Moderation.kt new file mode 100644 index 0000000..f665210 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/Moderation.kt @@ -0,0 +1,919 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import java.util.Objects + +@JsonDeserialize(builder = Moderation.Builder::class) +@NoAutoDetect +class Moderation +private constructor( + private val flagged: JsonField, + private val categories: JsonField, + private val categoryScores: JsonField, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** Whether any of the below categories are flagged. */ + fun flagged(): Boolean = flagged.getRequired("flagged") + + /** A list of the categories, and whether they are flagged or not. */ + fun categories(): Categories = categories.getRequired("categories") + + /** A list of the categories along with their scores as predicted by model. */ + fun categoryScores(): CategoryScores = categoryScores.getRequired("category_scores") + + /** Whether any of the below categories are flagged. */ + @JsonProperty("flagged") @ExcludeMissing fun _flagged() = flagged + + /** A list of the categories, and whether they are flagged or not. */ + @JsonProperty("categories") @ExcludeMissing fun _categories() = categories + + /** A list of the categories along with their scores as predicted by model. */ + @JsonProperty("category_scores") @ExcludeMissing fun _categoryScores() = categoryScores + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Moderation = apply { + if (!validated) { + flagged() + categories().validate() + categoryScores().validate() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Moderation && + this.flagged == other.flagged && + this.categories == other.categories && + this.categoryScores == other.categoryScores && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + flagged, + categories, + categoryScores, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Moderation{flagged=$flagged, categories=$categories, categoryScores=$categoryScores, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var flagged: JsonField = JsonMissing.of() + private var categories: JsonField = JsonMissing.of() + private var categoryScores: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(moderation: Moderation) = apply { + this.flagged = moderation.flagged + this.categories = moderation.categories + this.categoryScores = moderation.categoryScores + additionalProperties(moderation.additionalProperties) + } + + /** Whether any of the below categories are flagged. */ + fun flagged(flagged: Boolean) = flagged(JsonField.of(flagged)) + + /** Whether any of the below categories are flagged. */ + @JsonProperty("flagged") + @ExcludeMissing + fun flagged(flagged: JsonField) = apply { this.flagged = flagged } + + /** A list of the categories, and whether they are flagged or not. */ + fun categories(categories: Categories) = categories(JsonField.of(categories)) + + /** A list of the categories, and whether they are flagged or not. */ + @JsonProperty("categories") + @ExcludeMissing + fun categories(categories: JsonField) = apply { this.categories = categories } + + /** A list of the categories along with their scores as predicted by model. */ + fun categoryScores(categoryScores: CategoryScores) = + categoryScores(JsonField.of(categoryScores)) + + /** A list of the categories along with their scores as predicted by model. */ + @JsonProperty("category_scores") + @ExcludeMissing + fun categoryScores(categoryScores: JsonField) = apply { + this.categoryScores = categoryScores + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Moderation = + Moderation( + flagged, + categories, + categoryScores, + additionalProperties.toUnmodifiable(), + ) + } + + /** A list of the categories, and whether they are flagged or not. */ + @JsonDeserialize(builder = Categories.Builder::class) + @NoAutoDetect + class Categories + private constructor( + private val hate: JsonField, + private val hateThreatening: JsonField, + private val harassment: JsonField, + private val harassmentThreatening: JsonField, + private val selfHarm: JsonField, + private val selfHarmIntent: JsonField, + private val selfHarmInstructions: JsonField, + private val sexual: JsonField, + private val sexualMinors: JsonField, + private val violence: JsonField, + private val violenceGraphic: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** + * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, + * religion, nationality, sexual orientation, disability status, or caste. Hateful content + * aimed at non-protected groups (e.g., chess players) is harassment. + */ + fun hate(): Boolean = hate.getRequired("hate") + + /** + * Hateful content that also includes violence or serious harm towards the targeted group + * based on race, gender, ethnicity, religion, nationality, sexual orientation, disability + * status, or caste. + */ + fun hateThreatening(): Boolean = hateThreatening.getRequired("hate/threatening") + + /** Content that expresses, incites, or promotes harassing language towards any target. */ + fun harassment(): Boolean = harassment.getRequired("harassment") + + /** Harassment content that also includes violence or serious harm towards any target. */ + fun harassmentThreatening(): Boolean = + harassmentThreatening.getRequired("harassment/threatening") + + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, + * cutting, and eating disorders. + */ + fun selfHarm(): Boolean = selfHarm.getRequired("self-harm") + + /** + * Content where the speaker expresses that they are engaging or intend to engage in acts of + * self-harm, such as suicide, cutting, and eating disorders. + */ + fun selfHarmIntent(): Boolean = selfHarmIntent.getRequired("self-harm/intent") + + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, and + * eating disorders, or that gives instructions or advice on how to commit such acts. + */ + fun selfHarmInstructions(): Boolean = + selfHarmInstructions.getRequired("self-harm/instructions") + + /** + * Content meant to arouse sexual excitement, such as the description of sexual activity, or + * that promotes sexual services (excluding sex education and wellness). + */ + fun sexual(): Boolean = sexual.getRequired("sexual") + + /** Sexual content that includes an individual who is under 18 years old. */ + fun sexualMinors(): Boolean = sexualMinors.getRequired("sexual/minors") + + /** Content that depicts death, violence, or physical injury. */ + fun violence(): Boolean = violence.getRequired("violence") + + /** Content that depicts death, violence, or physical injury in graphic detail. */ + fun violenceGraphic(): Boolean = violenceGraphic.getRequired("violence/graphic") + + /** + * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, + * religion, nationality, sexual orientation, disability status, or caste. Hateful content + * aimed at non-protected groups (e.g., chess players) is harassment. + */ + @JsonProperty("hate") @ExcludeMissing fun _hate() = hate + + /** + * Hateful content that also includes violence or serious harm towards the targeted group + * based on race, gender, ethnicity, religion, nationality, sexual orientation, disability + * status, or caste. + */ + @JsonProperty("hate/threatening") @ExcludeMissing fun _hateThreatening() = hateThreatening + + /** Content that expresses, incites, or promotes harassing language towards any target. */ + @JsonProperty("harassment") @ExcludeMissing fun _harassment() = harassment + + /** Harassment content that also includes violence or serious harm towards any target. */ + @JsonProperty("harassment/threatening") + @ExcludeMissing + fun _harassmentThreatening() = harassmentThreatening + + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, + * cutting, and eating disorders. + */ + @JsonProperty("self-harm") @ExcludeMissing fun _selfHarm() = selfHarm + + /** + * Content where the speaker expresses that they are engaging or intend to engage in acts of + * self-harm, such as suicide, cutting, and eating disorders. + */ + @JsonProperty("self-harm/intent") @ExcludeMissing fun _selfHarmIntent() = selfHarmIntent + + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, and + * eating disorders, or that gives instructions or advice on how to commit such acts. + */ + @JsonProperty("self-harm/instructions") + @ExcludeMissing + fun _selfHarmInstructions() = selfHarmInstructions + + /** + * Content meant to arouse sexual excitement, such as the description of sexual activity, or + * that promotes sexual services (excluding sex education and wellness). + */ + @JsonProperty("sexual") @ExcludeMissing fun _sexual() = sexual + + /** Sexual content that includes an individual who is under 18 years old. */ + @JsonProperty("sexual/minors") @ExcludeMissing fun _sexualMinors() = sexualMinors + + /** Content that depicts death, violence, or physical injury. */ + @JsonProperty("violence") @ExcludeMissing fun _violence() = violence + + /** Content that depicts death, violence, or physical injury in graphic detail. */ + @JsonProperty("violence/graphic") @ExcludeMissing fun _violenceGraphic() = violenceGraphic + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): Categories = apply { + if (!validated) { + hate() + hateThreatening() + harassment() + harassmentThreatening() + selfHarm() + selfHarmIntent() + selfHarmInstructions() + sexual() + sexualMinors() + violence() + violenceGraphic() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Categories && + this.hate == other.hate && + this.hateThreatening == other.hateThreatening && + this.harassment == other.harassment && + this.harassmentThreatening == other.harassmentThreatening && + this.selfHarm == other.selfHarm && + this.selfHarmIntent == other.selfHarmIntent && + this.selfHarmInstructions == other.selfHarmInstructions && + this.sexual == other.sexual && + this.sexualMinors == other.sexualMinors && + this.violence == other.violence && + this.violenceGraphic == other.violenceGraphic && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + hate, + hateThreatening, + harassment, + harassmentThreatening, + selfHarm, + selfHarmIntent, + selfHarmInstructions, + sexual, + sexualMinors, + violence, + violenceGraphic, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "Categories{hate=$hate, hateThreatening=$hateThreatening, harassment=$harassment, harassmentThreatening=$harassmentThreatening, selfHarm=$selfHarm, selfHarmIntent=$selfHarmIntent, selfHarmInstructions=$selfHarmInstructions, sexual=$sexual, sexualMinors=$sexualMinors, violence=$violence, violenceGraphic=$violenceGraphic, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var hate: JsonField = JsonMissing.of() + private var hateThreatening: JsonField = JsonMissing.of() + private var harassment: JsonField = JsonMissing.of() + private var harassmentThreatening: JsonField = JsonMissing.of() + private var selfHarm: JsonField = JsonMissing.of() + private var selfHarmIntent: JsonField = JsonMissing.of() + private var selfHarmInstructions: JsonField = JsonMissing.of() + private var sexual: JsonField = JsonMissing.of() + private var sexualMinors: JsonField = JsonMissing.of() + private var violence: JsonField = JsonMissing.of() + private var violenceGraphic: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(categories: Categories) = apply { + this.hate = categories.hate + this.hateThreatening = categories.hateThreatening + this.harassment = categories.harassment + this.harassmentThreatening = categories.harassmentThreatening + this.selfHarm = categories.selfHarm + this.selfHarmIntent = categories.selfHarmIntent + this.selfHarmInstructions = categories.selfHarmInstructions + this.sexual = categories.sexual + this.sexualMinors = categories.sexualMinors + this.violence = categories.violence + this.violenceGraphic = categories.violenceGraphic + additionalProperties(categories.additionalProperties) + } + + /** + * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, + * religion, nationality, sexual orientation, disability status, or caste. Hateful + * content aimed at non-protected groups (e.g., chess players) is harassment. + */ + fun hate(hate: Boolean) = hate(JsonField.of(hate)) + + /** + * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, + * religion, nationality, sexual orientation, disability status, or caste. Hateful + * content aimed at non-protected groups (e.g., chess players) is harassment. + */ + @JsonProperty("hate") + @ExcludeMissing + fun hate(hate: JsonField) = apply { this.hate = hate } + + /** + * Hateful content that also includes violence or serious harm towards the targeted + * group based on race, gender, ethnicity, religion, nationality, sexual orientation, + * disability status, or caste. + */ + fun hateThreatening(hateThreatening: Boolean) = + hateThreatening(JsonField.of(hateThreatening)) + + /** + * Hateful content that also includes violence or serious harm towards the targeted + * group based on race, gender, ethnicity, religion, nationality, sexual orientation, + * disability status, or caste. + */ + @JsonProperty("hate/threatening") + @ExcludeMissing + fun hateThreatening(hateThreatening: JsonField) = apply { + this.hateThreatening = hateThreatening + } + + /** + * Content that expresses, incites, or promotes harassing language towards any target. + */ + fun harassment(harassment: Boolean) = harassment(JsonField.of(harassment)) + + /** + * Content that expresses, incites, or promotes harassing language towards any target. + */ + @JsonProperty("harassment") + @ExcludeMissing + fun harassment(harassment: JsonField) = apply { this.harassment = harassment } + + /** + * Harassment content that also includes violence or serious harm towards any target. + */ + fun harassmentThreatening(harassmentThreatening: Boolean) = + harassmentThreatening(JsonField.of(harassmentThreatening)) + + /** + * Harassment content that also includes violence or serious harm towards any target. + */ + @JsonProperty("harassment/threatening") + @ExcludeMissing + fun harassmentThreatening(harassmentThreatening: JsonField) = apply { + this.harassmentThreatening = harassmentThreatening + } + + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, + * cutting, and eating disorders. + */ + fun selfHarm(selfHarm: Boolean) = selfHarm(JsonField.of(selfHarm)) + + /** + * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, + * cutting, and eating disorders. + */ + @JsonProperty("self-harm") + @ExcludeMissing + fun selfHarm(selfHarm: JsonField) = apply { this.selfHarm = selfHarm } + + /** + * Content where the speaker expresses that they are engaging or intend to engage in + * acts of self-harm, such as suicide, cutting, and eating disorders. + */ + fun selfHarmIntent(selfHarmIntent: Boolean) = + selfHarmIntent(JsonField.of(selfHarmIntent)) + + /** + * Content where the speaker expresses that they are engaging or intend to engage in + * acts of self-harm, such as suicide, cutting, and eating disorders. + */ + @JsonProperty("self-harm/intent") + @ExcludeMissing + fun selfHarmIntent(selfHarmIntent: JsonField) = apply { + this.selfHarmIntent = selfHarmIntent + } + + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, and + * eating disorders, or that gives instructions or advice on how to commit such acts. + */ + fun selfHarmInstructions(selfHarmInstructions: Boolean) = + selfHarmInstructions(JsonField.of(selfHarmInstructions)) + + /** + * Content that encourages performing acts of self-harm, such as suicide, cutting, and + * eating disorders, or that gives instructions or advice on how to commit such acts. + */ + @JsonProperty("self-harm/instructions") + @ExcludeMissing + fun selfHarmInstructions(selfHarmInstructions: JsonField) = apply { + this.selfHarmInstructions = selfHarmInstructions + } + + /** + * Content meant to arouse sexual excitement, such as the description of sexual + * activity, or that promotes sexual services (excluding sex education and wellness). + */ + fun sexual(sexual: Boolean) = sexual(JsonField.of(sexual)) + + /** + * Content meant to arouse sexual excitement, such as the description of sexual + * activity, or that promotes sexual services (excluding sex education and wellness). + */ + @JsonProperty("sexual") + @ExcludeMissing + fun sexual(sexual: JsonField) = apply { this.sexual = sexual } + + /** Sexual content that includes an individual who is under 18 years old. */ + fun sexualMinors(sexualMinors: Boolean) = sexualMinors(JsonField.of(sexualMinors)) + + /** Sexual content that includes an individual who is under 18 years old. */ + @JsonProperty("sexual/minors") + @ExcludeMissing + fun sexualMinors(sexualMinors: JsonField) = apply { + this.sexualMinors = sexualMinors + } + + /** Content that depicts death, violence, or physical injury. */ + fun violence(violence: Boolean) = violence(JsonField.of(violence)) + + /** Content that depicts death, violence, or physical injury. */ + @JsonProperty("violence") + @ExcludeMissing + fun violence(violence: JsonField) = apply { this.violence = violence } + + /** Content that depicts death, violence, or physical injury in graphic detail. */ + fun violenceGraphic(violenceGraphic: Boolean) = + violenceGraphic(JsonField.of(violenceGraphic)) + + /** Content that depicts death, violence, or physical injury in graphic detail. */ + @JsonProperty("violence/graphic") + @ExcludeMissing + fun violenceGraphic(violenceGraphic: JsonField) = apply { + this.violenceGraphic = violenceGraphic + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): Categories = + Categories( + hate, + hateThreatening, + harassment, + harassmentThreatening, + selfHarm, + selfHarmIntent, + selfHarmInstructions, + sexual, + sexualMinors, + violence, + violenceGraphic, + additionalProperties.toUnmodifiable(), + ) + } + } + + /** A list of the categories along with their scores as predicted by model. */ + @JsonDeserialize(builder = CategoryScores.Builder::class) + @NoAutoDetect + class CategoryScores + private constructor( + private val hate: JsonField, + private val hateThreatening: JsonField, + private val harassment: JsonField, + private val harassmentThreatening: JsonField, + private val selfHarm: JsonField, + private val selfHarmIntent: JsonField, + private val selfHarmInstructions: JsonField, + private val sexual: JsonField, + private val sexualMinors: JsonField, + private val violence: JsonField, + private val violenceGraphic: JsonField, + private val additionalProperties: Map, + ) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The score for the category 'hate'. */ + fun hate(): Double = hate.getRequired("hate") + + /** The score for the category 'hate/threatening'. */ + fun hateThreatening(): Double = hateThreatening.getRequired("hate/threatening") + + /** The score for the category 'harassment'. */ + fun harassment(): Double = harassment.getRequired("harassment") + + /** The score for the category 'harassment/threatening'. */ + fun harassmentThreatening(): Double = + harassmentThreatening.getRequired("harassment/threatening") + + /** The score for the category 'self-harm'. */ + fun selfHarm(): Double = selfHarm.getRequired("self-harm") + + /** The score for the category 'self-harm/intent'. */ + fun selfHarmIntent(): Double = selfHarmIntent.getRequired("self-harm/intent") + + /** The score for the category 'self-harm/instructions'. */ + fun selfHarmInstructions(): Double = + selfHarmInstructions.getRequired("self-harm/instructions") + + /** The score for the category 'sexual'. */ + fun sexual(): Double = sexual.getRequired("sexual") + + /** The score for the category 'sexual/minors'. */ + fun sexualMinors(): Double = sexualMinors.getRequired("sexual/minors") + + /** The score for the category 'violence'. */ + fun violence(): Double = violence.getRequired("violence") + + /** The score for the category 'violence/graphic'. */ + fun violenceGraphic(): Double = violenceGraphic.getRequired("violence/graphic") + + /** The score for the category 'hate'. */ + @JsonProperty("hate") @ExcludeMissing fun _hate() = hate + + /** The score for the category 'hate/threatening'. */ + @JsonProperty("hate/threatening") @ExcludeMissing fun _hateThreatening() = hateThreatening + + /** The score for the category 'harassment'. */ + @JsonProperty("harassment") @ExcludeMissing fun _harassment() = harassment + + /** The score for the category 'harassment/threatening'. */ + @JsonProperty("harassment/threatening") + @ExcludeMissing + fun _harassmentThreatening() = harassmentThreatening + + /** The score for the category 'self-harm'. */ + @JsonProperty("self-harm") @ExcludeMissing fun _selfHarm() = selfHarm + + /** The score for the category 'self-harm/intent'. */ + @JsonProperty("self-harm/intent") @ExcludeMissing fun _selfHarmIntent() = selfHarmIntent + + /** The score for the category 'self-harm/instructions'. */ + @JsonProperty("self-harm/instructions") + @ExcludeMissing + fun _selfHarmInstructions() = selfHarmInstructions + + /** The score for the category 'sexual'. */ + @JsonProperty("sexual") @ExcludeMissing fun _sexual() = sexual + + /** The score for the category 'sexual/minors'. */ + @JsonProperty("sexual/minors") @ExcludeMissing fun _sexualMinors() = sexualMinors + + /** The score for the category 'violence'. */ + @JsonProperty("violence") @ExcludeMissing fun _violence() = violence + + /** The score for the category 'violence/graphic'. */ + @JsonProperty("violence/graphic") @ExcludeMissing fun _violenceGraphic() = violenceGraphic + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): CategoryScores = apply { + if (!validated) { + hate() + hateThreatening() + harassment() + harassmentThreatening() + selfHarm() + selfHarmIntent() + selfHarmInstructions() + sexual() + sexualMinors() + violence() + violenceGraphic() + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is CategoryScores && + this.hate == other.hate && + this.hateThreatening == other.hateThreatening && + this.harassment == other.harassment && + this.harassmentThreatening == other.harassmentThreatening && + this.selfHarm == other.selfHarm && + this.selfHarmIntent == other.selfHarmIntent && + this.selfHarmInstructions == other.selfHarmInstructions && + this.sexual == other.sexual && + this.sexualMinors == other.sexualMinors && + this.violence == other.violence && + this.violenceGraphic == other.violenceGraphic && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + hate, + hateThreatening, + harassment, + harassmentThreatening, + selfHarm, + selfHarmIntent, + selfHarmInstructions, + sexual, + sexualMinors, + violence, + violenceGraphic, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "CategoryScores{hate=$hate, hateThreatening=$hateThreatening, harassment=$harassment, harassmentThreatening=$harassmentThreatening, selfHarm=$selfHarm, selfHarmIntent=$selfHarmIntent, selfHarmInstructions=$selfHarmInstructions, sexual=$sexual, sexualMinors=$sexualMinors, violence=$violence, violenceGraphic=$violenceGraphic, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var hate: JsonField = JsonMissing.of() + private var hateThreatening: JsonField = JsonMissing.of() + private var harassment: JsonField = JsonMissing.of() + private var harassmentThreatening: JsonField = JsonMissing.of() + private var selfHarm: JsonField = JsonMissing.of() + private var selfHarmIntent: JsonField = JsonMissing.of() + private var selfHarmInstructions: JsonField = JsonMissing.of() + private var sexual: JsonField = JsonMissing.of() + private var sexualMinors: JsonField = JsonMissing.of() + private var violence: JsonField = JsonMissing.of() + private var violenceGraphic: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(categoryScores: CategoryScores) = apply { + this.hate = categoryScores.hate + this.hateThreatening = categoryScores.hateThreatening + this.harassment = categoryScores.harassment + this.harassmentThreatening = categoryScores.harassmentThreatening + this.selfHarm = categoryScores.selfHarm + this.selfHarmIntent = categoryScores.selfHarmIntent + this.selfHarmInstructions = categoryScores.selfHarmInstructions + this.sexual = categoryScores.sexual + this.sexualMinors = categoryScores.sexualMinors + this.violence = categoryScores.violence + this.violenceGraphic = categoryScores.violenceGraphic + additionalProperties(categoryScores.additionalProperties) + } + + /** The score for the category 'hate'. */ + fun hate(hate: Double) = hate(JsonField.of(hate)) + + /** The score for the category 'hate'. */ + @JsonProperty("hate") + @ExcludeMissing + fun hate(hate: JsonField) = apply { this.hate = hate } + + /** The score for the category 'hate/threatening'. */ + fun hateThreatening(hateThreatening: Double) = + hateThreatening(JsonField.of(hateThreatening)) + + /** The score for the category 'hate/threatening'. */ + @JsonProperty("hate/threatening") + @ExcludeMissing + fun hateThreatening(hateThreatening: JsonField) = apply { + this.hateThreatening = hateThreatening + } + + /** The score for the category 'harassment'. */ + fun harassment(harassment: Double) = harassment(JsonField.of(harassment)) + + /** The score for the category 'harassment'. */ + @JsonProperty("harassment") + @ExcludeMissing + fun harassment(harassment: JsonField) = apply { this.harassment = harassment } + + /** The score for the category 'harassment/threatening'. */ + fun harassmentThreatening(harassmentThreatening: Double) = + harassmentThreatening(JsonField.of(harassmentThreatening)) + + /** The score for the category 'harassment/threatening'. */ + @JsonProperty("harassment/threatening") + @ExcludeMissing + fun harassmentThreatening(harassmentThreatening: JsonField) = apply { + this.harassmentThreatening = harassmentThreatening + } + + /** The score for the category 'self-harm'. */ + fun selfHarm(selfHarm: Double) = selfHarm(JsonField.of(selfHarm)) + + /** The score for the category 'self-harm'. */ + @JsonProperty("self-harm") + @ExcludeMissing + fun selfHarm(selfHarm: JsonField) = apply { this.selfHarm = selfHarm } + + /** The score for the category 'self-harm/intent'. */ + fun selfHarmIntent(selfHarmIntent: Double) = + selfHarmIntent(JsonField.of(selfHarmIntent)) + + /** The score for the category 'self-harm/intent'. */ + @JsonProperty("self-harm/intent") + @ExcludeMissing + fun selfHarmIntent(selfHarmIntent: JsonField) = apply { + this.selfHarmIntent = selfHarmIntent + } + + /** The score for the category 'self-harm/instructions'. */ + fun selfHarmInstructions(selfHarmInstructions: Double) = + selfHarmInstructions(JsonField.of(selfHarmInstructions)) + + /** The score for the category 'self-harm/instructions'. */ + @JsonProperty("self-harm/instructions") + @ExcludeMissing + fun selfHarmInstructions(selfHarmInstructions: JsonField) = apply { + this.selfHarmInstructions = selfHarmInstructions + } + + /** The score for the category 'sexual'. */ + fun sexual(sexual: Double) = sexual(JsonField.of(sexual)) + + /** The score for the category 'sexual'. */ + @JsonProperty("sexual") + @ExcludeMissing + fun sexual(sexual: JsonField) = apply { this.sexual = sexual } + + /** The score for the category 'sexual/minors'. */ + fun sexualMinors(sexualMinors: Double) = sexualMinors(JsonField.of(sexualMinors)) + + /** The score for the category 'sexual/minors'. */ + @JsonProperty("sexual/minors") + @ExcludeMissing + fun sexualMinors(sexualMinors: JsonField) = apply { + this.sexualMinors = sexualMinors + } + + /** The score for the category 'violence'. */ + fun violence(violence: Double) = violence(JsonField.of(violence)) + + /** The score for the category 'violence'. */ + @JsonProperty("violence") + @ExcludeMissing + fun violence(violence: JsonField) = apply { this.violence = violence } + + /** The score for the category 'violence/graphic'. */ + fun violenceGraphic(violenceGraphic: Double) = + violenceGraphic(JsonField.of(violenceGraphic)) + + /** The score for the category 'violence/graphic'. */ + @JsonProperty("violence/graphic") + @ExcludeMissing + fun violenceGraphic(violenceGraphic: JsonField) = apply { + this.violenceGraphic = violenceGraphic + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): CategoryScores = + CategoryScores( + hate, + hateThreatening, + harassment, + harassmentThreatening, + selfHarm, + selfHarmIntent, + selfHarmInstructions, + sexual, + sexualMinors, + violence, + violenceGraphic, + additionalProperties.toUnmodifiable(), + ) + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModerationCreateParams.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModerationCreateParams.kt new file mode 100644 index 0000000..a8c6661 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModerationCreateParams.kt @@ -0,0 +1,625 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.core.JsonGenerator +import com.fasterxml.jackson.core.ObjectCodec +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.SerializerProvider +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.fasterxml.jackson.databind.annotation.JsonSerialize +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.openai.core.BaseDeserializer +import com.openai.core.BaseSerializer +import com.openai.core.Enum +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.getOrThrow +import com.openai.core.toUnmodifiable +import com.openai.errors.OpenAIInvalidDataException +import com.openai.models.* +import java.util.Objects +import java.util.Optional + +class ModerationCreateParams +constructor( + private val input: Input, + private val model: Model?, + private val additionalQueryParams: Map>, + private val additionalHeaders: Map>, + private val additionalBodyProperties: Map, +) { + + fun input(): Input = input + + fun model(): Optional = Optional.ofNullable(model) + + @JvmSynthetic + internal fun getBody(): ModerationCreateBody { + return ModerationCreateBody( + input, + model, + additionalBodyProperties, + ) + } + + @JvmSynthetic internal fun getQueryParams(): Map> = additionalQueryParams + + @JvmSynthetic internal fun getHeaders(): Map> = additionalHeaders + + @JsonDeserialize(builder = ModerationCreateBody.Builder::class) + @NoAutoDetect + class ModerationCreateBody + internal constructor( + private val input: Input?, + private val model: Model?, + private val additionalProperties: Map, + ) { + + private var hashCode: Int = 0 + + /** The input text to classify */ + @JsonProperty("input") fun input(): Input? = input + + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded over time. + * This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the model. + * Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + @JsonProperty("model") fun model(): Model? = model + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModerationCreateBody && + this.input == other.input && + this.model == other.model && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + input, + model, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "ModerationCreateBody{input=$input, model=$model, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var input: Input? = null + private var model: Model? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(moderationCreateBody: ModerationCreateBody) = apply { + this.input = moderationCreateBody.input + this.model = moderationCreateBody.model + additionalProperties(moderationCreateBody.additionalProperties) + } + + /** The input text to classify */ + @JsonProperty("input") fun input(input: Input) = apply { this.input = input } + + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded over + * time. This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the model. + * Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + @JsonProperty("model") fun model(model: Model) = apply { this.model = model } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): ModerationCreateBody = + ModerationCreateBody( + checkNotNull(input) { "`input` is required but was not set" }, + model, + additionalProperties.toUnmodifiable(), + ) + } + } + + fun _additionalQueryParams(): Map> = additionalQueryParams + + fun _additionalHeaders(): Map> = additionalHeaders + + fun _additionalBodyProperties(): Map = additionalBodyProperties + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModerationCreateParams && + this.input == other.input && + this.model == other.model && + this.additionalQueryParams == other.additionalQueryParams && + this.additionalHeaders == other.additionalHeaders && + this.additionalBodyProperties == other.additionalBodyProperties + } + + override fun hashCode(): Int { + return Objects.hash( + input, + model, + additionalQueryParams, + additionalHeaders, + additionalBodyProperties, + ) + } + + override fun toString() = + "ModerationCreateParams{input=$input, model=$model, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun builder() = Builder() + } + + @NoAutoDetect + class Builder { + + private var input: Input? = null + private var model: Model? = null + private var additionalQueryParams: MutableMap> = mutableMapOf() + private var additionalHeaders: MutableMap> = mutableMapOf() + private var additionalBodyProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(moderationCreateParams: ModerationCreateParams) = apply { + this.input = moderationCreateParams.input + this.model = moderationCreateParams.model + additionalQueryParams(moderationCreateParams.additionalQueryParams) + additionalHeaders(moderationCreateParams.additionalHeaders) + additionalBodyProperties(moderationCreateParams.additionalBodyProperties) + } + + /** The input text to classify */ + fun input(input: Input) = apply { this.input = input } + + /** The input text to classify */ + fun input(string: String) = apply { this.input = Input.ofString(string) } + + /** The input text to classify */ + fun input(strings: List) = apply { this.input = Input.ofStrings(strings) } + + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded over time. + * This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the model. + * Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + fun model(model: Model) = apply { this.model = model } + + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded over time. + * This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the model. + * Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + fun model(string: String) = apply { this.model = Model.ofString(string) } + + /** + * Two content moderations models are available: `text-moderation-stable` and + * `text-moderation-latest`. + * + * The default is `text-moderation-latest` which will be automatically upgraded over time. + * This ensures you are always using our most accurate model. If you use + * `text-moderation-stable`, we will provide advanced notice before updating the model. + * Accuracy of `text-moderation-stable` may be slightly lower than for + * `text-moderation-latest`. + */ + fun model(unionMember1: Model.UnionMember1) = apply { + this.model = Model.ofUnionMember1(unionMember1) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllQueryParams(additionalQueryParams) + } + + fun putQueryParam(name: String, value: String) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putQueryParams(name: String, values: Iterable) = apply { + this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllQueryParams(additionalQueryParams: Map>) = apply { + additionalQueryParams.forEach(this::putQueryParams) + } + + fun removeQueryParam(name: String) = apply { + this.additionalQueryParams.put(name, mutableListOf()) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllHeaders(additionalHeaders) + } + + fun putHeader(name: String, value: String) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) + } + + fun putHeaders(name: String, values: Iterable) = apply { + this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) + } + + fun putAllHeaders(additionalHeaders: Map>) = apply { + additionalHeaders.forEach(this::putHeaders) + } + + fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } + + fun additionalBodyProperties(additionalBodyProperties: Map) = apply { + this.additionalBodyProperties.clear() + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { + this.additionalBodyProperties.put(key, value) + } + + fun putAllAdditionalBodyProperties(additionalBodyProperties: Map) = + apply { + this.additionalBodyProperties.putAll(additionalBodyProperties) + } + + fun build(): ModerationCreateParams = + ModerationCreateParams( + checkNotNull(input) { "`input` is required but was not set" }, + model, + additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), + additionalBodyProperties.toUnmodifiable(), + ) + } + + @JsonDeserialize(using = Input.Deserializer::class) + @JsonSerialize(using = Input.Serializer::class) + class Input + private constructor( + private val string: String? = null, + private val strings: List? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun string(): Optional = Optional.ofNullable(string) + + fun strings(): Optional> = Optional.ofNullable(strings) + + fun isString(): Boolean = string != null + + fun isStrings(): Boolean = strings != null + + fun asString(): String = string.getOrThrow("string") + + fun asStrings(): List = strings.getOrThrow("strings") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + string != null -> visitor.visitString(string) + strings != null -> visitor.visitStrings(strings) + else -> visitor.unknown(_json) + } + } + + fun validate(): Input = apply { + if (!validated) { + if (string == null && strings == null) { + throw OpenAIInvalidDataException("Unknown Input: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Input && this.string == other.string && this.strings == other.strings + } + + override fun hashCode(): Int { + return Objects.hash(string, strings) + } + + override fun toString(): String { + return when { + string != null -> "Input{string=$string}" + strings != null -> "Input{strings=$strings}" + _json != null -> "Input{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Input") + } + } + + companion object { + + @JvmStatic fun ofString(string: String) = Input(string = string) + + @JvmStatic fun ofStrings(strings: List) = Input(strings = strings) + } + + interface Visitor { + + fun visitString(string: String): T + + fun visitStrings(strings: List): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown Input: $json") + } + } + + class Deserializer : BaseDeserializer(Input::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Input { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return Input(string = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef>())?.let { + return Input(strings = it, _json = json) + } + + return Input(_json = json) + } + } + + class Serializer : BaseSerializer(Input::class) { + + override fun serialize( + value: Input, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.strings != null -> generator.writeObject(value.strings) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Input") + } + } + } + } + + @JsonDeserialize(using = Model.Deserializer::class) + @JsonSerialize(using = Model.Serializer::class) + class Model + private constructor( + private val string: String? = null, + private val unionMember1: UnionMember1? = null, + private val _json: JsonValue? = null, + ) { + + private var validated: Boolean = false + + fun string(): Optional = Optional.ofNullable(string) + + fun unionMember1(): Optional = Optional.ofNullable(unionMember1) + + fun isString(): Boolean = string != null + + fun isUnionMember1(): Boolean = unionMember1 != null + + fun asString(): String = string.getOrThrow("string") + + fun asUnionMember1(): UnionMember1 = unionMember1.getOrThrow("unionMember1") + + fun _json(): Optional = Optional.ofNullable(_json) + + fun accept(visitor: Visitor): T { + return when { + string != null -> visitor.visitString(string) + unionMember1 != null -> visitor.visitUnionMember1(unionMember1) + else -> visitor.unknown(_json) + } + } + + fun validate(): Model = apply { + if (!validated) { + if (string == null && unionMember1 == null) { + throw OpenAIInvalidDataException("Unknown Model: $_json") + } + validated = true + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Model && + this.string == other.string && + this.unionMember1 == other.unionMember1 + } + + override fun hashCode(): Int { + return Objects.hash(string, unionMember1) + } + + override fun toString(): String { + return when { + string != null -> "Model{string=$string}" + unionMember1 != null -> "Model{unionMember1=$unionMember1}" + _json != null -> "Model{_unknown=$_json}" + else -> throw IllegalStateException("Invalid Model") + } + } + + companion object { + + @JvmStatic fun ofString(string: String) = Model(string = string) + + @JvmStatic + fun ofUnionMember1(unionMember1: UnionMember1) = Model(unionMember1 = unionMember1) + } + + interface Visitor { + + fun visitString(string: String): T + + fun visitUnionMember1(unionMember1: UnionMember1): T + + fun unknown(json: JsonValue?): T { + throw OpenAIInvalidDataException("Unknown Model: $json") + } + } + + class Deserializer : BaseDeserializer(Model::class) { + + override fun ObjectCodec.deserialize(node: JsonNode): Model { + val json = JsonValue.fromJsonNode(node) + tryDeserialize(node, jacksonTypeRef())?.let { + return Model(string = it, _json = json) + } + tryDeserialize(node, jacksonTypeRef())?.let { + return Model(unionMember1 = it, _json = json) + } + + return Model(_json = json) + } + } + + class Serializer : BaseSerializer(Model::class) { + + override fun serialize( + value: Model, + generator: JsonGenerator, + provider: SerializerProvider + ) { + when { + value.string != null -> generator.writeObject(value.string) + value.unionMember1 != null -> generator.writeObject(value.unionMember1) + value._json != null -> generator.writeObject(value._json) + else -> throw IllegalStateException("Invalid Model") + } + } + } + + class UnionMember1 + @JsonCreator + private constructor( + private val value: JsonField, + ) : Enum { + + @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField = value + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is UnionMember1 && this.value == other.value + } + + override fun hashCode() = value.hashCode() + + override fun toString() = value.toString() + + companion object { + + @JvmField + val TEXT_MODERATION_LATEST = UnionMember1(JsonField.of("text-moderation-latest")) + + @JvmField + val TEXT_MODERATION_STABLE = UnionMember1(JsonField.of("text-moderation-stable")) + + @JvmStatic fun of(value: String) = UnionMember1(JsonField.of(value)) + } + + enum class Known { + TEXT_MODERATION_LATEST, + TEXT_MODERATION_STABLE, + } + + enum class Value { + TEXT_MODERATION_LATEST, + TEXT_MODERATION_STABLE, + _UNKNOWN, + } + + fun value(): Value = + when (this) { + TEXT_MODERATION_LATEST -> Value.TEXT_MODERATION_LATEST + TEXT_MODERATION_STABLE -> Value.TEXT_MODERATION_STABLE + else -> Value._UNKNOWN + } + + fun known(): Known = + when (this) { + TEXT_MODERATION_LATEST -> Known.TEXT_MODERATION_LATEST + TEXT_MODERATION_STABLE -> Known.TEXT_MODERATION_STABLE + else -> throw OpenAIInvalidDataException("Unknown UnionMember1: $value") + } + + fun asString(): String = _value().asStringOrThrow() + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/models/ModerationCreateResponse.kt b/openai-java-core/src/main/kotlin/com/openai/models/ModerationCreateResponse.kt new file mode 100644 index 0000000..d448e22 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/models/ModerationCreateResponse.kt @@ -0,0 +1,157 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.databind.annotation.JsonDeserialize +import com.openai.core.ExcludeMissing +import com.openai.core.JsonField +import com.openai.core.JsonMissing +import com.openai.core.JsonValue +import com.openai.core.NoAutoDetect +import com.openai.core.toUnmodifiable +import java.util.Objects + +/** Represents if a given text input is potentially harmful. */ +@JsonDeserialize(builder = ModerationCreateResponse.Builder::class) +@NoAutoDetect +class ModerationCreateResponse +private constructor( + private val id: JsonField, + private val model: JsonField, + private val results: JsonField>, + private val additionalProperties: Map, +) { + + private var validated: Boolean = false + + private var hashCode: Int = 0 + + /** The unique identifier for the moderation request. */ + fun id(): String = id.getRequired("id") + + /** The model used to generate the moderation results. */ + fun model(): String = model.getRequired("model") + + /** A list of moderation objects. */ + fun results(): List = results.getRequired("results") + + /** The unique identifier for the moderation request. */ + @JsonProperty("id") @ExcludeMissing fun _id() = id + + /** The model used to generate the moderation results. */ + @JsonProperty("model") @ExcludeMissing fun _model() = model + + /** A list of moderation objects. */ + @JsonProperty("results") @ExcludeMissing fun _results() = results + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun validate(): ModerationCreateResponse = apply { + if (!validated) { + id() + model() + results().forEach { it.validate() } + validated = true + } + } + + fun toBuilder() = Builder().from(this) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is ModerationCreateResponse && + this.id == other.id && + this.model == other.model && + this.results == other.results && + this.additionalProperties == other.additionalProperties + } + + override fun hashCode(): Int { + if (hashCode == 0) { + hashCode = + Objects.hash( + id, + model, + results, + additionalProperties, + ) + } + return hashCode + } + + override fun toString() = + "ModerationCreateResponse{id=$id, model=$model, results=$results, additionalProperties=$additionalProperties}" + + companion object { + + @JvmStatic fun builder() = Builder() + } + + class Builder { + + private var id: JsonField = JsonMissing.of() + private var model: JsonField = JsonMissing.of() + private var results: JsonField> = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(moderationCreateResponse: ModerationCreateResponse) = apply { + this.id = moderationCreateResponse.id + this.model = moderationCreateResponse.model + this.results = moderationCreateResponse.results + additionalProperties(moderationCreateResponse.additionalProperties) + } + + /** The unique identifier for the moderation request. */ + fun id(id: String) = id(JsonField.of(id)) + + /** The unique identifier for the moderation request. */ + @JsonProperty("id") @ExcludeMissing fun id(id: JsonField) = apply { this.id = id } + + /** The model used to generate the moderation results. */ + fun model(model: String) = model(JsonField.of(model)) + + /** The model used to generate the moderation results. */ + @JsonProperty("model") + @ExcludeMissing + fun model(model: JsonField) = apply { this.model = model } + + /** A list of moderation objects. */ + fun results(results: List) = results(JsonField.of(results)) + + /** A list of moderation objects. */ + @JsonProperty("results") + @ExcludeMissing + fun results(results: JsonField>) = apply { this.results = results } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + this.additionalProperties.putAll(additionalProperties) + } + + @JsonAnySetter + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + this.additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun build(): ModerationCreateResponse = + ModerationCreateResponse( + id, + model, + results.map { it.toUnmodifiable() }, + additionalProperties.toUnmodifiable(), + ) + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/BatchServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/BatchServiceAsync.kt new file mode 100644 index 0000000..ca255f6 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/BatchServiceAsync.kt @@ -0,0 +1,49 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async + +import com.openai.core.RequestOptions +import com.openai.models.Batch +import com.openai.models.BatchCancelParams +import com.openai.models.BatchCreateParams +import com.openai.models.BatchListPageAsync +import com.openai.models.BatchListParams +import com.openai.models.BatchRetrieveParams +import java.util.concurrent.CompletableFuture + +interface BatchServiceAsync { + + /** Creates and executes a batch from an uploaded file of requests */ + @JvmOverloads + fun create( + params: BatchCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Retrieves a batch. */ + @JvmOverloads + fun retrieve( + params: BatchRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** List your organization's batches. */ + @JvmOverloads + fun list( + params: BatchListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, + * before changing to `cancelled`, where it will have partial results (if any) available in the + * output file. + */ + @JvmOverloads + fun cancel( + params: BatchCancelParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/BatchServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/BatchServiceAsyncImpl.kt new file mode 100644 index 0000000..26f3283 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/BatchServiceAsyncImpl.kt @@ -0,0 +1,153 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.Batch +import com.openai.models.BatchCancelParams +import com.openai.models.BatchCreateParams +import com.openai.models.BatchListPageAsync +import com.openai.models.BatchListParams +import com.openai.models.BatchRetrieveParams +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler +import java.util.concurrent.CompletableFuture + +class BatchServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : BatchServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Creates and executes a batch from an uploaded file of requests */ + override fun create( + params: BatchCreateParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("batches") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Retrieves a batch. */ + override fun retrieve( + params: BatchRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("batches", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** List your organization's batches. */ + override fun list( + params: BatchListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("batches") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { BatchListPageAsync.of(this, params, it) } + } + } + + private val cancelHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, + * before changing to `cancelled`, where it will have partial results (if any) available in the + * output file. + */ + override fun cancel( + params: BatchCancelParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("batches", params.getPathParam(0), "cancel") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { cancelHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/FileServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/FileServiceAsync.kt new file mode 100644 index 0000000..9d242c9 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/FileServiceAsync.kt @@ -0,0 +1,73 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async + +import com.openai.core.RequestOptions +import com.openai.core.http.BinaryResponseContent +import com.openai.models.FileContentParams +import com.openai.models.FileCreateParams +import com.openai.models.FileDeleteParams +import com.openai.models.FileDeleted +import com.openai.models.FileListPageAsync +import com.openai.models.FileListParams +import com.openai.models.FileObject +import com.openai.models.FileRetrieveParams +import java.util.concurrent.CompletableFuture + +interface FileServiceAsync { + + /** + * Upload a file that can be used across various endpoints. Individual files can be up to 512 + * MB, and the size of all files uploaded by one organization can be up to 100 GB. + * + * The Assistants API supports files up to 2 million tokens and of specific file types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats + * for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also has a + * specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these storage limits. + */ + @JvmOverloads + fun create( + params: FileCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Returns information about a specific file. */ + @JvmOverloads + fun retrieve( + params: FileRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Returns a list of files that belong to the user's organization. */ + @JvmOverloads + fun list( + params: FileListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Delete a file. */ + @JvmOverloads + fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Returns the contents of the specified file. */ + @JvmOverloads + fun content( + params: FileContentParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/FileServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/FileServiceAsyncImpl.kt new file mode 100644 index 0000000..817a862 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/FileServiceAsyncImpl.kt @@ -0,0 +1,195 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.BinaryResponseContent +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.FileContentParams +import com.openai.models.FileCreateParams +import com.openai.models.FileDeleteParams +import com.openai.models.FileDeleted +import com.openai.models.FileListPageAsync +import com.openai.models.FileListParams +import com.openai.models.FileObject +import com.openai.models.FileRetrieveParams +import com.openai.services.binaryHandler +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.multipartFormData +import com.openai.services.withErrorHandler +import java.util.concurrent.CompletableFuture + +class FileServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : FileServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Upload a file that can be used across various endpoints. Individual files can be up to 512 + * MB, and the size of all files uploaded by one organization can be up to 100 GB. + * + * The Assistants API supports files up to 2 million tokens and of specific file types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats + * for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also has a + * specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these storage limits. + */ + override fun create( + params: FileCreateParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("files") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(multipartFormData(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Returns information about a specific file. */ + override fun retrieve( + params: FileRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("files", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** Returns a list of files that belong to the user's organization. */ + override fun list( + params: FileListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("files") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FileListPageAsync.of(this, params, it) } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Delete a file. */ + override fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("files", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { deleteHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val contentHandler: Handler = + binaryHandler().withErrorHandler(errorHandler) + + /** Returns the contents of the specified file. */ + override fun content( + params: FileContentParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("files", params.getPathParam(0), "content") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response.let { contentHandler.handle(it) } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/FineTuningServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/FineTuningServiceAsync.kt new file mode 100644 index 0000000..83b26f3 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/FineTuningServiceAsync.kt @@ -0,0 +1,12 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async + +import com.openai.services.async.fineTuning.JobServiceAsync + +interface FineTuningServiceAsync { + + fun jobs(): JobServiceAsync +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/FineTuningServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/FineTuningServiceAsyncImpl.kt new file mode 100644 index 0000000..4a5ef18 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/FineTuningServiceAsyncImpl.kt @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async + +import com.openai.core.ClientOptions +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.services.async.fineTuning.JobServiceAsync +import com.openai.services.async.fineTuning.JobServiceAsyncImpl +import com.openai.services.errorHandler + +class FineTuningServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : FineTuningServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val jobs: JobServiceAsync by lazy { JobServiceAsyncImpl(clientOptions) } + + override fun jobs(): JobServiceAsync = jobs +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/ModelServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/ModelServiceAsync.kt new file mode 100644 index 0000000..b134548 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/ModelServiceAsync.kt @@ -0,0 +1,47 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async + +import com.openai.core.RequestOptions +import com.openai.models.Model +import com.openai.models.ModelDeleteParams +import com.openai.models.ModelDeleted +import com.openai.models.ModelListPageAsync +import com.openai.models.ModelListParams +import com.openai.models.ModelRetrieveParams +import java.util.concurrent.CompletableFuture + +interface ModelServiceAsync { + + /** + * Retrieves a model instance, providing basic information about the model such as the owner and + * permissioning. + */ + @JvmOverloads + fun retrieve( + params: ModelRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * Lists the currently available models, and provides basic information about each one such as + * the owner and availability. + */ + @JvmOverloads + fun list( + params: ModelListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to delete a + * model. + */ + @JvmOverloads + fun delete( + params: ModelDeleteParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/ModelServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/ModelServiceAsyncImpl.kt new file mode 100644 index 0000000..6c4ec53 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/ModelServiceAsyncImpl.kt @@ -0,0 +1,128 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.Model +import com.openai.models.ModelDeleteParams +import com.openai.models.ModelDeleted +import com.openai.models.ModelListPageAsync +import com.openai.models.ModelListParams +import com.openai.models.ModelRetrieveParams +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler +import java.util.concurrent.CompletableFuture + +class ModelServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : ModelServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Retrieves a model instance, providing basic information about the model such as the owner and + * permissioning. + */ + override fun retrieve( + params: ModelRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("models", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** + * Lists the currently available models, and provides basic information about each one such as + * the owner and availability. + */ + override fun list( + params: ModelListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("models") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { ModelListPageAsync.of(this, params, it) } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to delete a + * model. + */ + override fun delete( + params: ModelDeleteParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("models", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { deleteHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/ModerationServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/ModerationServiceAsync.kt new file mode 100644 index 0000000..d1c4c62 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/ModerationServiceAsync.kt @@ -0,0 +1,20 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async + +import com.openai.core.RequestOptions +import com.openai.models.ModerationCreateParams +import com.openai.models.ModerationCreateResponse +import java.util.concurrent.CompletableFuture + +interface ModerationServiceAsync { + + /** Classifies if text is potentially harmful. */ + @JvmOverloads + fun create( + params: ModerationCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/ModerationServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/ModerationServiceAsyncImpl.kt new file mode 100644 index 0000000..651a7ba --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/ModerationServiceAsyncImpl.kt @@ -0,0 +1,56 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.ModerationCreateParams +import com.openai.models.ModerationCreateResponse +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler +import java.util.concurrent.CompletableFuture + +class ModerationServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : ModerationServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** Classifies if text is potentially harmful. */ + override fun create( + params: ModerationCreateParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("moderations") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/JobServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/JobServiceAsync.kt new file mode 100644 index 0000000..24bf4c6 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/JobServiceAsync.kt @@ -0,0 +1,69 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async.fineTuning + +import com.openai.core.RequestOptions +import com.openai.models.FineTuningJob +import com.openai.models.FineTuningJobCancelParams +import com.openai.models.FineTuningJobCreateParams +import com.openai.models.FineTuningJobListEventsPageAsync +import com.openai.models.FineTuningJobListEventsParams +import com.openai.models.FineTuningJobListPageAsync +import com.openai.models.FineTuningJobListParams +import com.openai.models.FineTuningJobRetrieveParams +import com.openai.services.async.fineTuning.jobs.CheckpointServiceAsync +import java.util.concurrent.CompletableFuture + +interface JobServiceAsync { + + fun checkpoints(): CheckpointServiceAsync + + /** + * Creates a fine-tuning job which begins the process of creating a new model from a given + * dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + @JvmOverloads + fun create( + params: FineTuningJobCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + @JvmOverloads + fun retrieve( + params: FineTuningJobRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** List your organization's fine-tuning jobs */ + @JvmOverloads + fun list( + params: FineTuningJobListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Immediately cancel a fine-tune job. */ + @JvmOverloads + fun cancel( + params: FineTuningJobCancelParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture + + /** Get status updates for a fine-tuning job. */ + @JvmOverloads + fun listEvents( + params: FineTuningJobListEventsParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/JobServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/JobServiceAsyncImpl.kt new file mode 100644 index 0000000..0a69505 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/JobServiceAsyncImpl.kt @@ -0,0 +1,202 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async.fineTuning + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.FineTuningJob +import com.openai.models.FineTuningJobCancelParams +import com.openai.models.FineTuningJobCreateParams +import com.openai.models.FineTuningJobListEventsPageAsync +import com.openai.models.FineTuningJobListEventsParams +import com.openai.models.FineTuningJobListPageAsync +import com.openai.models.FineTuningJobListParams +import com.openai.models.FineTuningJobRetrieveParams +import com.openai.services.async.fineTuning.jobs.CheckpointServiceAsync +import com.openai.services.async.fineTuning.jobs.CheckpointServiceAsyncImpl +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler +import java.util.concurrent.CompletableFuture + +class JobServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : JobServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val checkpoints: CheckpointServiceAsync by lazy { + CheckpointServiceAsyncImpl(clientOptions) + } + + override fun checkpoints(): CheckpointServiceAsync = checkpoints + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Creates a fine-tuning job which begins the process of creating a new model from a given + * dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + override fun create( + params: FineTuningJobCreateParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("fine_tuning", "jobs") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + override fun retrieve( + params: FineTuningJobRetrieveParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** List your organization's fine-tuning jobs */ + override fun list( + params: FineTuningJobListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FineTuningJobListPageAsync.of(this, params, it) } + } + } + + private val cancelHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Immediately cancel a fine-tune job. */ + override fun cancel( + params: FineTuningJobCancelParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0), "cancel") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { cancelHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listEventsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** Get status updates for a fine-tuning job. */ + override fun listEvents( + params: FineTuningJobListEventsParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0), "events") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listEventsHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FineTuningJobListEventsPageAsync.of(this, params, it) } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/jobs/CheckpointServiceAsync.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/jobs/CheckpointServiceAsync.kt new file mode 100644 index 0000000..0d179cf --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/jobs/CheckpointServiceAsync.kt @@ -0,0 +1,20 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.async.fineTuning.jobs + +import com.openai.core.RequestOptions +import com.openai.models.FineTuningJobCheckpointListPageAsync +import com.openai.models.FineTuningJobCheckpointListParams +import java.util.concurrent.CompletableFuture + +interface CheckpointServiceAsync { + + /** List checkpoints for a fine-tuning job. */ + @JvmOverloads + fun list( + params: FineTuningJobCheckpointListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): CompletableFuture +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/jobs/CheckpointServiceAsyncImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/jobs/CheckpointServiceAsyncImpl.kt new file mode 100644 index 0000000..09a6d45 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/async/fineTuning/jobs/CheckpointServiceAsyncImpl.kt @@ -0,0 +1,55 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.async.fineTuning.jobs + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.FineTuningJobCheckpointListPageAsync +import com.openai.models.FineTuningJobCheckpointListParams +import com.openai.services.errorHandler +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler +import java.util.concurrent.CompletableFuture + +class CheckpointServiceAsyncImpl +constructor( + private val clientOptions: ClientOptions, +) : CheckpointServiceAsync { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** List checkpoints for a fine-tuning job. */ + override fun list( + params: FineTuningJobCheckpointListParams, + requestOptions: RequestOptions + ): CompletableFuture { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0), "checkpoints") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.executeAsync(request, requestOptions).thenApply { response + -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FineTuningJobCheckpointListPageAsync.of(this, params, it) } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/BatchService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/BatchService.kt new file mode 100644 index 0000000..cf206f1 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/BatchService.kt @@ -0,0 +1,48 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking + +import com.openai.core.RequestOptions +import com.openai.models.Batch +import com.openai.models.BatchCancelParams +import com.openai.models.BatchCreateParams +import com.openai.models.BatchListPage +import com.openai.models.BatchListParams +import com.openai.models.BatchRetrieveParams + +interface BatchService { + + /** Creates and executes a batch from an uploaded file of requests */ + @JvmOverloads + fun create( + params: BatchCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): Batch + + /** Retrieves a batch. */ + @JvmOverloads + fun retrieve( + params: BatchRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): Batch + + /** List your organization's batches. */ + @JvmOverloads + fun list( + params: BatchListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): BatchListPage + + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, + * before changing to `cancelled`, where it will have partial results (if any) available in the + * output file. + */ + @JvmOverloads + fun cancel( + params: BatchCancelParams, + requestOptions: RequestOptions = RequestOptions.none() + ): Batch +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/BatchServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/BatchServiceImpl.kt new file mode 100644 index 0000000..4a0ee55 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/BatchServiceImpl.kt @@ -0,0 +1,135 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.Batch +import com.openai.models.BatchCancelParams +import com.openai.models.BatchCreateParams +import com.openai.models.BatchListPage +import com.openai.models.BatchListParams +import com.openai.models.BatchRetrieveParams +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler + +class BatchServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : BatchService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Creates and executes a batch from an uploaded file of requests */ + override fun create(params: BatchCreateParams, requestOptions: RequestOptions): Batch { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("batches") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Retrieves a batch. */ + override fun retrieve(params: BatchRetrieveParams, requestOptions: RequestOptions): Batch { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("batches", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** List your organization's batches. */ + override fun list(params: BatchListParams, requestOptions: RequestOptions): BatchListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("batches") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { BatchListPage.of(this, params, it) } + } + } + + private val cancelHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, + * before changing to `cancelled`, where it will have partial results (if any) available in the + * output file. + */ + override fun cancel(params: BatchCancelParams, requestOptions: RequestOptions): Batch { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("batches", params.getPathParam(0), "cancel") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { cancelHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/FileService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FileService.kt new file mode 100644 index 0000000..c60f7bb --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FileService.kt @@ -0,0 +1,72 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking + +import com.openai.core.RequestOptions +import com.openai.core.http.BinaryResponseContent +import com.openai.models.FileContentParams +import com.openai.models.FileCreateParams +import com.openai.models.FileDeleteParams +import com.openai.models.FileDeleted +import com.openai.models.FileListPage +import com.openai.models.FileListParams +import com.openai.models.FileObject +import com.openai.models.FileRetrieveParams + +interface FileService { + + /** + * Upload a file that can be used across various endpoints. Individual files can be up to 512 + * MB, and the size of all files uploaded by one organization can be up to 100 GB. + * + * The Assistants API supports files up to 2 million tokens and of specific file types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats + * for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also has a + * specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these storage limits. + */ + @JvmOverloads + fun create( + params: FileCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FileObject + + /** Returns information about a specific file. */ + @JvmOverloads + fun retrieve( + params: FileRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FileObject + + /** Returns a list of files that belong to the user's organization. */ + @JvmOverloads + fun list( + params: FileListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FileListPage + + /** Delete a file. */ + @JvmOverloads + fun delete( + params: FileDeleteParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FileDeleted + + /** Returns the contents of the specified file. */ + @JvmOverloads + fun content( + params: FileContentParams, + requestOptions: RequestOptions = RequestOptions.none() + ): BinaryResponseContent +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/FileServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FileServiceImpl.kt new file mode 100644 index 0000000..699df91 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FileServiceImpl.kt @@ -0,0 +1,176 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.BinaryResponseContent +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.FileContentParams +import com.openai.models.FileCreateParams +import com.openai.models.FileDeleteParams +import com.openai.models.FileDeleted +import com.openai.models.FileListPage +import com.openai.models.FileListParams +import com.openai.models.FileObject +import com.openai.models.FileRetrieveParams +import com.openai.services.binaryHandler +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.multipartFormData +import com.openai.services.withErrorHandler + +class FileServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : FileService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Upload a file that can be used across various endpoints. Individual files can be up to 512 + * MB, and the size of all files uploaded by one organization can be up to 100 GB. + * + * The Assistants API supports files up to 2 million tokens and of specific file types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain required formats + * for fine-tuning [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also has a + * specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these storage limits. + */ + override fun create(params: FileCreateParams, requestOptions: RequestOptions): FileObject { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("files") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(multipartFormData(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Returns information about a specific file. */ + override fun retrieve(params: FileRetrieveParams, requestOptions: RequestOptions): FileObject { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("files", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Returns a list of files that belong to the user's organization. */ + override fun list(params: FileListParams, requestOptions: RequestOptions): FileListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("files") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FileListPage.of(this, params, it) } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Delete a file. */ + override fun delete(params: FileDeleteParams, requestOptions: RequestOptions): FileDeleted { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("files", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { deleteHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val contentHandler: Handler = + binaryHandler().withErrorHandler(errorHandler) + + /** Returns the contents of the specified file. */ + override fun content( + params: FileContentParams, + requestOptions: RequestOptions + ): BinaryResponseContent { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("files", params.getPathParam(0), "content") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response.let { contentHandler.handle(it) } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/FineTuningService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FineTuningService.kt new file mode 100644 index 0000000..c501bfb --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FineTuningService.kt @@ -0,0 +1,12 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking + +import com.openai.services.blocking.fineTuning.JobService + +interface FineTuningService { + + fun jobs(): JobService +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/FineTuningServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FineTuningServiceImpl.kt new file mode 100644 index 0000000..5cc7a90 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/FineTuningServiceImpl.kt @@ -0,0 +1,22 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking + +import com.openai.core.ClientOptions +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.services.blocking.fineTuning.JobService +import com.openai.services.blocking.fineTuning.JobServiceImpl +import com.openai.services.errorHandler + +class FineTuningServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : FineTuningService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val jobs: JobService by lazy { JobServiceImpl(clientOptions) } + + override fun jobs(): JobService = jobs +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModelService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModelService.kt new file mode 100644 index 0000000..b3f72e2 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModelService.kt @@ -0,0 +1,46 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking + +import com.openai.core.RequestOptions +import com.openai.models.Model +import com.openai.models.ModelDeleteParams +import com.openai.models.ModelDeleted +import com.openai.models.ModelListPage +import com.openai.models.ModelListParams +import com.openai.models.ModelRetrieveParams + +interface ModelService { + + /** + * Retrieves a model instance, providing basic information about the model such as the owner and + * permissioning. + */ + @JvmOverloads + fun retrieve( + params: ModelRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): Model + + /** + * Lists the currently available models, and provides basic information about each one such as + * the owner and availability. + */ + @JvmOverloads + fun list( + params: ModelListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): ModelListPage + + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to delete a + * model. + */ + @JvmOverloads + fun delete( + params: ModelDeleteParams, + requestOptions: RequestOptions = RequestOptions.none() + ): ModelDeleted +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModelServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModelServiceImpl.kt new file mode 100644 index 0000000..6c06230 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModelServiceImpl.kt @@ -0,0 +1,114 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.Model +import com.openai.models.ModelDeleteParams +import com.openai.models.ModelDeleted +import com.openai.models.ModelListPage +import com.openai.models.ModelListParams +import com.openai.models.ModelRetrieveParams +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler + +class ModelServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : ModelService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Retrieves a model instance, providing basic information about the model such as the owner and + * permissioning. + */ + override fun retrieve(params: ModelRetrieveParams, requestOptions: RequestOptions): Model { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("models", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Lists the currently available models, and provides basic information about each one such as + * the owner and availability. + */ + override fun list(params: ModelListParams, requestOptions: RequestOptions): ModelListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("models") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { ModelListPage.of(this, params, it) } + } + } + + private val deleteHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to delete a + * model. + */ + override fun delete(params: ModelDeleteParams, requestOptions: RequestOptions): ModelDeleted { + val request = + HttpRequest.builder() + .method(HttpMethod.DELETE) + .addPathSegments("models", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { deleteHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModerationService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModerationService.kt new file mode 100644 index 0000000..4bff6b2 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModerationService.kt @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking + +import com.openai.core.RequestOptions +import com.openai.models.ModerationCreateParams +import com.openai.models.ModerationCreateResponse + +interface ModerationService { + + /** Classifies if text is potentially harmful. */ + @JvmOverloads + fun create( + params: ModerationCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): ModerationCreateResponse +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModerationServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModerationServiceImpl.kt new file mode 100644 index 0000000..4f6cc32 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/ModerationServiceImpl.kt @@ -0,0 +1,54 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.ModerationCreateParams +import com.openai.models.ModerationCreateResponse +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler + +class ModerationServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : ModerationService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** Classifies if text is potentially harmful. */ + override fun create( + params: ModerationCreateParams, + requestOptions: RequestOptions + ): ModerationCreateResponse { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("moderations") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/JobService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/JobService.kt new file mode 100644 index 0000000..4d085f0 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/JobService.kt @@ -0,0 +1,68 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking.fineTuning + +import com.openai.core.RequestOptions +import com.openai.models.FineTuningJob +import com.openai.models.FineTuningJobCancelParams +import com.openai.models.FineTuningJobCreateParams +import com.openai.models.FineTuningJobListEventsPage +import com.openai.models.FineTuningJobListEventsParams +import com.openai.models.FineTuningJobListPage +import com.openai.models.FineTuningJobListParams +import com.openai.models.FineTuningJobRetrieveParams +import com.openai.services.blocking.fineTuning.jobs.CheckpointService + +interface JobService { + + fun checkpoints(): CheckpointService + + /** + * Creates a fine-tuning job which begins the process of creating a new model from a given + * dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + @JvmOverloads + fun create( + params: FineTuningJobCreateParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FineTuningJob + + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + @JvmOverloads + fun retrieve( + params: FineTuningJobRetrieveParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FineTuningJob + + /** List your organization's fine-tuning jobs */ + @JvmOverloads + fun list( + params: FineTuningJobListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FineTuningJobListPage + + /** Immediately cancel a fine-tune job. */ + @JvmOverloads + fun cancel( + params: FineTuningJobCancelParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FineTuningJob + + /** Get status updates for a fine-tuning job. */ + @JvmOverloads + fun listEvents( + params: FineTuningJobListEventsParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FineTuningJobListEventsPage +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/JobServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/JobServiceImpl.kt new file mode 100644 index 0000000..c06e76f --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/JobServiceImpl.kt @@ -0,0 +1,194 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking.fineTuning + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.FineTuningJob +import com.openai.models.FineTuningJobCancelParams +import com.openai.models.FineTuningJobCreateParams +import com.openai.models.FineTuningJobListEventsPage +import com.openai.models.FineTuningJobListEventsParams +import com.openai.models.FineTuningJobListPage +import com.openai.models.FineTuningJobListParams +import com.openai.models.FineTuningJobRetrieveParams +import com.openai.services.blocking.fineTuning.jobs.CheckpointService +import com.openai.services.blocking.fineTuning.jobs.CheckpointServiceImpl +import com.openai.services.errorHandler +import com.openai.services.json +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler + +class JobServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : JobService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val checkpoints: CheckpointService by lazy { CheckpointServiceImpl(clientOptions) } + + override fun checkpoints(): CheckpointService = checkpoints + + private val createHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Creates a fine-tuning job which begins the process of creating a new model from a given + * dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + override fun create( + params: FineTuningJobCreateParams, + requestOptions: RequestOptions + ): FineTuningJob { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("fine_tuning", "jobs") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .body(json(clientOptions.jsonMapper, params.getBody())) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { createHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val retrieveHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + */ + override fun retrieve( + params: FineTuningJobRetrieveParams, + requestOptions: RequestOptions + ): FineTuningJob { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0)) + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { retrieveHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** List your organization's fine-tuning jobs */ + override fun list( + params: FineTuningJobListParams, + requestOptions: RequestOptions + ): FineTuningJobListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FineTuningJobListPage.of(this, params, it) } + } + } + + private val cancelHandler: Handler = + jsonHandler(clientOptions.jsonMapper).withErrorHandler(errorHandler) + + /** Immediately cancel a fine-tune job. */ + override fun cancel( + params: FineTuningJobCancelParams, + requestOptions: RequestOptions + ): FineTuningJob { + val request = + HttpRequest.builder() + .method(HttpMethod.POST) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0), "cancel") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .apply { params.getBody().ifPresent { body(json(clientOptions.jsonMapper, it)) } } + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { cancelHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + } + } + + private val listEventsHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** Get status updates for a fine-tuning job. */ + override fun listEvents( + params: FineTuningJobListEventsParams, + requestOptions: RequestOptions + ): FineTuningJobListEventsPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0), "events") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listEventsHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FineTuningJobListEventsPage.of(this, params, it) } + } + } +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/jobs/CheckpointService.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/jobs/CheckpointService.kt new file mode 100644 index 0000000..ac55216 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/jobs/CheckpointService.kt @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. + +@file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 + +package com.openai.services.blocking.fineTuning.jobs + +import com.openai.core.RequestOptions +import com.openai.models.FineTuningJobCheckpointListPage +import com.openai.models.FineTuningJobCheckpointListParams + +interface CheckpointService { + + /** List checkpoints for a fine-tuning job. */ + @JvmOverloads + fun list( + params: FineTuningJobCheckpointListParams, + requestOptions: RequestOptions = RequestOptions.none() + ): FineTuningJobCheckpointListPage +} diff --git a/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/jobs/CheckpointServiceImpl.kt b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/jobs/CheckpointServiceImpl.kt new file mode 100644 index 0000000..fa83449 --- /dev/null +++ b/openai-java-core/src/main/kotlin/com/openai/services/blocking/fineTuning/jobs/CheckpointServiceImpl.kt @@ -0,0 +1,53 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.services.blocking.fineTuning.jobs + +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.core.http.HttpMethod +import com.openai.core.http.HttpRequest +import com.openai.core.http.HttpResponse.Handler +import com.openai.errors.OpenAIError +import com.openai.models.FineTuningJobCheckpointListPage +import com.openai.models.FineTuningJobCheckpointListParams +import com.openai.services.errorHandler +import com.openai.services.jsonHandler +import com.openai.services.withErrorHandler + +class CheckpointServiceImpl +constructor( + private val clientOptions: ClientOptions, +) : CheckpointService { + + private val errorHandler: Handler = errorHandler(clientOptions.jsonMapper) + + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + .withErrorHandler(errorHandler) + + /** List checkpoints for a fine-tuning job. */ + override fun list( + params: FineTuningJobCheckpointListParams, + requestOptions: RequestOptions + ): FineTuningJobCheckpointListPage { + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .addPathSegments("fine_tuning", "jobs", params.getPathParam(0), "checkpoints") + .putAllQueryParams(clientOptions.queryParams) + .putAllQueryParams(params.getQueryParams()) + .putAllHeaders(clientOptions.headers) + .putAllHeaders(params.getHeaders()) + .build() + return clientOptions.httpClient.execute(request, requestOptions).let { response -> + response + .use { listHandler.handle(it) } + .apply { + if (requestOptions.responseValidation ?: clientOptions.responseValidation) { + validate() + } + } + .let { FineTuningJobCheckpointListPage.of(this, params, it) } + } + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/BatchErrorTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/BatchErrorTest.kt new file mode 100644 index 0000000..369f8cd --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/BatchErrorTest.kt @@ -0,0 +1,20 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BatchErrorTest { + + @Test + fun createBatchError() { + val batchError = + BatchError.builder().code("code").line(123L).message("message").param("param").build() + assertThat(batchError).isNotNull + assertThat(batchError.code()).contains("code") + assertThat(batchError.line()).contains(123L) + assertThat(batchError.message()).contains("message") + assertThat(batchError.param()).contains("param") + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/BatchRequestCountsTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/BatchRequestCountsTest.kt new file mode 100644 index 0000000..6c391f6 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/BatchRequestCountsTest.kt @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BatchRequestCountsTest { + + @Test + fun createBatchRequestCounts() { + val batchRequestCounts = + BatchRequestCounts.builder().completed(123L).failed(123L).total(123L).build() + assertThat(batchRequestCounts).isNotNull + assertThat(batchRequestCounts.completed()).isEqualTo(123L) + assertThat(batchRequestCounts.failed()).isEqualTo(123L) + assertThat(batchRequestCounts.total()).isEqualTo(123L) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/BatchTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/BatchTest.kt new file mode 100644 index 0000000..747ec7f --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/BatchTest.kt @@ -0,0 +1,90 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import com.openai.core.JsonNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class BatchTest { + + @Test + fun createBatch() { + val batch = + Batch.builder() + .id("id") + .completionWindow("completion_window") + .createdAt(123L) + .endpoint("endpoint") + .inputFileId("input_file_id") + .object_(Batch.Object.BATCH) + .status(Batch.Status.VALIDATING) + .cancelledAt(123L) + .cancellingAt(123L) + .completedAt(123L) + .errorFileId("error_file_id") + .errors( + Batch.Errors.builder() + .data( + listOf( + BatchError.builder() + .code("code") + .line(123L) + .message("message") + .param("param") + .build() + ) + ) + .object_("object") + .build() + ) + .expiredAt(123L) + .expiresAt(123L) + .failedAt(123L) + .finalizingAt(123L) + .inProgressAt(123L) + .metadata(JsonNull.of()) + .outputFileId("output_file_id") + .requestCounts( + BatchRequestCounts.builder().completed(123L).failed(123L).total(123L).build() + ) + .build() + assertThat(batch).isNotNull + assertThat(batch.id()).isEqualTo("id") + assertThat(batch.completionWindow()).isEqualTo("completion_window") + assertThat(batch.createdAt()).isEqualTo(123L) + assertThat(batch.endpoint()).isEqualTo("endpoint") + assertThat(batch.inputFileId()).isEqualTo("input_file_id") + assertThat(batch.object_()).isEqualTo(Batch.Object.BATCH) + assertThat(batch.status()).isEqualTo(Batch.Status.VALIDATING) + assertThat(batch.cancelledAt()).contains(123L) + assertThat(batch.cancellingAt()).contains(123L) + assertThat(batch.completedAt()).contains(123L) + assertThat(batch.errorFileId()).contains("error_file_id") + assertThat(batch.errors()) + .contains( + Batch.Errors.builder() + .data( + listOf( + BatchError.builder() + .code("code") + .line(123L) + .message("message") + .param("param") + .build() + ) + ) + .object_("object") + .build() + ) + assertThat(batch.expiredAt()).contains(123L) + assertThat(batch.expiresAt()).contains(123L) + assertThat(batch.failedAt()).contains(123L) + assertThat(batch.finalizingAt()).contains(123L) + assertThat(batch.inProgressAt()).contains(123L) + assertThat(batch._metadata()).isEqualTo(JsonNull.of()) + assertThat(batch.outputFileId()).contains("output_file_id") + assertThat(batch.requestCounts()) + .contains(BatchRequestCounts.builder().completed(123L).failed(123L).total(123L).build()) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionAssistantMessageParamTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionAssistantMessageParamTest.kt index edcf3fd..5afd73f 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionAssistantMessageParamTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionAssistantMessageParamTest.kt @@ -12,22 +12,22 @@ class ChatCompletionAssistantMessageParamTest { val chatCompletionAssistantMessageParam = ChatCompletionAssistantMessageParam.builder() .role(ChatCompletionAssistantMessageParam.Role.ASSISTANT) - .content("string") + .content("content") .functionCall( ChatCompletionAssistantMessageParam.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) - .name("string") + .name("name") .toolCalls( listOf( ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) @@ -38,23 +38,23 @@ class ChatCompletionAssistantMessageParamTest { assertThat(chatCompletionAssistantMessageParam).isNotNull assertThat(chatCompletionAssistantMessageParam.role()) .isEqualTo(ChatCompletionAssistantMessageParam.Role.ASSISTANT) - assertThat(chatCompletionAssistantMessageParam.content()).contains("string") + assertThat(chatCompletionAssistantMessageParam.content()).contains("content") assertThat(chatCompletionAssistantMessageParam.functionCall()) .contains( ChatCompletionAssistantMessageParam.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) - assertThat(chatCompletionAssistantMessageParam.name()).contains("string") + assertThat(chatCompletionAssistantMessageParam.name()).contains("name") assertThat(chatCompletionAssistantMessageParam.toolCalls().get()) .containsExactly( ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionChunkTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionChunkTest.kt index 34ca093..cb24fb1 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionChunkTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionChunkTest.kt @@ -11,17 +11,17 @@ class ChatCompletionChunkTest { fun createChatCompletionChunk() { val chatCompletionChunk = ChatCompletionChunk.builder() - .id("string") + .id("id") .choices( listOf( ChatCompletionChunk.Choice.builder() .delta( ChatCompletionChunk.Choice.Delta.builder() - .content("string") + .content("content") .functionCall( ChatCompletionChunk.Choice.Delta.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .role(ChatCompletionChunk.Choice.Delta.Role.SYSTEM) @@ -29,13 +29,13 @@ class ChatCompletionChunkTest { listOf( ChatCompletionChunk.Choice.Delta.ToolCall.builder() .index(123L) - .id("string") + .id("id") .function( ChatCompletionChunk.Choice.Delta.ToolCall .Function .builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type( @@ -54,14 +54,14 @@ class ChatCompletionChunkTest { .content( listOf( ChatCompletionTokenLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .topLogprobs( listOf( ChatCompletionTokenLogprob.TopLogprob .builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .build() @@ -76,10 +76,10 @@ class ChatCompletionChunkTest { ) ) .created(123L) - .model("string") + .model("model") .object_(ChatCompletionChunk.Object.CHAT_COMPLETION_CHUNK) .serviceTier(ChatCompletionChunk.ServiceTier.SCALE) - .systemFingerprint("string") + .systemFingerprint("system_fingerprint") .usage( ChatCompletionChunk.Usage.builder() .completionTokens(123L) @@ -89,17 +89,17 @@ class ChatCompletionChunkTest { ) .build() assertThat(chatCompletionChunk).isNotNull - assertThat(chatCompletionChunk.id()).isEqualTo("string") + assertThat(chatCompletionChunk.id()).isEqualTo("id") assertThat(chatCompletionChunk.choices()) .containsExactly( ChatCompletionChunk.Choice.builder() .delta( ChatCompletionChunk.Choice.Delta.builder() - .content("string") + .content("content") .functionCall( ChatCompletionChunk.Choice.Delta.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .role(ChatCompletionChunk.Choice.Delta.Role.SYSTEM) @@ -107,12 +107,12 @@ class ChatCompletionChunkTest { listOf( ChatCompletionChunk.Choice.Delta.ToolCall.builder() .index(123L) - .id("string") + .id("id") .function( ChatCompletionChunk.Choice.Delta.ToolCall.Function .builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type( @@ -130,13 +130,13 @@ class ChatCompletionChunkTest { .content( listOf( ChatCompletionTokenLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .topLogprobs( listOf( ChatCompletionTokenLogprob.TopLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .build() @@ -150,12 +150,12 @@ class ChatCompletionChunkTest { .build() ) assertThat(chatCompletionChunk.created()).isEqualTo(123L) - assertThat(chatCompletionChunk.model()).isEqualTo("string") + assertThat(chatCompletionChunk.model()).isEqualTo("model") assertThat(chatCompletionChunk.object_()) .isEqualTo(ChatCompletionChunk.Object.CHAT_COMPLETION_CHUNK) assertThat(chatCompletionChunk.serviceTier()) .contains(ChatCompletionChunk.ServiceTier.SCALE) - assertThat(chatCompletionChunk.systemFingerprint()).contains("string") + assertThat(chatCompletionChunk.systemFingerprint()).contains("system_fingerprint") assertThat(chatCompletionChunk.usage()) .contains( ChatCompletionChunk.Usage.builder() diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionContentPartTextTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionContentPartTextTest.kt index da518e1..0491f1c 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionContentPartTextTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionContentPartTextTest.kt @@ -11,11 +11,11 @@ class ChatCompletionContentPartTextTest { fun createChatCompletionContentPartText() { val chatCompletionContentPartText = ChatCompletionContentPartText.builder() - .text("string") + .text("text") .type(ChatCompletionContentPartText.Type.TEXT) .build() assertThat(chatCompletionContentPartText).isNotNull - assertThat(chatCompletionContentPartText.text()).isEqualTo("string") + assertThat(chatCompletionContentPartText.text()).isEqualTo("text") assertThat(chatCompletionContentPartText.type()) .isEqualTo(ChatCompletionContentPartText.Type.TEXT) } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionCallOptionTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionCallOptionTest.kt index f4737fb..1a97883 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionCallOptionTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionCallOptionTest.kt @@ -10,8 +10,8 @@ class ChatCompletionFunctionCallOptionTest { @Test fun createChatCompletionFunctionCallOption() { val chatCompletionFunctionCallOption = - ChatCompletionFunctionCallOption.builder().name("string").build() + ChatCompletionFunctionCallOption.builder().name("name").build() assertThat(chatCompletionFunctionCallOption).isNotNull - assertThat(chatCompletionFunctionCallOption.name()).isEqualTo("string") + assertThat(chatCompletionFunctionCallOption.name()).isEqualTo("name") } } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionMessageParamTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionMessageParamTest.kt index e3879a7..531554e 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionMessageParamTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionFunctionMessageParamTest.kt @@ -11,13 +11,13 @@ class ChatCompletionFunctionMessageParamTest { fun createChatCompletionFunctionMessageParam() { val chatCompletionFunctionMessageParam = ChatCompletionFunctionMessageParam.builder() - .content("string") - .name("string") + .content("content") + .name("name") .role(ChatCompletionFunctionMessageParam.Role.FUNCTION) .build() assertThat(chatCompletionFunctionMessageParam).isNotNull - assertThat(chatCompletionFunctionMessageParam.content()).contains("string") - assertThat(chatCompletionFunctionMessageParam.name()).isEqualTo("string") + assertThat(chatCompletionFunctionMessageParam.content()).contains("content") + assertThat(chatCompletionFunctionMessageParam.name()).isEqualTo("name") assertThat(chatCompletionFunctionMessageParam.role()) .isEqualTo(ChatCompletionFunctionMessageParam.Role.FUNCTION) } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageTest.kt index 724bacb..cce86d0 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageTest.kt @@ -11,22 +11,22 @@ class ChatCompletionMessageTest { fun createChatCompletionMessage() { val chatCompletionMessage = ChatCompletionMessage.builder() - .content("string") + .content("content") .role(ChatCompletionMessage.Role.ASSISTANT) .functionCall( ChatCompletionMessage.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .toolCalls( listOf( ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) @@ -35,23 +35,23 @@ class ChatCompletionMessageTest { ) .build() assertThat(chatCompletionMessage).isNotNull - assertThat(chatCompletionMessage.content()).contains("string") + assertThat(chatCompletionMessage.content()).contains("content") assertThat(chatCompletionMessage.role()).isEqualTo(ChatCompletionMessage.Role.ASSISTANT) assertThat(chatCompletionMessage.functionCall()) .contains( ChatCompletionMessage.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) assertThat(chatCompletionMessage.toolCalls().get()) .containsExactly( ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageToolCallTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageToolCallTest.kt index 8fc6431..3017952 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageToolCallTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionMessageToolCallTest.kt @@ -11,22 +11,22 @@ class ChatCompletionMessageToolCallTest { fun createChatCompletionMessageToolCall() { val chatCompletionMessageToolCall = ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) .build() assertThat(chatCompletionMessageToolCall).isNotNull - assertThat(chatCompletionMessageToolCall.id()).isEqualTo("string") + assertThat(chatCompletionMessageToolCall.id()).isEqualTo("id") assertThat(chatCompletionMessageToolCall.function()) .isEqualTo( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) assertThat(chatCompletionMessageToolCall.type()) diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionNamedToolChoiceTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionNamedToolChoiceTest.kt index 17841f0..fc42132 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionNamedToolChoiceTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionNamedToolChoiceTest.kt @@ -11,12 +11,12 @@ class ChatCompletionNamedToolChoiceTest { fun createChatCompletionNamedToolChoice() { val chatCompletionNamedToolChoice = ChatCompletionNamedToolChoice.builder() - .function(ChatCompletionNamedToolChoice.Function.builder().name("string").build()) + .function(ChatCompletionNamedToolChoice.Function.builder().name("name").build()) .type(ChatCompletionNamedToolChoice.Type.FUNCTION) .build() assertThat(chatCompletionNamedToolChoice).isNotNull assertThat(chatCompletionNamedToolChoice.function()) - .isEqualTo(ChatCompletionNamedToolChoice.Function.builder().name("string").build()) + .isEqualTo(ChatCompletionNamedToolChoice.Function.builder().name("name").build()) assertThat(chatCompletionNamedToolChoice.type()) .isEqualTo(ChatCompletionNamedToolChoice.Type.FUNCTION) } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionSystemMessageParamTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionSystemMessageParamTest.kt index 5d9b93a..f55bb58 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionSystemMessageParamTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionSystemMessageParamTest.kt @@ -11,14 +11,14 @@ class ChatCompletionSystemMessageParamTest { fun createChatCompletionSystemMessageParam() { val chatCompletionSystemMessageParam = ChatCompletionSystemMessageParam.builder() - .content("string") + .content("content") .role(ChatCompletionSystemMessageParam.Role.SYSTEM) - .name("string") + .name("name") .build() assertThat(chatCompletionSystemMessageParam).isNotNull - assertThat(chatCompletionSystemMessageParam.content()).isEqualTo("string") + assertThat(chatCompletionSystemMessageParam.content()).isEqualTo("content") assertThat(chatCompletionSystemMessageParam.role()) .isEqualTo(ChatCompletionSystemMessageParam.Role.SYSTEM) - assertThat(chatCompletionSystemMessageParam.name()).contains("string") + assertThat(chatCompletionSystemMessageParam.name()).contains("name") } } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTest.kt index 3d9206b..370383b 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTest.kt @@ -11,7 +11,7 @@ class ChatCompletionTest { fun createChatCompletion() { val chatCompletion = ChatCompletion.builder() - .id("string") + .id("id") .choices( listOf( ChatCompletion.Choice.builder() @@ -22,14 +22,14 @@ class ChatCompletionTest { .content( listOf( ChatCompletionTokenLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .topLogprobs( listOf( ChatCompletionTokenLogprob.TopLogprob .builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .build() @@ -42,22 +42,22 @@ class ChatCompletionTest { ) .message( ChatCompletionMessage.builder() - .content("string") + .content("content") .role(ChatCompletionMessage.Role.ASSISTANT) .functionCall( ChatCompletionMessage.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .toolCalls( listOf( ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) @@ -70,10 +70,10 @@ class ChatCompletionTest { ) ) .created(123L) - .model("string") + .model("model") .object_(ChatCompletion.Object.CHAT_COMPLETION) .serviceTier(ChatCompletion.ServiceTier.SCALE) - .systemFingerprint("string") + .systemFingerprint("system_fingerprint") .usage( ChatCompletion.Usage.builder() .completionTokens(123L) @@ -83,7 +83,7 @@ class ChatCompletionTest { ) .build() assertThat(chatCompletion).isNotNull - assertThat(chatCompletion.id()).isEqualTo("string") + assertThat(chatCompletion.id()).isEqualTo("id") assertThat(chatCompletion.choices()) .containsExactly( ChatCompletion.Choice.builder() @@ -94,13 +94,13 @@ class ChatCompletionTest { .content( listOf( ChatCompletionTokenLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .topLogprobs( listOf( ChatCompletionTokenLogprob.TopLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .build() @@ -113,22 +113,22 @@ class ChatCompletionTest { ) .message( ChatCompletionMessage.builder() - .content("string") + .content("content") .role(ChatCompletionMessage.Role.ASSISTANT) .functionCall( ChatCompletionMessage.FunctionCall.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .toolCalls( listOf( ChatCompletionMessageToolCall.builder() - .id("string") + .id("id") .function( ChatCompletionMessageToolCall.Function.builder() - .arguments("string") - .name("string") + .arguments("arguments") + .name("name") .build() ) .type(ChatCompletionMessageToolCall.Type.FUNCTION) @@ -140,10 +140,10 @@ class ChatCompletionTest { .build() ) assertThat(chatCompletion.created()).isEqualTo(123L) - assertThat(chatCompletion.model()).isEqualTo("string") + assertThat(chatCompletion.model()).isEqualTo("model") assertThat(chatCompletion.object_()).isEqualTo(ChatCompletion.Object.CHAT_COMPLETION) assertThat(chatCompletion.serviceTier()).contains(ChatCompletion.ServiceTier.SCALE) - assertThat(chatCompletion.systemFingerprint()).contains("string") + assertThat(chatCompletion.systemFingerprint()).contains("system_fingerprint") assertThat(chatCompletion.usage()) .contains( ChatCompletion.Usage.builder() diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTokenLogprobTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTokenLogprobTest.kt index 8f5bbd8..3b81ec2 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTokenLogprobTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionTokenLogprobTest.kt @@ -11,13 +11,13 @@ class ChatCompletionTokenLogprobTest { fun createChatCompletionTokenLogprob() { val chatCompletionTokenLogprob = ChatCompletionTokenLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .topLogprobs( listOf( ChatCompletionTokenLogprob.TopLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .build() @@ -25,13 +25,13 @@ class ChatCompletionTokenLogprobTest { ) .build() assertThat(chatCompletionTokenLogprob).isNotNull - assertThat(chatCompletionTokenLogprob.token()).isEqualTo("string") + assertThat(chatCompletionTokenLogprob.token()).isEqualTo("token") assertThat(chatCompletionTokenLogprob.bytes().get()).containsExactly(123L) assertThat(chatCompletionTokenLogprob.logprob()).isEqualTo(42.23) assertThat(chatCompletionTokenLogprob.topLogprobs()) .containsExactly( ChatCompletionTokenLogprob.TopLogprob.builder() - .token("string") + .token("token") .bytes(listOf(123L)) .logprob(42.23) .build() diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolMessageParamTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolMessageParamTest.kt index f2ab358..0353641 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolMessageParamTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolMessageParamTest.kt @@ -11,14 +11,14 @@ class ChatCompletionToolMessageParamTest { fun createChatCompletionToolMessageParam() { val chatCompletionToolMessageParam = ChatCompletionToolMessageParam.builder() - .content("string") + .content("content") .role(ChatCompletionToolMessageParam.Role.TOOL) - .toolCallId("string") + .toolCallId("tool_call_id") .build() assertThat(chatCompletionToolMessageParam).isNotNull - assertThat(chatCompletionToolMessageParam.content()).isEqualTo("string") + assertThat(chatCompletionToolMessageParam.content()).isEqualTo("content") assertThat(chatCompletionToolMessageParam.role()) .isEqualTo(ChatCompletionToolMessageParam.Role.TOOL) - assertThat(chatCompletionToolMessageParam.toolCallId()).isEqualTo("string") + assertThat(chatCompletionToolMessageParam.toolCallId()).isEqualTo("tool_call_id") } } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolTest.kt index 0456dab..b4756ad 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionToolTest.kt @@ -13,8 +13,8 @@ class ChatCompletionToolTest { ChatCompletionTool.builder() .function( FunctionDefinition.builder() - .name("string") - .description("string") + .name("name") + .description("description") .parameters(FunctionParameters.builder().build()) .build() ) @@ -24,8 +24,8 @@ class ChatCompletionToolTest { assertThat(chatCompletionTool.function()) .isEqualTo( FunctionDefinition.builder() - .name("string") - .description("string") + .name("name") + .description("description") .parameters(FunctionParameters.builder().build()) .build() ) diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionUserMessageParamTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionUserMessageParamTest.kt index 984826f..c7d7d6e 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionUserMessageParamTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ChatCompletionUserMessageParamTest.kt @@ -13,13 +13,13 @@ class ChatCompletionUserMessageParamTest { ChatCompletionUserMessageParam.builder() .content(ChatCompletionUserMessageParam.Content.ofString("string")) .role(ChatCompletionUserMessageParam.Role.USER) - .name("string") + .name("name") .build() assertThat(chatCompletionUserMessageParam).isNotNull assertThat(chatCompletionUserMessageParam.content()) .isEqualTo(ChatCompletionUserMessageParam.Content.ofString("string")) assertThat(chatCompletionUserMessageParam.role()) .isEqualTo(ChatCompletionUserMessageParam.Role.USER) - assertThat(chatCompletionUserMessageParam.name()).contains("string") + assertThat(chatCompletionUserMessageParam.name()).contains("name") } } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ErrorObjectTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ErrorObjectTest.kt index cf0ba27..bab8cf5 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/ErrorObjectTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/ErrorObjectTest.kt @@ -11,15 +11,15 @@ class ErrorObjectTest { fun createErrorObject() { val errorObject = ErrorObject.builder() - .code("string") - .message("string") - .param("string") - .type("string") + .code("code") + .message("message") + .param("param") + .type("type") .build() assertThat(errorObject).isNotNull - assertThat(errorObject.code()).contains("string") - assertThat(errorObject.message()).isEqualTo("string") - assertThat(errorObject.param()).contains("string") - assertThat(errorObject.type()).isEqualTo("string") + assertThat(errorObject.code()).contains("code") + assertThat(errorObject.message()).isEqualTo("message") + assertThat(errorObject.param()).contains("param") + assertThat(errorObject.type()).isEqualTo("type") } } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FileDeletedTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FileDeletedTest.kt new file mode 100644 index 0000000..b085d58 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FileDeletedTest.kt @@ -0,0 +1,19 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FileDeletedTest { + + @Test + fun createFileDeleted() { + val fileDeleted = + FileDeleted.builder().id("id").deleted(true).object_(FileDeleted.Object.FILE).build() + assertThat(fileDeleted).isNotNull + assertThat(fileDeleted.id()).isEqualTo("id") + assertThat(fileDeleted.deleted()).isEqualTo(true) + assertThat(fileDeleted.object_()).isEqualTo(FileDeleted.Object.FILE) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FileObjectTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FileObjectTest.kt new file mode 100644 index 0000000..451c7f2 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FileObjectTest.kt @@ -0,0 +1,33 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FileObjectTest { + + @Test + fun createFileObject() { + val fileObject = + FileObject.builder() + .id("id") + .bytes(123L) + .createdAt(123L) + .filename("filename") + .object_(FileObject.Object.FILE) + .purpose(FileObject.Purpose.ASSISTANTS) + .status(FileObject.Status.UPLOADED) + .statusDetails("status_details") + .build() + assertThat(fileObject).isNotNull + assertThat(fileObject.id()).isEqualTo("id") + assertThat(fileObject.bytes()).isEqualTo(123L) + assertThat(fileObject.createdAt()).isEqualTo(123L) + assertThat(fileObject.filename()).isEqualTo("filename") + assertThat(fileObject.object_()).isEqualTo(FileObject.Object.FILE) + assertThat(fileObject.purpose()).isEqualTo(FileObject.Purpose.ASSISTANTS) + assertThat(fileObject.status()).isEqualTo(FileObject.Status.UPLOADED) + assertThat(fileObject.statusDetails()).contains("status_details") + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobCheckpointTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobCheckpointTest.kt new file mode 100644 index 0000000..69d71b1 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobCheckpointTest.kt @@ -0,0 +1,54 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FineTuningJobCheckpointTest { + + @Test + fun createFineTuningJobCheckpoint() { + val fineTuningJobCheckpoint = + FineTuningJobCheckpoint.builder() + .id("id") + .createdAt(123L) + .fineTunedModelCheckpoint("fine_tuned_model_checkpoint") + .fineTuningJobId("fine_tuning_job_id") + .metrics( + FineTuningJobCheckpoint.Metrics.builder() + .fullValidLoss(42.23) + .fullValidMeanTokenAccuracy(42.23) + .step(42.23) + .trainLoss(42.23) + .trainMeanTokenAccuracy(42.23) + .validLoss(42.23) + .validMeanTokenAccuracy(42.23) + .build() + ) + .object_(FineTuningJobCheckpoint.Object.FINE_TUNING_JOB_CHECKPOINT) + .stepNumber(123L) + .build() + assertThat(fineTuningJobCheckpoint).isNotNull + assertThat(fineTuningJobCheckpoint.id()).isEqualTo("id") + assertThat(fineTuningJobCheckpoint.createdAt()).isEqualTo(123L) + assertThat(fineTuningJobCheckpoint.fineTunedModelCheckpoint()) + .isEqualTo("fine_tuned_model_checkpoint") + assertThat(fineTuningJobCheckpoint.fineTuningJobId()).isEqualTo("fine_tuning_job_id") + assertThat(fineTuningJobCheckpoint.metrics()) + .isEqualTo( + FineTuningJobCheckpoint.Metrics.builder() + .fullValidLoss(42.23) + .fullValidMeanTokenAccuracy(42.23) + .step(42.23) + .trainLoss(42.23) + .trainMeanTokenAccuracy(42.23) + .validLoss(42.23) + .validMeanTokenAccuracy(42.23) + .build() + ) + assertThat(fineTuningJobCheckpoint.object_()) + .isEqualTo(FineTuningJobCheckpoint.Object.FINE_TUNING_JOB_CHECKPOINT) + assertThat(fineTuningJobCheckpoint.stepNumber()).isEqualTo(123L) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobEventTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobEventTest.kt new file mode 100644 index 0000000..f5e78a7 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobEventTest.kt @@ -0,0 +1,28 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FineTuningJobEventTest { + + @Test + fun createFineTuningJobEvent() { + val fineTuningJobEvent = + FineTuningJobEvent.builder() + .id("id") + .createdAt(123L) + .level(FineTuningJobEvent.Level.INFO) + .message("message") + .object_(FineTuningJobEvent.Object.FINE_TUNING_JOB_EVENT) + .build() + assertThat(fineTuningJobEvent).isNotNull + assertThat(fineTuningJobEvent.id()).isEqualTo("id") + assertThat(fineTuningJobEvent.createdAt()).isEqualTo(123L) + assertThat(fineTuningJobEvent.level()).isEqualTo(FineTuningJobEvent.Level.INFO) + assertThat(fineTuningJobEvent.message()).isEqualTo("message") + assertThat(fineTuningJobEvent.object_()) + .isEqualTo(FineTuningJobEvent.Object.FINE_TUNING_JOB_EVENT) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobTest.kt new file mode 100644 index 0000000..740f897 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobTest.kt @@ -0,0 +1,104 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FineTuningJobTest { + + @Test + fun createFineTuningJob() { + val fineTuningJob = + FineTuningJob.builder() + .id("id") + .createdAt(123L) + .error( + FineTuningJob.Error.builder() + .code("code") + .message("message") + .param("param") + .build() + ) + .fineTunedModel("fine_tuned_model") + .finishedAt(123L) + .hyperparameters( + FineTuningJob.Hyperparameters.builder() + .nEpochs( + FineTuningJob.Hyperparameters.NEpochs.ofUnionMember0( + FineTuningJob.Hyperparameters.NEpochs.UnionMember0.AUTO + ) + ) + .build() + ) + .model("model") + .object_(FineTuningJob.Object.FINE_TUNING_JOB) + .organizationId("organization_id") + .resultFiles(listOf("file-abc123")) + .seed(123L) + .status(FineTuningJob.Status.VALIDATING_FILES) + .trainedTokens(123L) + .trainingFile("training_file") + .validationFile("validation_file") + .estimatedFinish(123L) + .integrations( + listOf( + FineTuningJobWandbIntegrationObject.builder() + .type(FineTuningJobWandbIntegrationObject.Type.WANDB) + .wandb( + FineTuningJobWandbIntegration.builder() + .project("my-wandb-project") + .entity("entity") + .name("name") + .tags(listOf("custom-tag")) + .build() + ) + .build() + ) + ) + .build() + assertThat(fineTuningJob).isNotNull + assertThat(fineTuningJob.id()).isEqualTo("id") + assertThat(fineTuningJob.createdAt()).isEqualTo(123L) + assertThat(fineTuningJob.error()) + .contains( + FineTuningJob.Error.builder().code("code").message("message").param("param").build() + ) + assertThat(fineTuningJob.fineTunedModel()).contains("fine_tuned_model") + assertThat(fineTuningJob.finishedAt()).contains(123L) + assertThat(fineTuningJob.hyperparameters()) + .isEqualTo( + FineTuningJob.Hyperparameters.builder() + .nEpochs( + FineTuningJob.Hyperparameters.NEpochs.ofUnionMember0( + FineTuningJob.Hyperparameters.NEpochs.UnionMember0.AUTO + ) + ) + .build() + ) + assertThat(fineTuningJob.model()).isEqualTo("model") + assertThat(fineTuningJob.object_()).isEqualTo(FineTuningJob.Object.FINE_TUNING_JOB) + assertThat(fineTuningJob.organizationId()).isEqualTo("organization_id") + assertThat(fineTuningJob.resultFiles()).containsExactly("file-abc123") + assertThat(fineTuningJob.seed()).isEqualTo(123L) + assertThat(fineTuningJob.status()).isEqualTo(FineTuningJob.Status.VALIDATING_FILES) + assertThat(fineTuningJob.trainedTokens()).contains(123L) + assertThat(fineTuningJob.trainingFile()).isEqualTo("training_file") + assertThat(fineTuningJob.validationFile()).contains("validation_file") + assertThat(fineTuningJob.estimatedFinish()).contains(123L) + assertThat(fineTuningJob.integrations().get()) + .containsExactly( + FineTuningJobWandbIntegrationObject.builder() + .type(FineTuningJobWandbIntegrationObject.Type.WANDB) + .wandb( + FineTuningJobWandbIntegration.builder() + .project("my-wandb-project") + .entity("entity") + .name("name") + .tags(listOf("custom-tag")) + .build() + ) + .build() + ) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobWandbIntegrationObjectTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobWandbIntegrationObjectTest.kt new file mode 100644 index 0000000..fe22f07 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobWandbIntegrationObjectTest.kt @@ -0,0 +1,37 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FineTuningJobWandbIntegrationObjectTest { + + @Test + fun createFineTuningJobWandbIntegrationObject() { + val fineTuningJobWandbIntegrationObject = + FineTuningJobWandbIntegrationObject.builder() + .type(FineTuningJobWandbIntegrationObject.Type.WANDB) + .wandb( + FineTuningJobWandbIntegration.builder() + .project("my-wandb-project") + .entity("entity") + .name("name") + .tags(listOf("custom-tag")) + .build() + ) + .build() + assertThat(fineTuningJobWandbIntegrationObject).isNotNull + assertThat(fineTuningJobWandbIntegrationObject.type()) + .isEqualTo(FineTuningJobWandbIntegrationObject.Type.WANDB) + assertThat(fineTuningJobWandbIntegrationObject.wandb()) + .isEqualTo( + FineTuningJobWandbIntegration.builder() + .project("my-wandb-project") + .entity("entity") + .name("name") + .tags(listOf("custom-tag")) + .build() + ) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobWandbIntegrationTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobWandbIntegrationTest.kt new file mode 100644 index 0000000..6c66f46 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/FineTuningJobWandbIntegrationTest.kt @@ -0,0 +1,25 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class FineTuningJobWandbIntegrationTest { + + @Test + fun createFineTuningJobWandbIntegration() { + val fineTuningJobWandbIntegration = + FineTuningJobWandbIntegration.builder() + .project("my-wandb-project") + .entity("entity") + .name("name") + .tags(listOf("custom-tag")) + .build() + assertThat(fineTuningJobWandbIntegration).isNotNull + assertThat(fineTuningJobWandbIntegration.project()).isEqualTo("my-wandb-project") + assertThat(fineTuningJobWandbIntegration.entity()).contains("entity") + assertThat(fineTuningJobWandbIntegration.name()).contains("name") + assertThat(fineTuningJobWandbIntegration.tags().get()).containsExactly("custom-tag") + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/FunctionDefinitionTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/FunctionDefinitionTest.kt index 33e85c2..231e49e 100644 --- a/openai-java-core/src/test/kotlin/com/openai/models/FunctionDefinitionTest.kt +++ b/openai-java-core/src/test/kotlin/com/openai/models/FunctionDefinitionTest.kt @@ -11,13 +11,13 @@ class FunctionDefinitionTest { fun createFunctionDefinition() { val functionDefinition = FunctionDefinition.builder() - .name("string") - .description("string") + .name("name") + .description("description") .parameters(FunctionParameters.builder().build()) .build() assertThat(functionDefinition).isNotNull - assertThat(functionDefinition.name()).isEqualTo("string") - assertThat(functionDefinition.description()).contains("string") + assertThat(functionDefinition.name()).isEqualTo("name") + assertThat(functionDefinition.description()).contains("description") assertThat(functionDefinition.parameters()).contains(FunctionParameters.builder().build()) } } diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ModelDeletedTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ModelDeletedTest.kt new file mode 100644 index 0000000..e4e4a31 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/ModelDeletedTest.kt @@ -0,0 +1,18 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModelDeletedTest { + + @Test + fun createModelDeleted() { + val modelDeleted = ModelDeleted.builder().id("id").deleted(true).object_("object").build() + assertThat(modelDeleted).isNotNull + assertThat(modelDeleted.id()).isEqualTo("id") + assertThat(modelDeleted.deleted()).isEqualTo(true) + assertThat(modelDeleted.object_()).isEqualTo("object") + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ModelTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ModelTest.kt new file mode 100644 index 0000000..40627ae --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/ModelTest.kt @@ -0,0 +1,25 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModelTest { + + @Test + fun createModel() { + val model = + Model.builder() + .id("id") + .created(123L) + .object_(Model.Object.MODEL) + .ownedBy("owned_by") + .build() + assertThat(model).isNotNull + assertThat(model.id()).isEqualTo("id") + assertThat(model.created()).isEqualTo(123L) + assertThat(model.object_()).isEqualTo(Model.Object.MODEL) + assertThat(model.ownedBy()).isEqualTo("owned_by") + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ModerationCreateResponseTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ModerationCreateResponseTest.kt new file mode 100644 index 0000000..00450ff --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/ModerationCreateResponseTest.kt @@ -0,0 +1,94 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModerationCreateResponseTest { + + @Test + fun createModerationCreateResponse() { + val moderationCreateResponse = + ModerationCreateResponse.builder() + .id("id") + .model("model") + .results( + listOf( + Moderation.builder() + .categories( + Moderation.Categories.builder() + .harassment(true) + .harassmentThreatening(true) + .hate(true) + .hateThreatening(true) + .selfHarm(true) + .selfHarmInstructions(true) + .selfHarmIntent(true) + .sexual(true) + .sexualMinors(true) + .violence(true) + .violenceGraphic(true) + .build() + ) + .categoryScores( + Moderation.CategoryScores.builder() + .harassment(42.23) + .harassmentThreatening(42.23) + .hate(42.23) + .hateThreatening(42.23) + .selfHarm(42.23) + .selfHarmInstructions(42.23) + .selfHarmIntent(42.23) + .sexual(42.23) + .sexualMinors(42.23) + .violence(42.23) + .violenceGraphic(42.23) + .build() + ) + .flagged(true) + .build() + ) + ) + .build() + assertThat(moderationCreateResponse).isNotNull + assertThat(moderationCreateResponse.id()).isEqualTo("id") + assertThat(moderationCreateResponse.model()).isEqualTo("model") + assertThat(moderationCreateResponse.results()) + .containsExactly( + Moderation.builder() + .categories( + Moderation.Categories.builder() + .harassment(true) + .harassmentThreatening(true) + .hate(true) + .hateThreatening(true) + .selfHarm(true) + .selfHarmInstructions(true) + .selfHarmIntent(true) + .sexual(true) + .sexualMinors(true) + .violence(true) + .violenceGraphic(true) + .build() + ) + .categoryScores( + Moderation.CategoryScores.builder() + .harassment(42.23) + .harassmentThreatening(42.23) + .hate(42.23) + .hateThreatening(42.23) + .selfHarm(42.23) + .selfHarmInstructions(42.23) + .selfHarmIntent(42.23) + .sexual(42.23) + .sexualMinors(42.23) + .violence(42.23) + .violenceGraphic(42.23) + .build() + ) + .flagged(true) + .build() + ) + } +} diff --git a/openai-java-core/src/test/kotlin/com/openai/models/ModerationTest.kt b/openai-java-core/src/test/kotlin/com/openai/models/ModerationTest.kt new file mode 100644 index 0000000..307b945 --- /dev/null +++ b/openai-java-core/src/test/kotlin/com/openai/models/ModerationTest.kt @@ -0,0 +1,81 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.openai.models + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +class ModerationTest { + + @Test + fun createModeration() { + val moderation = + Moderation.builder() + .categories( + Moderation.Categories.builder() + .harassment(true) + .harassmentThreatening(true) + .hate(true) + .hateThreatening(true) + .selfHarm(true) + .selfHarmInstructions(true) + .selfHarmIntent(true) + .sexual(true) + .sexualMinors(true) + .violence(true) + .violenceGraphic(true) + .build() + ) + .categoryScores( + Moderation.CategoryScores.builder() + .harassment(42.23) + .harassmentThreatening(42.23) + .hate(42.23) + .hateThreatening(42.23) + .selfHarm(42.23) + .selfHarmInstructions(42.23) + .selfHarmIntent(42.23) + .sexual(42.23) + .sexualMinors(42.23) + .violence(42.23) + .violenceGraphic(42.23) + .build() + ) + .flagged(true) + .build() + assertThat(moderation).isNotNull + assertThat(moderation.categories()) + .isEqualTo( + Moderation.Categories.builder() + .harassment(true) + .harassmentThreatening(true) + .hate(true) + .hateThreatening(true) + .selfHarm(true) + .selfHarmInstructions(true) + .selfHarmIntent(true) + .sexual(true) + .sexualMinors(true) + .violence(true) + .violenceGraphic(true) + .build() + ) + assertThat(moderation.categoryScores()) + .isEqualTo( + Moderation.CategoryScores.builder() + .harassment(42.23) + .harassmentThreatening(42.23) + .hate(42.23) + .hateThreatening(42.23) + .selfHarm(42.23) + .selfHarmInstructions(42.23) + .selfHarmIntent(42.23) + .sexual(42.23) + .sexualMinors(42.23) + .violence(42.23) + .violenceGraphic(42.23) + .build() + ) + assertThat(moderation.flagged()).isEqualTo(true) + } +}