diff --git a/.fern/metadata.json b/.fern/metadata.json new file mode 100644 index 0000000..43e209a --- /dev/null +++ b/.fern/metadata.json @@ -0,0 +1,8 @@ +{ + "cliVersion": "0.109.1", + "generatorName": "fernapi/fern-java-sdk", + "generatorVersion": "3.13.0", + "generatorConfig": { + "client-class-name": "Cohere" + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 6da2fa7..b05c9e2 100644 --- a/build.gradle +++ b/build.gradle @@ -20,6 +20,7 @@ dependencies { api 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.17.2' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.8.2' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.2' } @@ -46,7 +47,7 @@ java { group = 'com.cohere' -version = '1.8.2' +version = '1.9.0' jar { dependsOn(":generatePomFileForMavenPublication") @@ -77,7 +78,7 @@ publishing { maven(MavenPublication) { groupId = 'com.cohere' artifactId = 'cohere-java' - version = '1.8.2' + version = '1.9.0' from components.java pom { name = 'cohere' @@ -120,9 +121,10 @@ sonatypeCentralUpload { } signing { - def signingKeyId = "$System.env.MAVEN_SIGNATURE_SECRET_KEY" + def signingKeyId = "$System.env.MAVEN_SIGNATURE_KID" + def signingKey = "$System.env.MAVEN_SIGNATURE_SECRET_KEY" def signingPassword = "$System.env.MAVEN_SIGNATURE_PASSWORD" - useInMemoryPgpKeys(signingKeyId, signingPassword) + useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword) sign publishing.publications.maven } diff --git a/reference.md b/reference.md index 0a2e614..578cd07 100644 --- a/reference.md +++ b/reference.md @@ -31,8 +31,9 @@ To learn how to use the Chat API and RAG follow our [Text Generation guides](htt client.chatStream( ChatStreamRequest .builder() - .message("hello world!") + .message("hello!") .stream(true) + .model("command-a-03-2025") .build() ); ``` @@ -223,9 +224,8 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D **citationQuality:** `Optional` -Defaults to `"accurate"`. - -Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `"accurate"` results, `"fast"` results or no results. +Defaults to `"enabled"`. +Citations are enabled by default for models that support it, but can be turned off by setting `"type": "disabled"`. Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments @@ -290,7 +290,7 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D
-**p:** `Optional` +**p:** `Optional` Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`. Defaults to `0.75`. min value of `0.01`, max value of `0.99`. @@ -330,7 +330,7 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D
-**frequencyPenalty:** `Optional` +**frequencyPenalty:** `Optional` Defaults to `0.0`, min value of `0.0`, max value of `1.0`. @@ -344,7 +344,7 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D
-**presencePenalty:** `Optional` +**presencePenalty:** `Optional` Defaults to `0.0`, min value of `0.0`, max value of `1.0`. @@ -487,36 +487,9 @@ To learn how to use the Chat API and RAG follow our [Text Generation guides](htt client.chatStream( ChatStreamRequest .builder() - .message("What year was he born?") + .message("Tell me about LLMs") .stream(false) - .chatHistory( - new ArrayList( - Arrays.asList( - Message.user( - ChatMessage - .builder() - .message("Who discovered gravity?") - .build() - ), - Message.chatbot( - ChatMessage - .builder() - .message("The man who is widely credited with discovering gravity is Sir Isaac Newton") - .build() - ) - ) - ) - ) - .connectors( - new ArrayList( - Arrays.asList( - ChatConnector - .builder() - .id("web-search") - .build() - ) - ) - ) + .model("command-a-03-2025") .build() ); ``` @@ -707,9 +680,8 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D **citationQuality:** `Optional` -Defaults to `"accurate"`. - -Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want `"accurate"` results, `"fast"` results or no results. +Defaults to `"enabled"`. +Citations are enabled by default for models that support it, but can be turned off by setting `"type": "disabled"`. Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments @@ -774,7 +746,7 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D
-**p:** `Optional` +**p:** `Optional` Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`. Defaults to `0.75`. min value of `0.01`, max value of `0.99`. @@ -814,7 +786,7 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D
-**frequencyPenalty:** `Optional` +**frequencyPenalty:** `Optional` Defaults to `0.0`, min value of `0.0`, max value of `1.0`. @@ -828,7 +800,7 @@ Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private D
-**presencePenalty:** `Optional` +**presencePenalty:** `Optional` Defaults to `0.0`, min value of `0.0`, max value of `1.0`. @@ -1065,7 +1037,7 @@ If `NONE` is selected, when the input exceeds the maximum input token length an
-**temperature:** `Optional` +**temperature:** `Optional` A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See [Temperature](/temperature-wiki) for more details. Defaults to `0.75`, min value of `0.0`, max value of `5.0`. @@ -1128,7 +1100,7 @@ Defaults to `0`, min value of `0`, max value of `500`.
-**p:** `Optional` +**p:** `Optional` Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`. Defaults to `0.75`. min value of `0.01`, max value of `0.99`. @@ -1139,7 +1111,7 @@ Defaults to `0.75`. min value of `0.01`, max value of `0.99`.
-**frequencyPenalty:** `Optional` +**frequencyPenalty:** `Optional` Used to reduce repetitiveness of generated tokens. The higher the value, the stronger a penalty is applied to previously present tokens, proportional to how many times they have already appeared in the prompt or prior generation. @@ -1151,7 +1123,7 @@ Using `frequency_penalty` in combination with `presence_penalty` is not supporte
-**presencePenalty:** `Optional` +**presencePenalty:** `Optional` Defaults to `0.0`, min value of `0.0`, max value of `1.0`. @@ -1316,7 +1288,7 @@ If `NONE` is selected, when the input exceeds the maximum input token length an
-**temperature:** `Optional` +**temperature:** `Optional` A non-negative float that tunes the degree of randomness in generation. Lower temperatures mean less random generations. See [Temperature](/temperature-wiki) for more details. Defaults to `0.75`, min value of `0.0`, max value of `5.0`. @@ -1379,7 +1351,7 @@ Defaults to `0`, min value of `0`, max value of `500`.
-**p:** `Optional` +**p:** `Optional` Ensures that only the most likely tokens, with total probability mass of `p`, are considered for generation at each step. If both `k` and `p` are enabled, `p` acts after `k`. Defaults to `0.75`. min value of `0.01`, max value of `0.99`. @@ -1390,7 +1362,7 @@ Defaults to `0.75`. min value of `0.01`, max value of `0.99`.
-**frequencyPenalty:** `Optional` +**frequencyPenalty:** `Optional` Used to reduce repetitiveness of generated tokens. The higher the value, the stronger a penalty is applied to previously present tokens, proportional to how many times they have already appeared in the prompt or prior generation. @@ -1402,7 +1374,7 @@ Using `frequency_penalty` in combination with `presence_penalty` is not supporte
-**presencePenalty:** `Optional` +**presencePenalty:** `Optional` Defaults to `0.0`, min value of `0.0`, max value of `1.0`. @@ -1477,7 +1449,7 @@ client.embed( EmbedRequest .builder() .texts( - new ArrayList( + Optional.of( Arrays.asList("hello", "goodbye") ) ) @@ -1511,7 +1483,7 @@ client.embed( An array of image data URIs for the model to embed. Maximum number of images per call is `1`. -The image must be a valid [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data). The image must be in either `image/jpeg` or `image/png` format and has a maximum size of 5MB. +The image must be a valid [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data). The image must be in either `image/jpeg`, `image/png`, `image/webp`, or `image/gif` format and has a maximum size of 5MB. Images are only supported with Embed v3.0 and newer models. @@ -1602,14 +1574,12 @@ client.rerank( RerankRequest .builder() .documents( - new ArrayList( - Arrays.asList( - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of(), - RerankRequestDocumentsItem.of() - ) + Arrays.asList( + RerankRequestDocumentsItem.of(), + RerankRequestDocumentsItem.of(), + RerankRequestDocumentsItem.of(), + RerankRequestDocumentsItem.of(), + RerankRequestDocumentsItem.of() ) ) .query("What is the capital of the United States?") @@ -1733,12 +1703,10 @@ client.classify( ClassifyRequest .builder() .inputs( - new ArrayList( - Arrays.asList("Confirm your email address", "hey i need u to send some $") - ) + Arrays.asList("Confirm your email address", "hey i need u to send some $") ) .examples( - new ArrayList( + Optional.of( Arrays.asList( ClassifyExample .builder() @@ -1957,7 +1925,7 @@ client.summarize(
-**temperature:** `Optional` — Ranges from 0 to 5. Controls the randomness of the output. Lower values tend to generate more “predictable” output, while higher values tend to generate more “creative” output. The sweet spot is typically between 0 and 1. +**temperature:** `Optional` — Ranges from 0 to 5. Controls the randomness of the output. Lower values tend to generate more “predictable” output, while higher values tend to generate more “creative” output. The sweet spot is typically between 0 and 1.
@@ -2076,9 +2044,7 @@ client.detokenize( DetokenizeRequest .builder() .tokens( - new ArrayList( - Arrays.asList(10002, 2261, 2012, 8, 2792, 43) - ) + Arrays.asList(10002, 2261, 2012, 8, 2792, 43) ) .model("command") .build() @@ -2189,18 +2155,16 @@ Follow the [Migration Guide](https://docs.cohere.com/v2/docs/migrating-v1-to-v2) client.v2().chatStream( V2ChatStreamRequest .builder() - .model("command-r") + .model("command-a-03-2025") .messages( - new ArrayList( - Arrays.asList( - ChatMessageV2.user( - UserMessageV2 - .builder() - .content( - UserMessageV2Content.of("Hello!") - ) - .build() - ) + Arrays.asList( + ChatMessageV2.user( + UserMessageV2 + .builder() + .content( + UserMessageV2Content.of("Tell me about LLMs") + ) + .build() ) ) ) @@ -2235,7 +2199,7 @@ Streaming is beneficial for user interfaces that render the contents of the resp
-**model:** `String` — The name of a compatible [Cohere model](https://docs.cohere.com/v2/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/v2/docs/chat-fine-tuning) model. +**model:** `String` — The name of a compatible [Cohere model](https://docs.cohere.com/v2/docs/models).
@@ -2433,6 +2397,17 @@ If tool_choice isn't specified, then the model is free to choose whether to use **thinking:** `Optional` +
+
+ +
+
+ +**priority:** `Optional` + +The priority of the request (lower means earlier handling; default 0 highest priority). +Higher priority requests are handled first, and dropped last when the system is under load. +
@@ -2477,16 +2452,14 @@ client.v2().chatStream( .builder() .model("command-a-03-2025") .messages( - new ArrayList( - Arrays.asList( - ChatMessageV2.user( - UserMessageV2 - .builder() - .content( - UserMessageV2Content.of("Tell me about LLMs") - ) - .build() - ) + Arrays.asList( + ChatMessageV2.user( + UserMessageV2 + .builder() + .content( + UserMessageV2Content.of("Tell me about LLMs") + ) + .build() ) ) ) @@ -2521,7 +2494,7 @@ Streaming is beneficial for user interfaces that render the contents of the resp
-**model:** `String` — The name of a compatible [Cohere model](https://docs.cohere.com/v2/docs/models) or the ID of a [fine-tuned](https://docs.cohere.com/v2/docs/chat-fine-tuning) model. +**model:** `String` — The name of a compatible [Cohere model](https://docs.cohere.com/v2/docs/models).
@@ -2719,6 +2692,17 @@ If tool_choice isn't specified, then the model is free to choose whether to use **thinking:** `Optional` +
+
+ +
+
+ +**priority:** `Optional` + +The priority of the request (lower means earlier handling; default 0 highest priority). +Higher priority requests are handled first, and dropped last when the system is under load. +
@@ -2766,12 +2750,12 @@ client.v2().embed( .model("embed-v4.0") .inputType(EmbedInputType.CLASSIFICATION) .texts( - new ArrayList( + Optional.of( Arrays.asList("hello", "goodbye") ) ) .embeddingTypes( - new ArrayList( + Optional.of( Arrays.asList(EmbeddingType.FLOAT) ) ) @@ -2803,7 +2787,7 @@ client.v2().embed( An array of image data URIs for the model to embed. Maximum number of images per call is `1`. -The image must be a valid [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data). The image must be in either `image/jpeg` or `image/png` format and has a maximum size of 5MB. +The image must be a valid [data URI](https://developer.mozilla.org/en-US/docs/Web/URI/Schemes/data). The image must be in either `image/jpeg`, `image/png`, `image/webp`, or `image/gif` format and has a maximum size of 5MB. Image embeddings are supported with Embed v3.0 and newer models. @@ -2881,6 +2865,17 @@ Passing `START` will discard the start of the input. `END` will discard the end If `NONE` is selected, when the input exceeds the maximum input token length an error will be returned. +
+
+ +
+
+ +**priority:** `Optional` + +The priority of the request (lower means earlier handling; default 0 highest priority). +Higher priority requests are handled first, and dropped last when the system is under load. +
@@ -2922,9 +2917,7 @@ client.v2().rerank( V2RerankRequest .builder() .documents( - new ArrayList( - Arrays.asList("Carson City is the capital city of the American state of Nevada.", "The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan.", "Capitalization or capitalisation in English grammar is the use of a capital letter at the start of a word. English usage varies from capitalization in other languages.", "Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district.", "Capital punishment has existed in the United States since beforethe United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states.") - ) + Arrays.asList("Carson City is the capital city of the American state of Nevada.", "The Commonwealth of the Northern Mariana Islands is a group of islands in the Pacific Ocean. Its capital is Saipan.", "Capitalization or capitalisation in English grammar is the use of a capital letter at the start of a word. English usage varies from capitalization in other languages.", "Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district.", "Capital punishment has existed in the United States since beforethe United States was a country. As of 2017, capital punishment is legal in 30 of the 50 states.") ) .query("What is the capital of the United States?") .model("rerank-v3.5") @@ -2986,6 +2979,275 @@ For optimal performance we recommend against sending more than 1,000 documents i **maxTokensPerDoc:** `Optional` — Defaults to `4096`. Long documents will be automatically truncated to the specified number of tokens. +
+
+ +
+
+ +**priority:** `Optional` + +The priority of the request (lower means earlier handling; default 0 highest priority). +Higher priority requests are handled first, and dropped last when the system is under load. + +
+
+
+
+ + +
+
+ + +## Batches +
client.batches.list() -> ListBatchesResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +List the batches for the current user +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```java +client.batches().list( + BatchesListBatchesRequest + .builder() + .pageSize(1) + .pageToken("page_token") + .orderBy("order_by") + .build() +); +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**pageSize:** `Optional` + +The maximum number of batches to return. The service may return fewer than +this value. +If unspecified, at most 50 batches will be returned. +The maximum value is 1000; values above 1000 will be coerced to 1000. + +
+
+ +
+
+ +**pageToken:** `Optional` + +A page token, received from a previous `ListBatches` call. +Provide this to retrieve the subsequent page. + +
+
+ +
+
+ +**orderBy:** `Optional` + +Batches can be ordered by creation time or last updated time. +Use `created_at` for creation time or `updated_at` for last updated time. + +
+
+
+
+ + +
+
+
+ +
client.batches.create(request) -> CreateBatchResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Creates and executes a batch from an uploaded dataset of requests +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```java +client.batches().create( + Batch + .builder() + .name("name") + .inputDatasetId("input_dataset_id") + .model("model") + .build() +); +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `Batch` + +
+
+
+
+ + +
+
+
+ +
client.batches.retrieve(id) -> GetBatchResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Retrieves a batch +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```java +client.batches().retrieve("id"); +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**id:** `String` — The batch ID. + +
+
+
+
+ + +
+
+
+ +
client.batches.cancel(id) -> Map<String, Object> +
+
+ +#### 📝 Description + +
+
+ +
+
+ +Cancels an in-progress batch +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```java +client.batches().cancel("id"); +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**id:** `String` — The batch ID. +
@@ -3297,6 +3559,12 @@ List datasets that have been created. client.datasets().list( DatasetsListRequest .builder() + .datasetType("datasetType") + .before(OffsetDateTime.parse("2024-01-15T09:30:00Z")) + .after(OffsetDateTime.parse("2024-01-15T09:30:00Z")) + .limit(1.1) + .offset(1.1) + .validationStatus(DatasetValidationStatus.UNKNOWN) .build() ); ``` @@ -3337,7 +3605,7 @@ client.datasets().list(
-**limit:** `Optional` — optional limit to number of results +**limit:** `Optional` — optional limit to number of results
@@ -3345,7 +3613,7 @@ client.datasets().list(
-**offset:** `Optional` — optional offset to start of results +**offset:** `Optional` — optional offset to start of results
@@ -3397,6 +3665,10 @@ client.datasets().create( .builder() .name("name") .type(DatasetType.EMBED_INPUT) + .keepOriginalFile(true) + .skipMalformedInput(true) + .textSeparator("text_separator") + .csvDelimiter("csv_delimiter") .build() ); ``` @@ -3421,7 +3693,7 @@ client.datasets().create(
-**type:** `DatasetType` — The dataset type, which is used to validate the data. Valid types are `embed-input`, `reranker-finetune-input`, `single-label-classification-finetune-input`, `chat-finetune-input`, and `multi-label-classification-finetune-input`. +**type:** `DatasetType` — The dataset type, which is used to validate the data. The only valid type is `embed-input` used in conjunction with the Embed Jobs API.
@@ -3659,6 +3931,8 @@ Returns a list of connectors ordered by descending creation date (newer first). client.connectors().list( ConnectorsListRequest .builder() + .limit(1.1) + .offset(1.1) .build() ); ``` @@ -3675,7 +3949,7 @@ client.connectors().list(
-**limit:** `Optional` — Maximum number of connectors to return [0, 100]. +**limit:** `Optional` — Maximum number of connectors to return [0, 100].
@@ -3683,7 +3957,7 @@ client.connectors().list(
-**offset:** `Optional` — Number of connectors to skip before returning results [0, inf]. +**offset:** `Optional` — Number of connectors to skip before returning results [0, inf].
@@ -4065,6 +4339,7 @@ client.connectors().oAuthAuthorize( "id", ConnectorsOAuthAuthorizeRequest .builder() + .afterTokenRedirect("after_token_redirect") .build() ); ``` @@ -4168,7 +4443,7 @@ client.models().get("command-a-03-2025");
-Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. +Returns a list of models available for use.
@@ -4186,6 +4461,10 @@ Returns a list of models available for use. The list contains models from Cohere client.models().list( ModelsListRequest .builder() + .pageSize(1.1) + .pageToken("page_token") + .endpoint(CompatibleEndpoint.CHAT) + .defaultOnly(true) .build() ); ``` @@ -4202,7 +4481,7 @@ client.models().list(
-**pageSize:** `Optional` +**pageSize:** `Optional` Maximum number of models to include in a page Defaults to `20`, min value of `1`, max value of `1000`. @@ -4272,6 +4551,9 @@ Returns a list of fine-tuned models that the user has access to. client.finetuning().listFinetunedModels( FinetuningListFinetunedModelsRequest .builder() + .pageSize(1) + .pageToken("page_token") + .orderBy("order_by") .build() ); ``` @@ -4635,6 +4917,9 @@ client.finetuning().listEvents( "finetuned_model_id", FinetuningListEventsRequest .builder() + .pageSize(1) + .pageToken("page_token") + .orderBy("order_by") .build() ); ``` @@ -4730,6 +5015,8 @@ client.finetuning().listTrainingStepMetrics( "finetuned_model_id", FinetuningListTrainingStepMetricsRequest .builder() + .pageSize(1) + .pageToken("page_token") .build() ); ``` diff --git a/src/main/java/com/cohere/api/AsyncCohere.java b/src/main/java/com/cohere/api/AsyncCohere.java index 5623a66..ff19ca9 100644 --- a/src/main/java/com/cohere/api/AsyncCohere.java +++ b/src/main/java/com/cohere/api/AsyncCohere.java @@ -16,6 +16,7 @@ import com.cohere.api.requests.RerankRequest; import com.cohere.api.requests.SummarizeRequest; import com.cohere.api.requests.TokenizeRequest; +import com.cohere.api.resources.batches.AsyncBatchesClient; import com.cohere.api.resources.connectors.AsyncConnectorsClient; import com.cohere.api.resources.datasets.AsyncDatasetsClient; import com.cohere.api.resources.embedjobs.AsyncEmbedJobsClient; @@ -43,6 +44,8 @@ public class AsyncCohere { protected final Supplier v2Client; + protected final Supplier batchesClient; + protected final Supplier embedJobsClient; protected final Supplier datasetsClient; @@ -57,6 +60,7 @@ public AsyncCohere(ClientOptions clientOptions) { this.clientOptions = clientOptions; this.rawClient = new AsyncRawCohere(clientOptions); this.v2Client = Suppliers.memoize(() -> new AsyncV2Client(clientOptions)); + this.batchesClient = Suppliers.memoize(() -> new AsyncBatchesClient(clientOptions)); this.embedJobsClient = Suppliers.memoize(() -> new AsyncEmbedJobsClient(clientOptions)); this.datasetsClient = Suppliers.memoize(() -> new AsyncDatasetsClient(clientOptions)); this.connectorsClient = Suppliers.memoize(() -> new AsyncConnectorsClient(clientOptions)); @@ -268,6 +272,10 @@ public AsyncV2Client v2() { return this.v2Client.get(); } + public AsyncBatchesClient batches() { + return this.batchesClient.get(); + } + public AsyncEmbedJobsClient embedJobs() { return this.embedJobsClient.get(); } diff --git a/src/main/java/com/cohere/api/AsyncCohereBuilder.java b/src/main/java/com/cohere/api/AsyncCohereBuilder.java index 8d89214..0aa8d20 100644 --- a/src/main/java/com/cohere/api/AsyncCohereBuilder.java +++ b/src/main/java/com/cohere/api/AsyncCohereBuilder.java @@ -5,6 +5,8 @@ import com.cohere.api.core.ClientOptions; import com.cohere.api.core.Environment; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import okhttp3.OkHttpClient; @@ -13,6 +15,8 @@ public class AsyncCohereBuilder { private Optional maxRetries = Optional.empty(); + private final Map customHeaders = new HashMap<>(); + private String token = System.getenv("CO_API_KEY"); private String clientName = null; @@ -72,6 +76,19 @@ public AsyncCohereBuilder httpClient(OkHttpClient httpClient) { return this; } + /** + * Add a custom header to be sent with all requests. + * For headers that need to be computed dynamically or conditionally, use the setAdditional() method override instead. + * + * @param name The header name + * @param value The header value + * @return This builder for method chaining + */ + public AsyncCohereBuilder addHeader(String name, String value) { + this.customHeaders.put(name, value); + return this; + } + protected ClientOptions buildClientOptions() { ClientOptions.Builder builder = ClientOptions.builder(); setEnvironment(builder); @@ -80,6 +97,9 @@ protected ClientOptions buildClientOptions() { setHttpClient(builder); setTimeouts(builder); setRetries(builder); + for (Map.Entry header : this.customHeaders.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } setAdditional(builder); return builder.build(); } @@ -209,9 +229,6 @@ protected void setAdditional(ClientOptions.Builder builder) {} protected void validateConfiguration() {} public AsyncCohere build() { - if (token == null) { - throw new RuntimeException("Please provide token or set the CO_API_KEY environment variable."); - } validateConfiguration(); return new AsyncCohere(buildClientOptions()); } diff --git a/src/main/java/com/cohere/api/AsyncRawCohere.java b/src/main/java/com/cohere/api/AsyncRawCohere.java index 32d586b..4e4ac98 100644 --- a/src/main/java/com/cohere/api/AsyncRawCohere.java +++ b/src/main/java/com/cohere/api/AsyncRawCohere.java @@ -88,79 +88,31 @@ public CompletableFuture>> cha .build(); Map properties = new HashMap<>(); properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - properties.put("model", request.getModel()); - } + properties.put("model", request.getModel()); properties.put("stream", request.getStream()); - if (request.getPreamble().isPresent()) { - properties.put("preamble", request.getPreamble()); - } - if (request.getChatHistory().isPresent()) { - properties.put("chat_history", request.getChatHistory()); - } - if (request.getConversationId().isPresent()) { - properties.put("conversation_id", request.getConversationId()); - } - if (request.getPromptTruncation().isPresent()) { - properties.put("prompt_truncation", request.getPromptTruncation()); - } - if (request.getConnectors().isPresent()) { - properties.put("connectors", request.getConnectors()); - } - if (request.getSearchQueriesOnly().isPresent()) { - properties.put("search_queries_only", request.getSearchQueriesOnly()); - } - if (request.getDocuments().isPresent()) { - properties.put("documents", request.getDocuments()); - } - if (request.getCitationQuality().isPresent()) { - properties.put("citation_quality", request.getCitationQuality()); - } - if (request.getTemperature().isPresent()) { - properties.put("temperature", request.getTemperature()); - } - if (request.getMaxTokens().isPresent()) { - properties.put("max_tokens", request.getMaxTokens()); - } - if (request.getMaxInputTokens().isPresent()) { - properties.put("max_input_tokens", request.getMaxInputTokens()); - } - if (request.getK().isPresent()) { - properties.put("k", request.getK()); - } - if (request.getP().isPresent()) { - properties.put("p", request.getP()); - } - if (request.getSeed().isPresent()) { - properties.put("seed", request.getSeed()); - } - if (request.getStopSequences().isPresent()) { - properties.put("stop_sequences", request.getStopSequences()); - } - if (request.getFrequencyPenalty().isPresent()) { - properties.put("frequency_penalty", request.getFrequencyPenalty()); - } - if (request.getPresencePenalty().isPresent()) { - properties.put("presence_penalty", request.getPresencePenalty()); - } - if (request.getRawPrompting().isPresent()) { - properties.put("raw_prompting", request.getRawPrompting()); - } - if (request.getTools().isPresent()) { - properties.put("tools", request.getTools()); - } - if (request.getToolResults().isPresent()) { - properties.put("tool_results", request.getToolResults()); - } - if (request.getForceSingleStep().isPresent()) { - properties.put("force_single_step", request.getForceSingleStep()); - } - if (request.getResponseFormat().isPresent()) { - properties.put("response_format", request.getResponseFormat()); - } - if (request.getSafetyMode().isPresent()) { - properties.put("safety_mode", request.getSafetyMode()); - } + properties.put("preamble", request.getPreamble()); + properties.put("chat_history", request.getChatHistory()); + properties.put("conversation_id", request.getConversationId()); + properties.put("prompt_truncation", request.getPromptTruncation()); + properties.put("connectors", request.getConnectors()); + properties.put("search_queries_only", request.getSearchQueriesOnly()); + properties.put("documents", request.getDocuments()); + properties.put("citation_quality", request.getCitationQuality()); + properties.put("temperature", request.getTemperature()); + properties.put("max_tokens", request.getMaxTokens()); + properties.put("max_input_tokens", request.getMaxInputTokens()); + properties.put("k", request.getK()); + properties.put("p", request.getP()); + properties.put("seed", request.getSeed()); + properties.put("stop_sequences", request.getStopSequences()); + properties.put("frequency_penalty", request.getFrequencyPenalty()); + properties.put("presence_penalty", request.getPresencePenalty()); + properties.put("raw_prompting", request.getRawPrompting()); + properties.put("tools", request.getTools()); + properties.put("tool_results", request.getToolResults()); + properties.put("force_single_step", request.getForceSingleStep()); + properties.put("response_format", request.getResponseFormat()); + properties.put("safety_mode", request.getSafetyMode()); RequestBody body; try { body = RequestBody.create( @@ -261,11 +213,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -300,79 +250,31 @@ public CompletableFuture> chat( .build(); Map properties = new HashMap<>(); properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - properties.put("model", request.getModel()); - } + properties.put("model", request.getModel()); properties.put("stream", request.getStream()); - if (request.getPreamble().isPresent()) { - properties.put("preamble", request.getPreamble()); - } - if (request.getChatHistory().isPresent()) { - properties.put("chat_history", request.getChatHistory()); - } - if (request.getConversationId().isPresent()) { - properties.put("conversation_id", request.getConversationId()); - } - if (request.getPromptTruncation().isPresent()) { - properties.put("prompt_truncation", request.getPromptTruncation()); - } - if (request.getConnectors().isPresent()) { - properties.put("connectors", request.getConnectors()); - } - if (request.getSearchQueriesOnly().isPresent()) { - properties.put("search_queries_only", request.getSearchQueriesOnly()); - } - if (request.getDocuments().isPresent()) { - properties.put("documents", request.getDocuments()); - } - if (request.getCitationQuality().isPresent()) { - properties.put("citation_quality", request.getCitationQuality()); - } - if (request.getTemperature().isPresent()) { - properties.put("temperature", request.getTemperature()); - } - if (request.getMaxTokens().isPresent()) { - properties.put("max_tokens", request.getMaxTokens()); - } - if (request.getMaxInputTokens().isPresent()) { - properties.put("max_input_tokens", request.getMaxInputTokens()); - } - if (request.getK().isPresent()) { - properties.put("k", request.getK()); - } - if (request.getP().isPresent()) { - properties.put("p", request.getP()); - } - if (request.getSeed().isPresent()) { - properties.put("seed", request.getSeed()); - } - if (request.getStopSequences().isPresent()) { - properties.put("stop_sequences", request.getStopSequences()); - } - if (request.getFrequencyPenalty().isPresent()) { - properties.put("frequency_penalty", request.getFrequencyPenalty()); - } - if (request.getPresencePenalty().isPresent()) { - properties.put("presence_penalty", request.getPresencePenalty()); - } - if (request.getRawPrompting().isPresent()) { - properties.put("raw_prompting", request.getRawPrompting()); - } - if (request.getTools().isPresent()) { - properties.put("tools", request.getTools()); - } - if (request.getToolResults().isPresent()) { - properties.put("tool_results", request.getToolResults()); - } - if (request.getForceSingleStep().isPresent()) { - properties.put("force_single_step", request.getForceSingleStep()); - } - if (request.getResponseFormat().isPresent()) { - properties.put("response_format", request.getResponseFormat()); - } - if (request.getSafetyMode().isPresent()) { - properties.put("safety_mode", request.getSafetyMode()); - } + properties.put("preamble", request.getPreamble()); + properties.put("chat_history", request.getChatHistory()); + properties.put("conversation_id", request.getConversationId()); + properties.put("prompt_truncation", request.getPromptTruncation()); + properties.put("connectors", request.getConnectors()); + properties.put("search_queries_only", request.getSearchQueriesOnly()); + properties.put("documents", request.getDocuments()); + properties.put("citation_quality", request.getCitationQuality()); + properties.put("temperature", request.getTemperature()); + properties.put("max_tokens", request.getMaxTokens()); + properties.put("max_input_tokens", request.getMaxInputTokens()); + properties.put("k", request.getK()); + properties.put("p", request.getP()); + properties.put("seed", request.getSeed()); + properties.put("stop_sequences", request.getStopSequences()); + properties.put("frequency_penalty", request.getFrequencyPenalty()); + properties.put("presence_penalty", request.getPresencePenalty()); + properties.put("raw_prompting", request.getRawPrompting()); + properties.put("tools", request.getTools()); + properties.put("tool_results", request.getToolResults()); + properties.put("force_single_step", request.getForceSingleStep()); + properties.put("response_format", request.getResponseFormat()); + properties.put("safety_mode", request.getSafetyMode()); RequestBody body; try { body = RequestBody.create( @@ -399,14 +301,13 @@ public CompletableFuture> chat( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), NonStreamedChatResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NonStreamedChatResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -473,11 +374,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -613,11 +512,9 @@ GenerateStreamedResponse.class, new ResponseBodyReader(response), "\\n"), } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -677,13 +574,12 @@ public CompletableFuture> generate( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Generation.class), - response)); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Generation.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -750,11 +646,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -821,13 +715,13 @@ public CompletableFuture> embed( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmbedResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -894,11 +788,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -952,13 +844,13 @@ public CompletableFuture> rerank( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), RerankResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, RerankResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1025,11 +917,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -1085,13 +975,13 @@ public CompletableFuture> classify( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ClassifyResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ClassifyResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1158,11 +1048,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -1222,13 +1110,13 @@ public CompletableFuture> summarize( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SummarizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, SummarizeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1295,11 +1183,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -1353,13 +1239,13 @@ public CompletableFuture> tokenize( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TokenizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TokenizeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1426,11 +1312,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -1484,13 +1368,13 @@ public CompletableFuture> detokenize( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetokenizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetokenizeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1557,11 +1441,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -1606,13 +1488,13 @@ public CompletableFuture> checkApiKey(Re @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckApiKeyResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CheckApiKeyResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1679,11 +1561,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/Cohere.java b/src/main/java/com/cohere/api/Cohere.java index aa2a15e..ee56fd7 100644 --- a/src/main/java/com/cohere/api/Cohere.java +++ b/src/main/java/com/cohere/api/Cohere.java @@ -16,6 +16,7 @@ import com.cohere.api.requests.RerankRequest; import com.cohere.api.requests.SummarizeRequest; import com.cohere.api.requests.TokenizeRequest; +import com.cohere.api.resources.batches.BatchesClient; import com.cohere.api.resources.connectors.ConnectorsClient; import com.cohere.api.resources.datasets.DatasetsClient; import com.cohere.api.resources.embedjobs.EmbedJobsClient; @@ -42,6 +43,8 @@ public class Cohere { protected final Supplier v2Client; + protected final Supplier batchesClient; + protected final Supplier embedJobsClient; protected final Supplier datasetsClient; @@ -56,6 +59,7 @@ public Cohere(ClientOptions clientOptions) { this.clientOptions = clientOptions; this.rawClient = new RawCohere(clientOptions); this.v2Client = Suppliers.memoize(() -> new V2Client(clientOptions)); + this.batchesClient = Suppliers.memoize(() -> new BatchesClient(clientOptions)); this.embedJobsClient = Suppliers.memoize(() -> new EmbedJobsClient(clientOptions)); this.datasetsClient = Suppliers.memoize(() -> new DatasetsClient(clientOptions)); this.connectorsClient = Suppliers.memoize(() -> new ConnectorsClient(clientOptions)); @@ -266,6 +270,10 @@ public V2Client v2() { return this.v2Client.get(); } + public BatchesClient batches() { + return this.batchesClient.get(); + } + public EmbedJobsClient embedJobs() { return this.embedJobsClient.get(); } diff --git a/src/main/java/com/cohere/api/CohereBuilder.java b/src/main/java/com/cohere/api/CohereBuilder.java index 2050387..b1bbff9 100644 --- a/src/main/java/com/cohere/api/CohereBuilder.java +++ b/src/main/java/com/cohere/api/CohereBuilder.java @@ -5,6 +5,8 @@ import com.cohere.api.core.ClientOptions; import com.cohere.api.core.Environment; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import okhttp3.OkHttpClient; @@ -13,6 +15,8 @@ public class CohereBuilder { private Optional maxRetries = Optional.empty(); + private final Map customHeaders = new HashMap<>(); + private String token = System.getenv("CO_API_KEY"); private String clientName = null; @@ -72,6 +76,19 @@ public CohereBuilder httpClient(OkHttpClient httpClient) { return this; } + /** + * Add a custom header to be sent with all requests. + * For headers that need to be computed dynamically or conditionally, use the setAdditional() method override instead. + * + * @param name The header name + * @param value The header value + * @return This builder for method chaining + */ + public CohereBuilder addHeader(String name, String value) { + this.customHeaders.put(name, value); + return this; + } + protected ClientOptions buildClientOptions() { ClientOptions.Builder builder = ClientOptions.builder(); setEnvironment(builder); @@ -80,6 +97,9 @@ protected ClientOptions buildClientOptions() { setHttpClient(builder); setTimeouts(builder); setRetries(builder); + for (Map.Entry header : this.customHeaders.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } setAdditional(builder); return builder.build(); } @@ -209,9 +229,6 @@ protected void setAdditional(ClientOptions.Builder builder) {} protected void validateConfiguration() {} public Cohere build() { - if (token == null) { - throw new RuntimeException("Please provide token or set the CO_API_KEY environment variable."); - } validateConfiguration(); return new Cohere(buildClientOptions()); } diff --git a/src/main/java/com/cohere/api/RawCohere.java b/src/main/java/com/cohere/api/RawCohere.java index 2e43695..7f36061 100644 --- a/src/main/java/com/cohere/api/RawCohere.java +++ b/src/main/java/com/cohere/api/RawCohere.java @@ -84,79 +84,31 @@ public CohereHttpResponse> chatStream( .build(); Map properties = new HashMap<>(); properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - properties.put("model", request.getModel()); - } + properties.put("model", request.getModel()); properties.put("stream", request.getStream()); - if (request.getPreamble().isPresent()) { - properties.put("preamble", request.getPreamble()); - } - if (request.getChatHistory().isPresent()) { - properties.put("chat_history", request.getChatHistory()); - } - if (request.getConversationId().isPresent()) { - properties.put("conversation_id", request.getConversationId()); - } - if (request.getPromptTruncation().isPresent()) { - properties.put("prompt_truncation", request.getPromptTruncation()); - } - if (request.getConnectors().isPresent()) { - properties.put("connectors", request.getConnectors()); - } - if (request.getSearchQueriesOnly().isPresent()) { - properties.put("search_queries_only", request.getSearchQueriesOnly()); - } - if (request.getDocuments().isPresent()) { - properties.put("documents", request.getDocuments()); - } - if (request.getCitationQuality().isPresent()) { - properties.put("citation_quality", request.getCitationQuality()); - } - if (request.getTemperature().isPresent()) { - properties.put("temperature", request.getTemperature()); - } - if (request.getMaxTokens().isPresent()) { - properties.put("max_tokens", request.getMaxTokens()); - } - if (request.getMaxInputTokens().isPresent()) { - properties.put("max_input_tokens", request.getMaxInputTokens()); - } - if (request.getK().isPresent()) { - properties.put("k", request.getK()); - } - if (request.getP().isPresent()) { - properties.put("p", request.getP()); - } - if (request.getSeed().isPresent()) { - properties.put("seed", request.getSeed()); - } - if (request.getStopSequences().isPresent()) { - properties.put("stop_sequences", request.getStopSequences()); - } - if (request.getFrequencyPenalty().isPresent()) { - properties.put("frequency_penalty", request.getFrequencyPenalty()); - } - if (request.getPresencePenalty().isPresent()) { - properties.put("presence_penalty", request.getPresencePenalty()); - } - if (request.getRawPrompting().isPresent()) { - properties.put("raw_prompting", request.getRawPrompting()); - } - if (request.getTools().isPresent()) { - properties.put("tools", request.getTools()); - } - if (request.getToolResults().isPresent()) { - properties.put("tool_results", request.getToolResults()); - } - if (request.getForceSingleStep().isPresent()) { - properties.put("force_single_step", request.getForceSingleStep()); - } - if (request.getResponseFormat().isPresent()) { - properties.put("response_format", request.getResponseFormat()); - } - if (request.getSafetyMode().isPresent()) { - properties.put("safety_mode", request.getSafetyMode()); - } + properties.put("preamble", request.getPreamble()); + properties.put("chat_history", request.getChatHistory()); + properties.put("conversation_id", request.getConversationId()); + properties.put("prompt_truncation", request.getPromptTruncation()); + properties.put("connectors", request.getConnectors()); + properties.put("search_queries_only", request.getSearchQueriesOnly()); + properties.put("documents", request.getDocuments()); + properties.put("citation_quality", request.getCitationQuality()); + properties.put("temperature", request.getTemperature()); + properties.put("max_tokens", request.getMaxTokens()); + properties.put("max_input_tokens", request.getMaxInputTokens()); + properties.put("k", request.getK()); + properties.put("p", request.getP()); + properties.put("seed", request.getSeed()); + properties.put("stop_sequences", request.getStopSequences()); + properties.put("frequency_penalty", request.getFrequencyPenalty()); + properties.put("presence_penalty", request.getPresencePenalty()); + properties.put("raw_prompting", request.getRawPrompting()); + properties.put("tools", request.getTools()); + properties.put("tool_results", request.getToolResults()); + properties.put("force_single_step", request.getForceSingleStep()); + properties.put("response_format", request.getResponseFormat()); + properties.put("safety_mode", request.getSafetyMode()); RequestBody body; try { body = RequestBody.create( @@ -228,11 +180,9 @@ public CohereHttpResponse> chatStream( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -257,79 +207,31 @@ public CohereHttpResponse chat(ChatRequest request, Req .build(); Map properties = new HashMap<>(); properties.put("message", request.getMessage()); - if (request.getModel().isPresent()) { - properties.put("model", request.getModel()); - } + properties.put("model", request.getModel()); properties.put("stream", request.getStream()); - if (request.getPreamble().isPresent()) { - properties.put("preamble", request.getPreamble()); - } - if (request.getChatHistory().isPresent()) { - properties.put("chat_history", request.getChatHistory()); - } - if (request.getConversationId().isPresent()) { - properties.put("conversation_id", request.getConversationId()); - } - if (request.getPromptTruncation().isPresent()) { - properties.put("prompt_truncation", request.getPromptTruncation()); - } - if (request.getConnectors().isPresent()) { - properties.put("connectors", request.getConnectors()); - } - if (request.getSearchQueriesOnly().isPresent()) { - properties.put("search_queries_only", request.getSearchQueriesOnly()); - } - if (request.getDocuments().isPresent()) { - properties.put("documents", request.getDocuments()); - } - if (request.getCitationQuality().isPresent()) { - properties.put("citation_quality", request.getCitationQuality()); - } - if (request.getTemperature().isPresent()) { - properties.put("temperature", request.getTemperature()); - } - if (request.getMaxTokens().isPresent()) { - properties.put("max_tokens", request.getMaxTokens()); - } - if (request.getMaxInputTokens().isPresent()) { - properties.put("max_input_tokens", request.getMaxInputTokens()); - } - if (request.getK().isPresent()) { - properties.put("k", request.getK()); - } - if (request.getP().isPresent()) { - properties.put("p", request.getP()); - } - if (request.getSeed().isPresent()) { - properties.put("seed", request.getSeed()); - } - if (request.getStopSequences().isPresent()) { - properties.put("stop_sequences", request.getStopSequences()); - } - if (request.getFrequencyPenalty().isPresent()) { - properties.put("frequency_penalty", request.getFrequencyPenalty()); - } - if (request.getPresencePenalty().isPresent()) { - properties.put("presence_penalty", request.getPresencePenalty()); - } - if (request.getRawPrompting().isPresent()) { - properties.put("raw_prompting", request.getRawPrompting()); - } - if (request.getTools().isPresent()) { - properties.put("tools", request.getTools()); - } - if (request.getToolResults().isPresent()) { - properties.put("tool_results", request.getToolResults()); - } - if (request.getForceSingleStep().isPresent()) { - properties.put("force_single_step", request.getForceSingleStep()); - } - if (request.getResponseFormat().isPresent()) { - properties.put("response_format", request.getResponseFormat()); - } - if (request.getSafetyMode().isPresent()) { - properties.put("safety_mode", request.getSafetyMode()); - } + properties.put("preamble", request.getPreamble()); + properties.put("chat_history", request.getChatHistory()); + properties.put("conversation_id", request.getConversationId()); + properties.put("prompt_truncation", request.getPromptTruncation()); + properties.put("connectors", request.getConnectors()); + properties.put("search_queries_only", request.getSearchQueriesOnly()); + properties.put("documents", request.getDocuments()); + properties.put("citation_quality", request.getCitationQuality()); + properties.put("temperature", request.getTemperature()); + properties.put("max_tokens", request.getMaxTokens()); + properties.put("max_input_tokens", request.getMaxInputTokens()); + properties.put("k", request.getK()); + properties.put("p", request.getP()); + properties.put("seed", request.getSeed()); + properties.put("stop_sequences", request.getStopSequences()); + properties.put("frequency_penalty", request.getFrequencyPenalty()); + properties.put("presence_penalty", request.getPresencePenalty()); + properties.put("raw_prompting", request.getRawPrompting()); + properties.put("tools", request.getTools()); + properties.put("tool_results", request.getToolResults()); + properties.put("force_single_step", request.getForceSingleStep()); + properties.put("response_format", request.getResponseFormat()); + properties.put("safety_mode", request.getSafetyMode()); RequestBody body; try { body = RequestBody.create( @@ -353,12 +255,12 @@ public CohereHttpResponse chat(ChatRequest request, Req } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), NonStreamedChatResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, NonStreamedChatResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -401,11 +303,9 @@ public CohereHttpResponse chat(ChatRequest request, Req } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -502,11 +402,9 @@ public CohereHttpResponse> generateStream( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -553,11 +451,11 @@ public CohereHttpResponse generate(GenerateRequest request, RequestO } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), Generation.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Generation.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -600,11 +498,9 @@ public CohereHttpResponse generate(GenerateRequest request, RequestO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -658,11 +554,11 @@ public CohereHttpResponse embed(EmbedRequest request, RequestOpti } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmbedResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -705,11 +601,9 @@ public CohereHttpResponse embed(EmbedRequest request, RequestOpti } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -750,11 +644,11 @@ public CohereHttpResponse rerank(RerankRequest request, RequestO } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), RerankResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, RerankResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -797,11 +691,9 @@ public CohereHttpResponse rerank(RerankRequest request, RequestO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -844,11 +736,11 @@ public CohereHttpResponse classify(ClassifyRequest request, Re } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ClassifyResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ClassifyResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -891,11 +783,9 @@ public CohereHttpResponse classify(ClassifyRequest request, Re } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -942,11 +832,11 @@ public CohereHttpResponse summarize(SummarizeRequest request, } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), SummarizeResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, SummarizeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -989,11 +879,9 @@ public CohereHttpResponse summarize(SummarizeRequest request, } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -1034,11 +922,11 @@ public CohereHttpResponse tokenize(TokenizeRequest request, Re } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), TokenizeResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, TokenizeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1081,11 +969,9 @@ public CohereHttpResponse tokenize(TokenizeRequest request, Re } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -1126,11 +1012,11 @@ public CohereHttpResponse detokenize(DetokenizeRequest reque } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DetokenizeResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DetokenizeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1173,11 +1059,9 @@ public CohereHttpResponse detokenize(DetokenizeRequest reque } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -1210,12 +1094,11 @@ public CohereHttpResponse checkApiKey(RequestOptions reques } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckApiKeyResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CheckApiKeyResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -1258,11 +1141,9 @@ public CohereHttpResponse checkApiKey(RequestOptions reques } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/core/ClientOptions.java b/src/main/java/com/cohere/api/core/ClientOptions.java index 07e7379..ee8dd4d 100644 --- a/src/main/java/com/cohere/api/core/ClientOptions.java +++ b/src/main/java/com/cohere/api/core/ClientOptions.java @@ -32,10 +32,10 @@ private ClientOptions( this.headers.putAll(headers); this.headers.putAll(new HashMap() { { - put("User-Agent", "com.cohere:cohere-java/1.8.0"); + put("User-Agent", "com.cohere:cohere-java/1.9.0"); put("X-Fern-Language", "JAVA"); put("X-Fern-SDK-Name", "com.cohere.fern:api-sdk"); - put("X-Fern-SDK-Version", "1.8.0"); + put("X-Fern-SDK-Version", "1.9.0"); } }); this.headerSuppliers = headerSuppliers; diff --git a/src/main/java/com/cohere/api/core/CohereApiException.java b/src/main/java/com/cohere/api/core/CohereApiException.java index 46c8bb9..b0b6a3b 100644 --- a/src/main/java/com/cohere/api/core/CohereApiException.java +++ b/src/main/java/com/cohere/api/core/CohereApiException.java @@ -65,9 +65,9 @@ public Map> headers() { return this.headers; } - @java.lang.Override + @Override public String toString() { - return "CohereApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body - + "}"; + return "CohereApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + + ObjectMappers.stringify(body) + "}"; } } diff --git a/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java b/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java index 62644da..6b92248 100644 --- a/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java +++ b/src/main/java/com/cohere/api/core/NullableNonemptyFilter.java @@ -14,6 +14,9 @@ public boolean equals(Object o) { } private boolean isOptionalEmpty(Object o) { - return o instanceof Optional && !((Optional) o).isPresent(); + if (o instanceof Optional) { + return !((Optional) o).isPresent(); + } + return false; } } diff --git a/src/main/java/com/cohere/api/core/ObjectMappers.java b/src/main/java/com/cohere/api/core/ObjectMappers.java index e4a1b5c..1790e8e 100644 --- a/src/main/java/com/cohere/api/core/ObjectMappers.java +++ b/src/main/java/com/cohere/api/core/ObjectMappers.java @@ -4,6 +4,7 @@ package com.cohere.api.core; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -33,4 +34,12 @@ public static String stringify(Object o) { return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); } } + + public static Object parseErrorBody(String responseBodyString) { + try { + return JSON_MAPPER.readValue(responseBodyString, Object.class); + } catch (JsonProcessingException ignored) { + return responseBodyString; + } + } } diff --git a/src/main/java/com/cohere/api/core/RetryInterceptor.java b/src/main/java/com/cohere/api/core/RetryInterceptor.java index 5b17329..7fa6843 100644 --- a/src/main/java/com/cohere/api/core/RetryInterceptor.java +++ b/src/main/java/com/cohere/api/core/RetryInterceptor.java @@ -5,6 +5,9 @@ import java.io.IOException; import java.time.Duration; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.Optional; import java.util.Random; import okhttp3.Interceptor; @@ -12,7 +15,10 @@ public class RetryInterceptor implements Interceptor { - private static final Duration ONE_SECOND = Duration.ofSeconds(1); + private static final Duration INITIAL_RETRY_DELAY = Duration.ofMillis(1000); + private static final Duration MAX_RETRY_DELAY = Duration.ofMillis(60000); + private static final double JITTER_FACTOR = 0.2; + private final ExponentialBackoff backoff; private final Random random = new Random(); @@ -32,7 +38,7 @@ public Response intercept(Chain chain) throws IOException { } private Response retryChain(Response response, Chain chain) throws IOException { - Optional nextBackoff = this.backoff.nextBackoff(); + Optional nextBackoff = this.backoff.nextBackoff(response); while (nextBackoff.isPresent()) { try { Thread.sleep(nextBackoff.get().toMillis()); @@ -42,7 +48,7 @@ private Response retryChain(Response response, Chain chain) throws IOException { response.close(); response = chain.proceed(chain.request()); if (shouldRetry(response.code())) { - nextBackoff = this.backoff.nextBackoff(); + nextBackoff = this.backoff.nextBackoff(response); } else { return response; } @@ -51,6 +57,102 @@ private Response retryChain(Response response, Chain chain) throws IOException { return response; } + /** + * Calculates the retry delay from response headers, with fallback to exponential backoff. + * Priority: Retry-After > X-RateLimit-Reset > Exponential Backoff + */ + private Duration getRetryDelayFromHeaders(Response response, int retryAttempt) { + // Check for Retry-After header first (RFC 7231), with no jitter + String retryAfter = response.header("Retry-After"); + if (retryAfter != null) { + // Parse as number of seconds... + Optional secondsDelay = tryParseLong(retryAfter) + .map(seconds -> seconds * 1000) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis())) + .map(Duration::ofMillis); + if (secondsDelay.isPresent()) { + return secondsDelay.get(); + } + + // ...or as an HTTP date; both are valid + Optional dateDelay = tryParseHttpDate(retryAfter) + .map(resetTime -> resetTime.toInstant().toEpochMilli() - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis())) + .map(Duration::ofMillis); + if (dateDelay.isPresent()) { + return dateDelay.get(); + } + } + + // Then check for industry-standard X-RateLimit-Reset header, with positive jitter + String rateLimitReset = response.header("X-RateLimit-Reset"); + if (rateLimitReset != null) { + // Assume Unix timestamp in epoch seconds + Optional rateLimitDelay = tryParseLong(rateLimitReset) + .map(resetTimeSeconds -> (resetTimeSeconds * 1000) - System.currentTimeMillis()) + .filter(delayMs -> delayMs > 0) + .map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis())) + .map(this::addPositiveJitter) + .map(Duration::ofMillis); + if (rateLimitDelay.isPresent()) { + return rateLimitDelay.get(); + } + } + + // Fall back to exponential backoff, with symmetric jitter + long baseDelay = INITIAL_RETRY_DELAY.toMillis() * (1L << retryAttempt); // 2^retryAttempt + long cappedDelay = Math.min(baseDelay, MAX_RETRY_DELAY.toMillis()); + return Duration.ofMillis(addSymmetricJitter(cappedDelay)); + } + + /** + * Attempts to parse a string as a long, returning empty Optional on failure. + */ + private Optional tryParseLong(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(Long.parseLong(value)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + } + + /** + * Attempts to parse a string as an HTTP date (RFC 1123), returning empty Optional on failure. + */ + private Optional tryParseHttpDate(String value) { + if (value == null) { + return Optional.empty(); + } + try { + return Optional.of(ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME)); + } catch (DateTimeParseException e) { + return Optional.empty(); + } + } + + /** + * Adds positive jitter (100-120% of original value) to prevent thundering herd. + * Used for X-RateLimit-Reset header delays. + */ + private long addPositiveJitter(long delayMs) { + double jitterMultiplier = 1.0 + (random.nextDouble() * JITTER_FACTOR); + return (long) (delayMs * jitterMultiplier); + } + + /** + * Adds symmetric jitter (90-110% of original value) to prevent thundering herd. + * Used for exponential backoff delays. + */ + private long addSymmetricJitter(long delayMs) { + double jitterMultiplier = 1.0 + ((random.nextDouble() - 0.5) * JITTER_FACTOR); + return (long) (delayMs * jitterMultiplier); + } + private static boolean shouldRetry(int statusCode) { return statusCode == 408 || statusCode == 429 || statusCode >= 500; } @@ -65,14 +167,14 @@ private final class ExponentialBackoff { this.maxNumRetries = maxNumRetries; } - public Optional nextBackoff() { - retryNumber += 1; - if (retryNumber > maxNumRetries) { + public Optional nextBackoff(Response response) { + if (retryNumber >= maxNumRetries) { return Optional.empty(); } - int upperBound = (int) Math.pow(2, retryNumber); - return Optional.of(ONE_SECOND.multipliedBy(random.nextInt(upperBound))); + Duration delay = getRetryDelayFromHeaders(response, retryNumber); + retryNumber += 1; + return Optional.of(delay); } } } diff --git a/src/main/java/com/cohere/api/core/Stream.java b/src/main/java/com/cohere/api/core/Stream.java index 9b1c240..3ee1c8a 100644 --- a/src/main/java/com/cohere/api/core/Stream.java +++ b/src/main/java/com/cohere/api/core/Stream.java @@ -174,8 +174,8 @@ private final class SSEIterator implements Iterator { private T nextItem; private boolean hasNextItem = false; private boolean endOfStream = false; - private StringBuilder buffer = new StringBuilder(); - private boolean prefixSeen = false; + private StringBuilder eventDataBuffer = new StringBuilder(); + private String currentEventType = null; private SSEIterator() { if (sseReader != null && !isStreamClosed()) { @@ -223,39 +223,69 @@ private boolean readNextMessage() { try { while (sseScanner.hasNextLine()) { - String chunk = sseScanner.nextLine(); - buffer.append(chunk).append(NEWLINE); - - int terminatorIndex; - while ((terminatorIndex = buffer.indexOf(messageTerminator)) >= 0) { - String line = buffer.substring(0, terminatorIndex + messageTerminator.length()); - buffer.delete(0, terminatorIndex + messageTerminator.length()); - - line = line.trim(); - if (line.isEmpty()) { - continue; + String line = sseScanner.nextLine(); + + if (line.trim().isEmpty()) { + if (eventDataBuffer.length() > 0) { + try { + nextItem = ObjectMappers.JSON_MAPPER.readValue(eventDataBuffer.toString(), valueType); + hasNextItem = true; + eventDataBuffer.setLength(0); + currentEventType = null; + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse SSE event: " + parseEx.getMessage()); + eventDataBuffer.setLength(0); + currentEventType = null; + continue; + } } + continue; + } - if (!prefixSeen && line.startsWith(DATA_PREFIX)) { - prefixSeen = true; - line = line.substring(DATA_PREFIX.length()).trim(); - } else if (!prefixSeen) { - continue; + if (line.startsWith(DATA_PREFIX)) { + String dataContent = line.substring(DATA_PREFIX.length()); + if (dataContent.startsWith(" ")) { + dataContent = dataContent.substring(1); } - if (streamTerminator != null && line.contains(streamTerminator)) { + if (eventDataBuffer.length() == 0 + && streamTerminator != null + && dataContent.trim().equals(streamTerminator)) { endOfStream = true; return false; } - try { - nextItem = ObjectMappers.JSON_MAPPER.readValue(line, valueType); - hasNextItem = true; - prefixSeen = false; - return true; - } catch (Exception parseEx) { - continue; + if (eventDataBuffer.length() > 0) { + eventDataBuffer.append('\n'); + } + eventDataBuffer.append(dataContent); + } else if (line.startsWith("event:")) { + String eventValue = line.length() > 6 ? line.substring(6) : ""; + if (eventValue.startsWith(" ")) { + eventValue = eventValue.substring(1); } + currentEventType = eventValue; + } else if (line.startsWith("id:")) { + // Event ID field (ignored) + } else if (line.startsWith("retry:")) { + // Retry field (ignored) + } else if (line.startsWith(":")) { + // Comment line (ignored) + } + } + + if (eventDataBuffer.length() > 0) { + try { + nextItem = ObjectMappers.JSON_MAPPER.readValue(eventDataBuffer.toString(), valueType); + hasNextItem = true; + eventDataBuffer.setLength(0); + currentEventType = null; + return true; + } catch (Exception parseEx) { + System.err.println("Failed to parse final SSE event: " + parseEx.getMessage()); + eventDataBuffer.setLength(0); + currentEventType = null; } } diff --git a/src/main/java/com/cohere/api/requests/ChatRequest.java b/src/main/java/com/cohere/api/requests/ChatRequest.java index 487f9c7..0dcbc0d 100644 --- a/src/main/java/com/cohere/api/requests/ChatRequest.java +++ b/src/main/java/com/cohere/api/requests/ChatRequest.java @@ -267,8 +267,8 @@ public Optional>> getDocuments() { } /** - * @return Defaults to "accurate". - *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ * @return Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled". *

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

*/ @JsonProperty("citation_quality") @@ -630,8 +630,8 @@ public interface _FinalStage { _FinalStage documents(List> documents); /** - *

Defaults to "accurate".

- *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

*/ _FinalStage citationQuality(Optional citationQuality); @@ -1280,8 +1280,8 @@ public _FinalStage temperature(Optional temperature) { } /** - *

Defaults to "accurate".

- *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -1292,8 +1292,8 @@ public _FinalStage citationQuality(ChatRequestCitationQuality citationQuality) { } /** - *

Defaults to "accurate".

- *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

*/ @java.lang.Override diff --git a/src/main/java/com/cohere/api/requests/ChatStreamRequest.java b/src/main/java/com/cohere/api/requests/ChatStreamRequest.java index 299342b..292e17a 100644 --- a/src/main/java/com/cohere/api/requests/ChatStreamRequest.java +++ b/src/main/java/com/cohere/api/requests/ChatStreamRequest.java @@ -267,8 +267,8 @@ public Optional>> getDocuments() { } /** - * @return Defaults to "accurate". - *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ * @return Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled". *

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

*/ @JsonProperty("citation_quality") @@ -630,8 +630,8 @@ public interface _FinalStage { _FinalStage documents(List> documents); /** - *

Defaults to "accurate".

- *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

*/ _FinalStage citationQuality(Optional citationQuality); @@ -1280,8 +1280,8 @@ public _FinalStage temperature(Optional temperature) { } /** - *

Defaults to "accurate".

- *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -1292,8 +1292,8 @@ public _FinalStage citationQuality(ChatStreamRequestCitationQuality citationQual } /** - *

Defaults to "accurate".

- *

Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*

Compatible Deployments: Cohere Platform, Azure, AWS Sagemaker/Bedrock, Private Deployments

*/ @java.lang.Override diff --git a/src/main/java/com/cohere/api/requests/ClassifyRequest.java b/src/main/java/com/cohere/api/requests/ClassifyRequest.java index 3dd6207..ff7aebc 100644 --- a/src/main/java/com/cohere/api/requests/ClassifyRequest.java +++ b/src/main/java/com/cohere/api/requests/ClassifyRequest.java @@ -163,7 +163,9 @@ public Builder from(ClassifyRequest other) { @JsonSetter(value = "inputs", nulls = Nulls.SKIP) public Builder inputs(List inputs) { this.inputs.clear(); - this.inputs.addAll(inputs); + if (inputs != null) { + this.inputs.addAll(inputs); + } return this; } @@ -173,7 +175,9 @@ public Builder addInputs(String inputs) { } public Builder addAllInputs(List inputs) { - this.inputs.addAll(inputs); + if (inputs != null) { + this.inputs.addAll(inputs); + } return this; } diff --git a/src/main/java/com/cohere/api/requests/DetokenizeRequest.java b/src/main/java/com/cohere/api/requests/DetokenizeRequest.java index a5111d5..45b2d14 100644 --- a/src/main/java/com/cohere/api/requests/DetokenizeRequest.java +++ b/src/main/java/com/cohere/api/requests/DetokenizeRequest.java @@ -137,7 +137,9 @@ public _FinalStage model(@NotNull String model) { */ @java.lang.Override public _FinalStage addAllTokens(List tokens) { - this.tokens.addAll(tokens); + if (tokens != null) { + this.tokens.addAll(tokens); + } return this; } @@ -158,7 +160,9 @@ public _FinalStage addTokens(Integer tokens) { @JsonSetter(value = "tokens", nulls = Nulls.SKIP) public _FinalStage tokens(List tokens) { this.tokens.clear(); - this.tokens.addAll(tokens); + if (tokens != null) { + this.tokens.addAll(tokens); + } return this; } diff --git a/src/main/java/com/cohere/api/requests/EmbedRequest.java b/src/main/java/com/cohere/api/requests/EmbedRequest.java index 25329ed..e8af641 100644 --- a/src/main/java/com/cohere/api/requests/EmbedRequest.java +++ b/src/main/java/com/cohere/api/requests/EmbedRequest.java @@ -65,7 +65,7 @@ public Optional> getTexts() { /** * @return An array of image data URIs for the model to embed. Maximum number of images per call is 1. - *

The image must be a valid data URI. The image must be in either image/jpeg or image/png format and has a maximum size of 5MB.

+ *

The image must be a valid data URI. The image must be in either image/jpeg, image/png, image/webp, or image/gif format and has a maximum size of 5MB.

*

Images are only supported with Embed v3.0 and newer models.

*/ @JsonProperty("images") @@ -190,7 +190,7 @@ public Builder texts(List texts) { /** *

An array of image data URIs for the model to embed. Maximum number of images per call is 1.

- *

The image must be a valid data URI. The image must be in either image/jpeg or image/png format and has a maximum size of 5MB.

+ *

The image must be a valid data URI. The image must be in either image/jpeg, image/png, image/webp, or image/gif format and has a maximum size of 5MB.

*

Images are only supported with Embed v3.0 and newer models.

*/ @JsonSetter(value = "images", nulls = Nulls.SKIP) diff --git a/src/main/java/com/cohere/api/requests/RerankRequest.java b/src/main/java/com/cohere/api/requests/RerankRequest.java index 5e4c069..46c22ab 100644 --- a/src/main/java/com/cohere/api/requests/RerankRequest.java +++ b/src/main/java/com/cohere/api/requests/RerankRequest.java @@ -366,7 +366,9 @@ public _FinalStage topN(Optional topN) { */ @java.lang.Override public _FinalStage addAllDocuments(List documents) { - this.documents.addAll(documents); + if (documents != null) { + this.documents.addAll(documents); + } return this; } @@ -393,7 +395,9 @@ public _FinalStage addDocuments(RerankRequestDocumentsItem documents) { @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(List documents) { this.documents.clear(); - this.documents.addAll(documents); + if (documents != null) { + this.documents.addAll(documents); + } return this; } diff --git a/src/main/java/com/cohere/api/resources/batches/AsyncBatchesClient.java b/src/main/java/com/cohere/api/resources/batches/AsyncBatchesClient.java new file mode 100644 index 0000000..b425fec --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/AsyncBatchesClient.java @@ -0,0 +1,96 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches; + +import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.RequestOptions; +import com.cohere.api.resources.batches.requests.BatchesListBatchesRequest; +import com.cohere.api.resources.batches.types.Batch; +import com.cohere.api.resources.batches.types.CreateBatchResponse; +import com.cohere.api.resources.batches.types.GetBatchResponse; +import com.cohere.api.resources.batches.types.ListBatchesResponse; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +public class AsyncBatchesClient { + protected final ClientOptions clientOptions; + + private final AsyncRawBatchesClient rawClient; + + public AsyncBatchesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawBatchesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawBatchesClient withRawResponse() { + return this.rawClient; + } + + /** + * List the batches for the current user + */ + public CompletableFuture list() { + return this.rawClient.list().thenApply(response -> response.body()); + } + + /** + * List the batches for the current user + */ + public CompletableFuture list(BatchesListBatchesRequest request) { + return this.rawClient.list(request).thenApply(response -> response.body()); + } + + /** + * List the batches for the current user + */ + public CompletableFuture list( + BatchesListBatchesRequest request, RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CompletableFuture create(Batch request) { + return this.rawClient.create(request).thenApply(response -> response.body()); + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CompletableFuture create(Batch request, RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Retrieves a batch + */ + public CompletableFuture retrieve(String id) { + return this.rawClient.retrieve(id).thenApply(response -> response.body()); + } + + /** + * Retrieves a batch + */ + public CompletableFuture retrieve(String id, RequestOptions requestOptions) { + return this.rawClient.retrieve(id, requestOptions).thenApply(response -> response.body()); + } + + /** + * Cancels an in-progress batch + */ + public CompletableFuture> cancel(String id) { + return this.rawClient.cancel(id).thenApply(response -> response.body()); + } + + /** + * Cancels an in-progress batch + */ + public CompletableFuture> cancel(String id, RequestOptions requestOptions) { + return this.rawClient.cancel(id, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/AsyncRawBatchesClient.java b/src/main/java/com/cohere/api/resources/batches/AsyncRawBatchesClient.java new file mode 100644 index 0000000..7b1d79d --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/AsyncRawBatchesClient.java @@ -0,0 +1,439 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches; + +import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.CohereHttpResponse; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; +import com.cohere.api.core.QueryStringMapper; +import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.resources.batches.requests.BatchesListBatchesRequest; +import com.cohere.api.resources.batches.types.Batch; +import com.cohere.api.resources.batches.types.CreateBatchResponse; +import com.cohere.api.resources.batches.types.GetBatchResponse; +import com.cohere.api.resources.batches.types.ListBatchesResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawBatchesClient { + protected final ClientOptions clientOptions; + + public AsyncRawBatchesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * List the batches for the current user + */ + public CompletableFuture> list() { + return list(BatchesListBatchesRequest.builder().build()); + } + + /** + * List the batches for the current user + */ + public CompletableFuture> list(BatchesListBatchesRequest request) { + return list(request, null); + } + + /** + * List the batches for the current user + */ + public CompletableFuture> list( + BatchesListBatchesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches"); + if (request.getPageSize().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page_size", request.getPageSize().get(), false); + } + if (request.getPageToken().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page_token", request.getPageToken().get(), false); + } + if (request.getOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "order_by", request.getOrderBy().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListBatchesResponse.class), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 503: + future.completeExceptionally(new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CompletableFuture> create(Batch request) { + return create(request, null); + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CompletableFuture> create( + Batch request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateBatchResponse.class), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 503: + future.completeExceptionally(new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Retrieves a batch + */ + public CompletableFuture> retrieve(String id) { + return retrieve(id, null); + } + + /** + * Retrieves a batch + */ + public CompletableFuture> retrieve(String id, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetBatchResponse.class), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 503: + future.completeExceptionally(new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Cancels an in-progress batch + */ + public CompletableFuture>> cancel(String id) { + return cancel(id, null); + } + + /** + * Cancels an in-progress batch + */ + public CompletableFuture>> cancel(String id, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches") + .addPathSegment(id) + .addPathSegments(":cancel") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture>> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + future.complete(new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBodyString, new TypeReference>() {}), + response)); + return; + } + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 403: + future.completeExceptionally(new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 503: + future.completeExceptionally(new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + future.completeExceptionally(new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response)); + return; + } catch (IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/BatchesClient.java b/src/main/java/com/cohere/api/resources/batches/BatchesClient.java new file mode 100644 index 0000000..82f4fd0 --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/BatchesClient.java @@ -0,0 +1,94 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches; + +import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.RequestOptions; +import com.cohere.api.resources.batches.requests.BatchesListBatchesRequest; +import com.cohere.api.resources.batches.types.Batch; +import com.cohere.api.resources.batches.types.CreateBatchResponse; +import com.cohere.api.resources.batches.types.GetBatchResponse; +import com.cohere.api.resources.batches.types.ListBatchesResponse; +import java.util.Map; + +public class BatchesClient { + protected final ClientOptions clientOptions; + + private final RawBatchesClient rawClient; + + public BatchesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawBatchesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawBatchesClient withRawResponse() { + return this.rawClient; + } + + /** + * List the batches for the current user + */ + public ListBatchesResponse list() { + return this.rawClient.list().body(); + } + + /** + * List the batches for the current user + */ + public ListBatchesResponse list(BatchesListBatchesRequest request) { + return this.rawClient.list(request).body(); + } + + /** + * List the batches for the current user + */ + public ListBatchesResponse list(BatchesListBatchesRequest request, RequestOptions requestOptions) { + return this.rawClient.list(request, requestOptions).body(); + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CreateBatchResponse create(Batch request) { + return this.rawClient.create(request).body(); + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CreateBatchResponse create(Batch request, RequestOptions requestOptions) { + return this.rawClient.create(request, requestOptions).body(); + } + + /** + * Retrieves a batch + */ + public GetBatchResponse retrieve(String id) { + return this.rawClient.retrieve(id).body(); + } + + /** + * Retrieves a batch + */ + public GetBatchResponse retrieve(String id, RequestOptions requestOptions) { + return this.rawClient.retrieve(id, requestOptions).body(); + } + + /** + * Cancels an in-progress batch + */ + public Map cancel(String id) { + return this.rawClient.cancel(id).body(); + } + + /** + * Cancels an in-progress batch + */ + public Map cancel(String id, RequestOptions requestOptions) { + return this.rawClient.cancel(id, requestOptions).body(); + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/RawBatchesClient.java b/src/main/java/com/cohere/api/resources/batches/RawBatchesClient.java new file mode 100644 index 0000000..6dfed17 --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/RawBatchesClient.java @@ -0,0 +1,331 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches; + +import com.cohere.api.core.ClientOptions; +import com.cohere.api.core.CohereApiException; +import com.cohere.api.core.CohereException; +import com.cohere.api.core.CohereHttpResponse; +import com.cohere.api.core.MediaTypes; +import com.cohere.api.core.ObjectMappers; +import com.cohere.api.core.QueryStringMapper; +import com.cohere.api.core.RequestOptions; +import com.cohere.api.errors.BadRequestError; +import com.cohere.api.errors.ForbiddenError; +import com.cohere.api.errors.InternalServerError; +import com.cohere.api.errors.NotFoundError; +import com.cohere.api.errors.ServiceUnavailableError; +import com.cohere.api.errors.UnauthorizedError; +import com.cohere.api.resources.batches.requests.BatchesListBatchesRequest; +import com.cohere.api.resources.batches.types.Batch; +import com.cohere.api.resources.batches.types.CreateBatchResponse; +import com.cohere.api.resources.batches.types.GetBatchResponse; +import com.cohere.api.resources.batches.types.ListBatchesResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import java.io.IOException; +import java.util.Map; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawBatchesClient { + protected final ClientOptions clientOptions; + + public RawBatchesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * List the batches for the current user + */ + public CohereHttpResponse list() { + return list(BatchesListBatchesRequest.builder().build()); + } + + /** + * List the batches for the current user + */ + public CohereHttpResponse list(BatchesListBatchesRequest request) { + return list(request, null); + } + + /** + * List the batches for the current user + */ + public CohereHttpResponse list( + BatchesListBatchesRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches"); + if (request.getPageSize().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page_size", request.getPageSize().get(), false); + } + if (request.getPageToken().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "page_token", request.getPageToken().get(), false); + } + if (request.getOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "order_by", request.getOrderBy().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListBatchesResponse.class), response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CohereHttpResponse create(Batch request) { + return create(request, null); + } + + /** + * Creates and executes a batch from an uploaded dataset of requests + */ + public CohereHttpResponse create(Batch request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new CohereException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateBatchResponse.class), response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } + } + + /** + * Retrieves a batch + */ + public CohereHttpResponse retrieve(String id) { + return retrieve(id, null); + } + + /** + * Retrieves a batch + */ + public CohereHttpResponse retrieve(String id, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches") + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetBatchResponse.class), response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } + } + + /** + * Cancels an in-progress batch + */ + public CohereHttpResponse> cancel(String id) { + return cancel(id, null); + } + + /** + * Cancels an in-progress batch + */ + public CohereHttpResponse> cancel(String id, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/batches") + .addPathSegment(id) + .addPathSegments(":cancel") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", RequestBody.create("", null)) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + if (response.isSuccessful()) { + return new CohereHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBodyString, new TypeReference>() {}), + response); + } + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 403: + throw new ForbiddenError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 503: + throw new ServiceUnavailableError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); + throw new CohereApiException( + "Error with status code " + response.code(), response.code(), errorBody, response); + } catch (IOException e) { + throw new CohereException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/requests/BatchesListBatchesRequest.java b/src/main/java/com/cohere/api/resources/batches/requests/BatchesListBatchesRequest.java new file mode 100644 index 0000000..7f1220e --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/requests/BatchesListBatchesRequest.java @@ -0,0 +1,171 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches.requests; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = BatchesListBatchesRequest.Builder.class) +public final class BatchesListBatchesRequest { + private final Optional pageSize; + + private final Optional pageToken; + + private final Optional orderBy; + + private final Map additionalProperties; + + private BatchesListBatchesRequest( + Optional pageSize, + Optional pageToken, + Optional orderBy, + Map additionalProperties) { + this.pageSize = pageSize; + this.pageToken = pageToken; + this.orderBy = orderBy; + this.additionalProperties = additionalProperties; + } + + /** + * @return The maximum number of batches to return. The service may return fewer than + * this value. + * If unspecified, at most 50 batches will be returned. + * The maximum value is 1000; values above 1000 will be coerced to 1000. + */ + @JsonProperty("page_size") + public Optional getPageSize() { + return pageSize; + } + + /** + * @return A page token, received from a previous ListBatches call. + * Provide this to retrieve the subsequent page. + */ + @JsonProperty("page_token") + public Optional getPageToken() { + return pageToken; + } + + /** + * @return Batches can be ordered by creation time or last updated time. + * Use created_at for creation time or updated_at for last updated time. + */ + @JsonProperty("order_by") + public Optional getOrderBy() { + return orderBy; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof BatchesListBatchesRequest && equalTo((BatchesListBatchesRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(BatchesListBatchesRequest other) { + return pageSize.equals(other.pageSize) && pageToken.equals(other.pageToken) && orderBy.equals(other.orderBy); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.pageSize, this.pageToken, this.orderBy); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional pageSize = Optional.empty(); + + private Optional pageToken = Optional.empty(); + + private Optional orderBy = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(BatchesListBatchesRequest other) { + pageSize(other.getPageSize()); + pageToken(other.getPageToken()); + orderBy(other.getOrderBy()); + return this; + } + + /** + *

The maximum number of batches to return. The service may return fewer than + * this value. + * If unspecified, at most 50 batches will be returned. + * The maximum value is 1000; values above 1000 will be coerced to 1000.

+ */ + @JsonSetter(value = "page_size", nulls = Nulls.SKIP) + public Builder pageSize(Optional pageSize) { + this.pageSize = pageSize; + return this; + } + + public Builder pageSize(Integer pageSize) { + this.pageSize = Optional.ofNullable(pageSize); + return this; + } + + /** + *

A page token, received from a previous ListBatches call. + * Provide this to retrieve the subsequent page.

+ */ + @JsonSetter(value = "page_token", nulls = Nulls.SKIP) + public Builder pageToken(Optional pageToken) { + this.pageToken = pageToken; + return this; + } + + public Builder pageToken(String pageToken) { + this.pageToken = Optional.ofNullable(pageToken); + return this; + } + + /** + *

Batches can be ordered by creation time or last updated time. + * Use created_at for creation time or updated_at for last updated time.

+ */ + @JsonSetter(value = "order_by", nulls = Nulls.SKIP) + public Builder orderBy(Optional orderBy) { + this.orderBy = orderBy; + return this; + } + + public Builder orderBy(String orderBy) { + this.orderBy = Optional.ofNullable(orderBy); + return this; + } + + public BatchesListBatchesRequest build() { + return new BatchesListBatchesRequest(pageSize, pageToken, orderBy, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/types/Batch.java b/src/main/java/com/cohere/api/resources/batches/types/Batch.java new file mode 100644 index 0000000..5d53b12 --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/types/Batch.java @@ -0,0 +1,767 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Batch.Builder.class) +public final class Batch { + private final Optional id; + + private final String name; + + private final Optional creatorId; + + private final Optional orgId; + + private final Optional status; + + private final Optional createdAt; + + private final Optional updatedAt; + + private final String inputDatasetId; + + private final Optional outputDatasetId; + + private final Optional inputTokens; + + private final Optional outputTokens; + + private final String model; + + private final Optional numRecords; + + private final Optional numSuccessfulRecords; + + private final Optional numFailedRecords; + + private final Optional statusReason; + + private final Map additionalProperties; + + private Batch( + Optional id, + String name, + Optional creatorId, + Optional orgId, + Optional status, + Optional createdAt, + Optional updatedAt, + String inputDatasetId, + Optional outputDatasetId, + Optional inputTokens, + Optional outputTokens, + String model, + Optional numRecords, + Optional numSuccessfulRecords, + Optional numFailedRecords, + Optional statusReason, + Map additionalProperties) { + this.id = id; + this.name = name; + this.creatorId = creatorId; + this.orgId = orgId; + this.status = status; + this.createdAt = createdAt; + this.updatedAt = updatedAt; + this.inputDatasetId = inputDatasetId; + this.outputDatasetId = outputDatasetId; + this.inputTokens = inputTokens; + this.outputTokens = outputTokens; + this.model = model; + this.numRecords = numRecords; + this.numSuccessfulRecords = numSuccessfulRecords; + this.numFailedRecords = numFailedRecords; + this.statusReason = statusReason; + this.additionalProperties = additionalProperties; + } + + /** + * @return read-only. Batch ID. + */ + @JsonProperty("id") + public Optional getId() { + return id; + } + + /** + * @return Batch name (e.g. foobar). + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * @return read-only. User ID of the creator. + */ + @JsonProperty("creator_id") + public Optional getCreatorId() { + return creatorId; + } + + /** + * @return read-only. Organization ID. + */ + @JsonProperty("org_id") + public Optional getOrgId() { + return orgId; + } + + /** + * @return read-only. Current stage in the life-cycle of the batch. + */ + @JsonProperty("status") + public Optional getStatus() { + return status; + } + + /** + * @return read-only. Creation timestamp. + */ + @JsonProperty("created_at") + public Optional getCreatedAt() { + return createdAt; + } + + /** + * @return read-only. Latest update timestamp. + */ + @JsonProperty("updated_at") + public Optional getUpdatedAt() { + return updatedAt; + } + + /** + * @return ID of the dataset the batch reads inputs from. + */ + @JsonProperty("input_dataset_id") + public String getInputDatasetId() { + return inputDatasetId; + } + + @JsonProperty("output_dataset_id") + public Optional getOutputDatasetId() { + return outputDatasetId; + } + + /** + * @return read-only. The total number of input tokens in the batch. + */ + @JsonProperty("input_tokens") + public Optional getInputTokens() { + return inputTokens; + } + + /** + * @return read-only. The total number of output tokens in the batch. + */ + @JsonProperty("output_tokens") + public Optional getOutputTokens() { + return outputTokens; + } + + /** + * @return The name of the model the batch uses. + */ + @JsonProperty("model") + public String getModel() { + return model; + } + + /** + * @return read-only. The total number of records in the batch. + */ + @JsonProperty("num_records") + public Optional getNumRecords() { + return numRecords; + } + + /** + * @return read-only. The current number of successful records in the batch. + */ + @JsonProperty("num_successful_records") + public Optional getNumSuccessfulRecords() { + return numSuccessfulRecords; + } + + /** + * @return read-only. The current number of failed records in the batch. + */ + @JsonProperty("num_failed_records") + public Optional getNumFailedRecords() { + return numFailedRecords; + } + + /** + * @return read-only. More details about the reason for the status of a batch job. + */ + @JsonProperty("status_reason") + public Optional getStatusReason() { + return statusReason; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Batch && equalTo((Batch) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Batch other) { + return id.equals(other.id) + && name.equals(other.name) + && creatorId.equals(other.creatorId) + && orgId.equals(other.orgId) + && status.equals(other.status) + && createdAt.equals(other.createdAt) + && updatedAt.equals(other.updatedAt) + && inputDatasetId.equals(other.inputDatasetId) + && outputDatasetId.equals(other.outputDatasetId) + && inputTokens.equals(other.inputTokens) + && outputTokens.equals(other.outputTokens) + && model.equals(other.model) + && numRecords.equals(other.numRecords) + && numSuccessfulRecords.equals(other.numSuccessfulRecords) + && numFailedRecords.equals(other.numFailedRecords) + && statusReason.equals(other.statusReason); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.id, + this.name, + this.creatorId, + this.orgId, + this.status, + this.createdAt, + this.updatedAt, + this.inputDatasetId, + this.outputDatasetId, + this.inputTokens, + this.outputTokens, + this.model, + this.numRecords, + this.numSuccessfulRecords, + this.numFailedRecords, + this.statusReason); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static NameStage builder() { + return new Builder(); + } + + public interface NameStage { + /** + *

Batch name (e.g. foobar).

+ */ + InputDatasetIdStage name(@NotNull String name); + + Builder from(Batch other); + } + + public interface InputDatasetIdStage { + /** + *

ID of the dataset the batch reads inputs from.

+ */ + ModelStage inputDatasetId(@NotNull String inputDatasetId); + } + + public interface ModelStage { + /** + *

The name of the model the batch uses.

+ */ + _FinalStage model(@NotNull String model); + } + + public interface _FinalStage { + Batch build(); + + /** + *

read-only. Batch ID.

+ */ + _FinalStage id(Optional id); + + _FinalStage id(String id); + + /** + *

read-only. User ID of the creator.

+ */ + _FinalStage creatorId(Optional creatorId); + + _FinalStage creatorId(String creatorId); + + /** + *

read-only. Organization ID.

+ */ + _FinalStage orgId(Optional orgId); + + _FinalStage orgId(String orgId); + + /** + *

read-only. Current stage in the life-cycle of the batch.

+ */ + _FinalStage status(Optional status); + + _FinalStage status(BatchStatus status); + + /** + *

read-only. Creation timestamp.

+ */ + _FinalStage createdAt(Optional createdAt); + + _FinalStage createdAt(OffsetDateTime createdAt); + + /** + *

read-only. Latest update timestamp.

+ */ + _FinalStage updatedAt(Optional updatedAt); + + _FinalStage updatedAt(OffsetDateTime updatedAt); + + _FinalStage outputDatasetId(Optional outputDatasetId); + + _FinalStage outputDatasetId(String outputDatasetId); + + /** + *

read-only. The total number of input tokens in the batch.

+ */ + _FinalStage inputTokens(Optional inputTokens); + + _FinalStage inputTokens(String inputTokens); + + /** + *

read-only. The total number of output tokens in the batch.

+ */ + _FinalStage outputTokens(Optional outputTokens); + + _FinalStage outputTokens(String outputTokens); + + /** + *

read-only. The total number of records in the batch.

+ */ + _FinalStage numRecords(Optional numRecords); + + _FinalStage numRecords(Integer numRecords); + + /** + *

read-only. The current number of successful records in the batch.

+ */ + _FinalStage numSuccessfulRecords(Optional numSuccessfulRecords); + + _FinalStage numSuccessfulRecords(Integer numSuccessfulRecords); + + /** + *

read-only. The current number of failed records in the batch.

+ */ + _FinalStage numFailedRecords(Optional numFailedRecords); + + _FinalStage numFailedRecords(Integer numFailedRecords); + + /** + *

read-only. More details about the reason for the status of a batch job.

+ */ + _FinalStage statusReason(Optional statusReason); + + _FinalStage statusReason(String statusReason); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements NameStage, InputDatasetIdStage, ModelStage, _FinalStage { + private String name; + + private String inputDatasetId; + + private String model; + + private Optional statusReason = Optional.empty(); + + private Optional numFailedRecords = Optional.empty(); + + private Optional numSuccessfulRecords = Optional.empty(); + + private Optional numRecords = Optional.empty(); + + private Optional outputTokens = Optional.empty(); + + private Optional inputTokens = Optional.empty(); + + private Optional outputDatasetId = Optional.empty(); + + private Optional updatedAt = Optional.empty(); + + private Optional createdAt = Optional.empty(); + + private Optional status = Optional.empty(); + + private Optional orgId = Optional.empty(); + + private Optional creatorId = Optional.empty(); + + private Optional id = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(Batch other) { + id(other.getId()); + name(other.getName()); + creatorId(other.getCreatorId()); + orgId(other.getOrgId()); + status(other.getStatus()); + createdAt(other.getCreatedAt()); + updatedAt(other.getUpdatedAt()); + inputDatasetId(other.getInputDatasetId()); + outputDatasetId(other.getOutputDatasetId()); + inputTokens(other.getInputTokens()); + outputTokens(other.getOutputTokens()); + model(other.getModel()); + numRecords(other.getNumRecords()); + numSuccessfulRecords(other.getNumSuccessfulRecords()); + numFailedRecords(other.getNumFailedRecords()); + statusReason(other.getStatusReason()); + return this; + } + + /** + *

Batch name (e.g. foobar).

+ *

Batch name (e.g. foobar).

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("name") + public InputDatasetIdStage name(@NotNull String name) { + this.name = Objects.requireNonNull(name, "name must not be null"); + return this; + } + + /** + *

ID of the dataset the batch reads inputs from.

+ *

ID of the dataset the batch reads inputs from.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("input_dataset_id") + public ModelStage inputDatasetId(@NotNull String inputDatasetId) { + this.inputDatasetId = Objects.requireNonNull(inputDatasetId, "inputDatasetId must not be null"); + return this; + } + + /** + *

The name of the model the batch uses.

+ *

The name of the model the batch uses.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("model") + public _FinalStage model(@NotNull String model) { + this.model = Objects.requireNonNull(model, "model must not be null"); + return this; + } + + /** + *

read-only. More details about the reason for the status of a batch job.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage statusReason(String statusReason) { + this.statusReason = Optional.ofNullable(statusReason); + return this; + } + + /** + *

read-only. More details about the reason for the status of a batch job.

+ */ + @java.lang.Override + @JsonSetter(value = "status_reason", nulls = Nulls.SKIP) + public _FinalStage statusReason(Optional statusReason) { + this.statusReason = statusReason; + return this; + } + + /** + *

read-only. The current number of failed records in the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage numFailedRecords(Integer numFailedRecords) { + this.numFailedRecords = Optional.ofNullable(numFailedRecords); + return this; + } + + /** + *

read-only. The current number of failed records in the batch.

+ */ + @java.lang.Override + @JsonSetter(value = "num_failed_records", nulls = Nulls.SKIP) + public _FinalStage numFailedRecords(Optional numFailedRecords) { + this.numFailedRecords = numFailedRecords; + return this; + } + + /** + *

read-only. The current number of successful records in the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage numSuccessfulRecords(Integer numSuccessfulRecords) { + this.numSuccessfulRecords = Optional.ofNullable(numSuccessfulRecords); + return this; + } + + /** + *

read-only. The current number of successful records in the batch.

+ */ + @java.lang.Override + @JsonSetter(value = "num_successful_records", nulls = Nulls.SKIP) + public _FinalStage numSuccessfulRecords(Optional numSuccessfulRecords) { + this.numSuccessfulRecords = numSuccessfulRecords; + return this; + } + + /** + *

read-only. The total number of records in the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage numRecords(Integer numRecords) { + this.numRecords = Optional.ofNullable(numRecords); + return this; + } + + /** + *

read-only. The total number of records in the batch.

+ */ + @java.lang.Override + @JsonSetter(value = "num_records", nulls = Nulls.SKIP) + public _FinalStage numRecords(Optional numRecords) { + this.numRecords = numRecords; + return this; + } + + /** + *

read-only. The total number of output tokens in the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputTokens(String outputTokens) { + this.outputTokens = Optional.ofNullable(outputTokens); + return this; + } + + /** + *

read-only. The total number of output tokens in the batch.

+ */ + @java.lang.Override + @JsonSetter(value = "output_tokens", nulls = Nulls.SKIP) + public _FinalStage outputTokens(Optional outputTokens) { + this.outputTokens = outputTokens; + return this; + } + + /** + *

read-only. The total number of input tokens in the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage inputTokens(String inputTokens) { + this.inputTokens = Optional.ofNullable(inputTokens); + return this; + } + + /** + *

read-only. The total number of input tokens in the batch.

+ */ + @java.lang.Override + @JsonSetter(value = "input_tokens", nulls = Nulls.SKIP) + public _FinalStage inputTokens(Optional inputTokens) { + this.inputTokens = inputTokens; + return this; + } + + @java.lang.Override + public _FinalStage outputDatasetId(String outputDatasetId) { + this.outputDatasetId = Optional.ofNullable(outputDatasetId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "output_dataset_id", nulls = Nulls.SKIP) + public _FinalStage outputDatasetId(Optional outputDatasetId) { + this.outputDatasetId = outputDatasetId; + return this; + } + + /** + *

read-only. Latest update timestamp.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage updatedAt(OffsetDateTime updatedAt) { + this.updatedAt = Optional.ofNullable(updatedAt); + return this; + } + + /** + *

read-only. Latest update timestamp.

+ */ + @java.lang.Override + @JsonSetter(value = "updated_at", nulls = Nulls.SKIP) + public _FinalStage updatedAt(Optional updatedAt) { + this.updatedAt = updatedAt; + return this; + } + + /** + *

read-only. Creation timestamp.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage createdAt(OffsetDateTime createdAt) { + this.createdAt = Optional.ofNullable(createdAt); + return this; + } + + /** + *

read-only. Creation timestamp.

+ */ + @java.lang.Override + @JsonSetter(value = "created_at", nulls = Nulls.SKIP) + public _FinalStage createdAt(Optional createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + *

read-only. Current stage in the life-cycle of the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage status(BatchStatus status) { + this.status = Optional.ofNullable(status); + return this; + } + + /** + *

read-only. Current stage in the life-cycle of the batch.

+ */ + @java.lang.Override + @JsonSetter(value = "status", nulls = Nulls.SKIP) + public _FinalStage status(Optional status) { + this.status = status; + return this; + } + + /** + *

read-only. Organization ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage orgId(String orgId) { + this.orgId = Optional.ofNullable(orgId); + return this; + } + + /** + *

read-only. Organization ID.

+ */ + @java.lang.Override + @JsonSetter(value = "org_id", nulls = Nulls.SKIP) + public _FinalStage orgId(Optional orgId) { + this.orgId = orgId; + return this; + } + + /** + *

read-only. User ID of the creator.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage creatorId(String creatorId) { + this.creatorId = Optional.ofNullable(creatorId); + return this; + } + + /** + *

read-only. User ID of the creator.

+ */ + @java.lang.Override + @JsonSetter(value = "creator_id", nulls = Nulls.SKIP) + public _FinalStage creatorId(Optional creatorId) { + this.creatorId = creatorId; + return this; + } + + /** + *

read-only. Batch ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage id(String id) { + this.id = Optional.ofNullable(id); + return this; + } + + /** + *

read-only. Batch ID.

+ */ + @java.lang.Override + @JsonSetter(value = "id", nulls = Nulls.SKIP) + public _FinalStage id(Optional id) { + this.id = id; + return this; + } + + @java.lang.Override + public Batch build() { + return new Batch( + id, + name, + creatorId, + orgId, + status, + createdAt, + updatedAt, + inputDatasetId, + outputDatasetId, + inputTokens, + outputTokens, + model, + numRecords, + numSuccessfulRecords, + numFailedRecords, + statusReason, + additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/types/BatchStatus.java b/src/main/java/com/cohere/api/resources/batches/types/BatchStatus.java new file mode 100644 index 0000000..5688c1c --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/types/BatchStatus.java @@ -0,0 +1,139 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches.types; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public final class BatchStatus { + public static final BatchStatus BATCH_STATUS_QUEUED = + new BatchStatus(Value.BATCH_STATUS_QUEUED, "BATCH_STATUS_QUEUED"); + + public static final BatchStatus BATCH_STATUS_IN_PROGRESS = + new BatchStatus(Value.BATCH_STATUS_IN_PROGRESS, "BATCH_STATUS_IN_PROGRESS"); + + public static final BatchStatus BATCH_STATUS_UNSPECIFIED = + new BatchStatus(Value.BATCH_STATUS_UNSPECIFIED, "BATCH_STATUS_UNSPECIFIED"); + + public static final BatchStatus BATCH_STATUS_FAILED = + new BatchStatus(Value.BATCH_STATUS_FAILED, "BATCH_STATUS_FAILED"); + + public static final BatchStatus BATCH_STATUS_CANCELING = + new BatchStatus(Value.BATCH_STATUS_CANCELING, "BATCH_STATUS_CANCELING"); + + public static final BatchStatus BATCH_STATUS_CANCELED = + new BatchStatus(Value.BATCH_STATUS_CANCELED, "BATCH_STATUS_CANCELED"); + + public static final BatchStatus BATCH_STATUS_COMPLETED = + new BatchStatus(Value.BATCH_STATUS_COMPLETED, "BATCH_STATUS_COMPLETED"); + + private final Value value; + + private final String string; + + BatchStatus(Value value, String string) { + this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; + } + + @java.lang.Override + @JsonValue + public String toString() { + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof BatchStatus && this.string.equals(((BatchStatus) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BATCH_STATUS_QUEUED: + return visitor.visitBatchStatusQueued(); + case BATCH_STATUS_IN_PROGRESS: + return visitor.visitBatchStatusInProgress(); + case BATCH_STATUS_UNSPECIFIED: + return visitor.visitBatchStatusUnspecified(); + case BATCH_STATUS_FAILED: + return visitor.visitBatchStatusFailed(); + case BATCH_STATUS_CANCELING: + return visitor.visitBatchStatusCanceling(); + case BATCH_STATUS_CANCELED: + return visitor.visitBatchStatusCanceled(); + case BATCH_STATUS_COMPLETED: + return visitor.visitBatchStatusCompleted(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static BatchStatus valueOf(String value) { + switch (value) { + case "BATCH_STATUS_QUEUED": + return BATCH_STATUS_QUEUED; + case "BATCH_STATUS_IN_PROGRESS": + return BATCH_STATUS_IN_PROGRESS; + case "BATCH_STATUS_UNSPECIFIED": + return BATCH_STATUS_UNSPECIFIED; + case "BATCH_STATUS_FAILED": + return BATCH_STATUS_FAILED; + case "BATCH_STATUS_CANCELING": + return BATCH_STATUS_CANCELING; + case "BATCH_STATUS_CANCELED": + return BATCH_STATUS_CANCELED; + case "BATCH_STATUS_COMPLETED": + return BATCH_STATUS_COMPLETED; + default: + return new BatchStatus(Value.UNKNOWN, value); + } + } + + public enum Value { + BATCH_STATUS_UNSPECIFIED, + + BATCH_STATUS_QUEUED, + + BATCH_STATUS_IN_PROGRESS, + + BATCH_STATUS_CANCELING, + + BATCH_STATUS_COMPLETED, + + BATCH_STATUS_FAILED, + + BATCH_STATUS_CANCELED, + + UNKNOWN + } + + public interface Visitor { + T visitBatchStatusUnspecified(); + + T visitBatchStatusQueued(); + + T visitBatchStatusInProgress(); + + T visitBatchStatusCanceling(); + + T visitBatchStatusCompleted(); + + T visitBatchStatusFailed(); + + T visitBatchStatusCanceled(); + + T visitUnknown(String unknownType); + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/types/CreateBatchResponse.java b/src/main/java/com/cohere/api/resources/batches/types/CreateBatchResponse.java new file mode 100644 index 0000000..6ace36c --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/types/CreateBatchResponse.java @@ -0,0 +1,113 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = CreateBatchResponse.Builder.class) +public final class CreateBatchResponse { + private final Batch batch; + + private final Map additionalProperties; + + private CreateBatchResponse(Batch batch, Map additionalProperties) { + this.batch = batch; + this.additionalProperties = additionalProperties; + } + + /** + * @return Information about the batch. + */ + @JsonProperty("batch") + public Batch getBatch() { + return batch; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CreateBatchResponse && equalTo((CreateBatchResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(CreateBatchResponse other) { + return batch.equals(other.batch); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.batch); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static BatchStage builder() { + return new Builder(); + } + + public interface BatchStage { + /** + *

Information about the batch.

+ */ + _FinalStage batch(@NotNull Batch batch); + + Builder from(CreateBatchResponse other); + } + + public interface _FinalStage { + CreateBatchResponse build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements BatchStage, _FinalStage { + private Batch batch; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(CreateBatchResponse other) { + batch(other.getBatch()); + return this; + } + + /** + *

Information about the batch.

+ *

Information about the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("batch") + public _FinalStage batch(@NotNull Batch batch) { + this.batch = Objects.requireNonNull(batch, "batch must not be null"); + return this; + } + + @java.lang.Override + public CreateBatchResponse build() { + return new CreateBatchResponse(batch, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/types/GetBatchResponse.java b/src/main/java/com/cohere/api/resources/batches/types/GetBatchResponse.java new file mode 100644 index 0000000..a2cfed9 --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/types/GetBatchResponse.java @@ -0,0 +1,113 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetBatchResponse.Builder.class) +public final class GetBatchResponse { + private final Batch batch; + + private final Map additionalProperties; + + private GetBatchResponse(Batch batch, Map additionalProperties) { + this.batch = batch; + this.additionalProperties = additionalProperties; + } + + /** + * @return Information about the batch. + */ + @JsonProperty("batch") + public Batch getBatch() { + return batch; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetBatchResponse && equalTo((GetBatchResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetBatchResponse other) { + return batch.equals(other.batch); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.batch); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static BatchStage builder() { + return new Builder(); + } + + public interface BatchStage { + /** + *

Information about the batch.

+ */ + _FinalStage batch(@NotNull Batch batch); + + Builder from(GetBatchResponse other); + } + + public interface _FinalStage { + GetBatchResponse build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements BatchStage, _FinalStage { + private Batch batch; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetBatchResponse other) { + batch(other.getBatch()); + return this; + } + + /** + *

Information about the batch.

+ *

Information about the batch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("batch") + public _FinalStage batch(@NotNull Batch batch) { + this.batch = Objects.requireNonNull(batch, "batch must not be null"); + return this; + } + + @java.lang.Override + public GetBatchResponse build() { + return new GetBatchResponse(batch, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/batches/types/ListBatchesResponse.java b/src/main/java/com/cohere/api/resources/batches/types/ListBatchesResponse.java new file mode 100644 index 0000000..bb265ac --- /dev/null +++ b/src/main/java/com/cohere/api/resources/batches/types/ListBatchesResponse.java @@ -0,0 +1,133 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.cohere.api.resources.batches.types; + +import com.cohere.api.core.ObjectMappers; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ListBatchesResponse.Builder.class) +public final class ListBatchesResponse { + private final Optional> batches; + + private final Optional nextPageToken; + + private final Map additionalProperties; + + private ListBatchesResponse( + Optional> batches, Optional nextPageToken, Map additionalProperties) { + this.batches = batches; + this.nextPageToken = nextPageToken; + this.additionalProperties = additionalProperties; + } + + /** + * @return The batches that belong to the authenticated user. + */ + @JsonProperty("batches") + public Optional> getBatches() { + return batches; + } + + /** + * @return A token, which can be sent as page_token to retrieve the next page. + * If this field is omitted, there are no subsequent pages. + */ + @JsonProperty("next_page_token") + public Optional getNextPageToken() { + return nextPageToken; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ListBatchesResponse && equalTo((ListBatchesResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ListBatchesResponse other) { + return batches.equals(other.batches) && nextPageToken.equals(other.nextPageToken); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.batches, this.nextPageToken); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> batches = Optional.empty(); + + private Optional nextPageToken = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ListBatchesResponse other) { + batches(other.getBatches()); + nextPageToken(other.getNextPageToken()); + return this; + } + + /** + *

The batches that belong to the authenticated user.

+ */ + @JsonSetter(value = "batches", nulls = Nulls.SKIP) + public Builder batches(Optional> batches) { + this.batches = batches; + return this; + } + + public Builder batches(List batches) { + this.batches = Optional.ofNullable(batches); + return this; + } + + /** + *

A token, which can be sent as page_token to retrieve the next page. + * If this field is omitted, there are no subsequent pages.

+ */ + @JsonSetter(value = "next_page_token", nulls = Nulls.SKIP) + public Builder nextPageToken(Optional nextPageToken) { + this.nextPageToken = nextPageToken; + return this; + } + + public Builder nextPageToken(String nextPageToken) { + this.nextPageToken = Optional.ofNullable(nextPageToken); + return this; + } + + public ListBatchesResponse build() { + return new ListBatchesResponse(batches, nextPageToken, additionalProperties); + } + } +} diff --git a/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java b/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java index e634341..6476616 100644 --- a/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java +++ b/src/main/java/com/cohere/api/resources/connectors/AsyncRawConnectorsClient.java @@ -100,14 +100,13 @@ public CompletableFuture> list( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListConnectorsResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListConnectorsResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -174,11 +173,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -232,14 +229,13 @@ public CompletableFuture> create( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CreateConnectorResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateConnectorResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -306,11 +302,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -356,13 +350,13 @@ public CompletableFuture> get(String id @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetConnectorResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetConnectorResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -429,11 +423,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -479,14 +471,14 @@ public CompletableFuture>> delete(String @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), + responseBodyString, new TypeReference>() {}), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -553,11 +545,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -620,14 +610,13 @@ public CompletableFuture> update( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), UpdateConnectorResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UpdateConnectorResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -694,11 +683,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -737,7 +724,8 @@ public CompletableFuture> oAuthAuthor .newBuilder() .addPathSegments("v1/connectors") .addPathSegment(id) - .addPathSegments("oauth/authorize"); + .addPathSegments("oauth") + .addPathSegments("authorize"); if (request.getAfterTokenRedirect().isPresent()) { QueryStringMapper.addQueryParameter( httpUrl, @@ -760,14 +748,13 @@ public CompletableFuture> oAuthAuthor @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), OAuthAuthorizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OAuthAuthorizeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -834,11 +821,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/resources/connectors/RawConnectorsClient.java b/src/main/java/com/cohere/api/resources/connectors/RawConnectorsClient.java index 2a23506..1f4c18e 100644 --- a/src/main/java/com/cohere/api/resources/connectors/RawConnectorsClient.java +++ b/src/main/java/com/cohere/api/resources/connectors/RawConnectorsClient.java @@ -93,12 +93,12 @@ public CohereHttpResponse list( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListConnectorsResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListConnectorsResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -141,11 +141,9 @@ public CohereHttpResponse list( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -187,12 +185,12 @@ public CohereHttpResponse create( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateConnectorResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateConnectorResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -235,11 +233,9 @@ public CohereHttpResponse create( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -273,12 +269,11 @@ public CohereHttpResponse get(String id, RequestOptions re } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetConnectorResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetConnectorResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -321,11 +316,9 @@ public CohereHttpResponse get(String id, RequestOptions re } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -359,13 +352,13 @@ public CohereHttpResponse> delete(String id, RequestOptions } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), + responseBodyString, new TypeReference>() {}), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -408,11 +401,9 @@ public CohereHttpResponse> delete(String id, RequestOptions } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -462,12 +453,12 @@ public CohereHttpResponse update( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UpdateConnectorResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UpdateConnectorResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -510,11 +501,9 @@ public CohereHttpResponse update( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -544,7 +533,8 @@ public CohereHttpResponse oAuthAuthorize( .newBuilder() .addPathSegments("v1/connectors") .addPathSegment(id) - .addPathSegments("oauth/authorize"); + .addPathSegments("oauth") + .addPathSegments("authorize"); if (request.getAfterTokenRedirect().isPresent()) { QueryStringMapper.addQueryParameter( httpUrl, @@ -564,12 +554,12 @@ public CohereHttpResponse oAuthAuthorize( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), OAuthAuthorizeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, OAuthAuthorizeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -612,11 +602,9 @@ public CohereHttpResponse oAuthAuthorize( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java b/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java index 7ad14e7..71ea815 100644 --- a/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java +++ b/src/main/java/com/cohere/api/resources/datasets/AsyncRawDatasetsClient.java @@ -117,13 +117,13 @@ public CompletableFuture> list( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsListResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsListResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -190,11 +190,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -286,14 +284,13 @@ public CompletableFuture> create( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DatasetsCreateResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsCreateResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -360,11 +357,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -409,14 +404,13 @@ public CompletableFuture> getUsage( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), DatasetsGetUsageResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsGetUsageResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -483,11 +477,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -533,13 +525,13 @@ public CompletableFuture> get(String id, @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsGetResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -606,11 +598,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -656,14 +646,14 @@ public CompletableFuture>> delete(String @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), + responseBodyString, new TypeReference>() {}), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -730,11 +720,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/resources/datasets/RawDatasetsClient.java b/src/main/java/com/cohere/api/resources/datasets/RawDatasetsClient.java index 382f180..7fe0b85 100644 --- a/src/main/java/com/cohere/api/resources/datasets/RawDatasetsClient.java +++ b/src/main/java/com/cohere/api/resources/datasets/RawDatasetsClient.java @@ -109,12 +109,11 @@ public CohereHttpResponse list(DatasetsListRequest request } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsListResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsListResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -157,11 +156,9 @@ public CohereHttpResponse list(DatasetsListRequest request } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -241,12 +238,12 @@ public CohereHttpResponse create( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsCreateResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsCreateResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -289,11 +286,9 @@ public CohereHttpResponse create( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -326,12 +321,12 @@ public CohereHttpResponse getUsage(RequestOptions requ } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetUsageResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsGetUsageResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -374,11 +369,9 @@ public CohereHttpResponse getUsage(RequestOptions requ } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -412,12 +405,11 @@ public CohereHttpResponse get(String id, RequestOptions req } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DatasetsGetResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, DatasetsGetResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -460,11 +452,9 @@ public CohereHttpResponse get(String id, RequestOptions req } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -498,13 +488,13 @@ public CohereHttpResponse> delete(String id, RequestOptions } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), + responseBodyString, new TypeReference>() {}), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -547,11 +537,9 @@ public CohereHttpResponse> delete(String id, RequestOptions } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java b/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java index fda96a8..882a935 100644 --- a/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java +++ b/src/main/java/com/cohere/api/resources/datasets/requests/DatasetsCreateRequest.java @@ -88,7 +88,7 @@ public String getName() { } /** - * @return The dataset type, which is used to validate the data. Valid types are embed-input, reranker-finetune-input, single-label-classification-finetune-input, chat-finetune-input, and multi-label-classification-finetune-input. + * @return The dataset type, which is used to validate the data. The only valid type is embed-input used in conjunction with the Embed Jobs API. */ @JsonProperty("type") public DatasetType getType() { @@ -182,7 +182,7 @@ public interface NameStage { public interface TypeStage { /** - *

The dataset type, which is used to validate the data. Valid types are embed-input, reranker-finetune-input, single-label-classification-finetune-input, chat-finetune-input, and multi-label-classification-finetune-input.

+ *

The dataset type, which is used to validate the data. The only valid type is embed-input used in conjunction with the Embed Jobs API.

*/ _FinalStage type(@NotNull DatasetType type); } @@ -286,8 +286,8 @@ public TypeStage name(@NotNull String name) { } /** - *

The dataset type, which is used to validate the data. Valid types are embed-input, reranker-finetune-input, single-label-classification-finetune-input, chat-finetune-input, and multi-label-classification-finetune-input.

- *

The dataset type, which is used to validate the data. Valid types are embed-input, reranker-finetune-input, single-label-classification-finetune-input, chat-finetune-input, and multi-label-classification-finetune-input.

+ *

The dataset type, which is used to validate the data. The only valid type is embed-input used in conjunction with the Embed Jobs API.

+ *

The dataset type, which is used to validate the data. The only valid type is embed-input used in conjunction with the Embed Jobs API.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override diff --git a/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java b/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java index eb7a551..0587ef9 100644 --- a/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java +++ b/src/main/java/com/cohere/api/resources/embedjobs/AsyncRawEmbedJobsClient.java @@ -77,13 +77,13 @@ public CompletableFuture> list(RequestO @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEmbedJobResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListEmbedJobResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -150,11 +150,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -208,14 +206,13 @@ public CompletableFuture> create( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CreateEmbedJobResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateEmbedJobResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -282,11 +279,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -332,12 +327,12 @@ public CompletableFuture> get(String id, RequestOpt @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedJob.class), response)); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmbedJob.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -404,11 +399,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -526,11 +519,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/resources/embedjobs/RawEmbedJobsClient.java b/src/main/java/com/cohere/api/resources/embedjobs/RawEmbedJobsClient.java index cecf37f..11de558 100644 --- a/src/main/java/com/cohere/api/resources/embedjobs/RawEmbedJobsClient.java +++ b/src/main/java/com/cohere/api/resources/embedjobs/RawEmbedJobsClient.java @@ -70,12 +70,11 @@ public CohereHttpResponse list(RequestOptions requestOptio } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEmbedJobResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListEmbedJobResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -118,11 +117,9 @@ public CohereHttpResponse list(RequestOptions requestOptio } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -164,12 +161,12 @@ public CohereHttpResponse create( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateEmbedJobResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateEmbedJobResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -212,11 +209,9 @@ public CohereHttpResponse create( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -250,11 +245,11 @@ public CohereHttpResponse get(String id, RequestOptions requestOptions } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedJob.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmbedJob.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -297,11 +292,9 @@ public CohereHttpResponse get(String id, RequestOptions requestOptions } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -382,11 +375,9 @@ public CohereHttpResponse cancel(String id, RequestOptions requestOptions) } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/resources/embedjobs/types/CreateEmbedJobRequestTruncate.java b/src/main/java/com/cohere/api/resources/embedjobs/types/CreateEmbedJobRequestTruncate.java index 1c63e90..ea57863 100644 --- a/src/main/java/com/cohere/api/resources/embedjobs/types/CreateEmbedJobRequestTruncate.java +++ b/src/main/java/com/cohere/api/resources/embedjobs/types/CreateEmbedJobRequestTruncate.java @@ -3,22 +3,82 @@ */ package com.cohere.api.resources.embedjobs.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum CreateEmbedJobRequestTruncate { - START("START"), +public final class CreateEmbedJobRequestTruncate { + public static final CreateEmbedJobRequestTruncate END = new CreateEmbedJobRequestTruncate(Value.END, "END"); - END("END"); + public static final CreateEmbedJobRequestTruncate START = new CreateEmbedJobRequestTruncate(Value.START, "START"); - private final String value; + private final Value value; - CreateEmbedJobRequestTruncate(String value) { + private final String string; + + CreateEmbedJobRequestTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof CreateEmbedJobRequestTruncate + && this.string.equals(((CreateEmbedJobRequestTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static CreateEmbedJobRequestTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "START": + return START; + default: + return new CreateEmbedJobRequestTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java b/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java index 2f1e153..f8531b6 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java +++ b/src/main/java/com/cohere/api/resources/finetuning/AsyncRawFinetuningClient.java @@ -102,14 +102,14 @@ public CompletableFuture> listFi @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListFinetunedModelsResponse.class), + responseBodyString, ListFinetunedModelsResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -146,11 +146,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -205,14 +203,14 @@ public CompletableFuture> creat @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), CreateFinetunedModelResponse.class), + responseBodyString, CreateFinetunedModelResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -249,11 +247,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -300,14 +296,14 @@ public CompletableFuture> getFinet @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), GetFinetunedModelResponse.class), + responseBodyString, GetFinetunedModelResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -344,11 +340,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -397,14 +391,14 @@ public CompletableFuture>> deleteFinetune @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), + responseBodyString, new TypeReference>() {}), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -441,11 +435,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -501,14 +493,14 @@ public CompletableFuture> updat @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), UpdateFinetunedModelResponse.class), + responseBodyString, UpdateFinetunedModelResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -545,11 +537,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -623,13 +613,13 @@ public CompletableFuture> listEvents( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEventsResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListEventsResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -666,11 +656,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -742,14 +730,14 @@ public CompletableFuture> li @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListTrainingStepMetricsResponse.class), + responseBodyString, ListTrainingStepMetricsResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -786,11 +774,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/resources/finetuning/RawFinetuningClient.java b/src/main/java/com/cohere/api/resources/finetuning/RawFinetuningClient.java index 1dd95fc..02f48c4 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/RawFinetuningClient.java +++ b/src/main/java/com/cohere/api/resources/finetuning/RawFinetuningClient.java @@ -95,12 +95,12 @@ public CohereHttpResponse listFinetunedModels( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListFinetunedModelsResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListFinetunedModelsResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -125,11 +125,9 @@ public CohereHttpResponse listFinetunedModels( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -171,12 +169,12 @@ public CohereHttpResponse createFinetunedModel( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CreateFinetunedModelResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateFinetunedModelResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -201,11 +199,9 @@ public CohereHttpResponse createFinetunedModel( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -239,12 +235,12 @@ public CohereHttpResponse getFinetunedModel(String id } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetFinetunedModelResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetFinetunedModelResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -269,11 +265,9 @@ public CohereHttpResponse getFinetunedModel(String id } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -309,13 +303,13 @@ public CohereHttpResponse> deleteFinetunedModel(String id, R } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), new TypeReference>() {}), + responseBodyString, new TypeReference>() {}), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -340,11 +334,9 @@ public CohereHttpResponse> deleteFinetunedModel(String id, R } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -388,12 +380,12 @@ public CohereHttpResponse updateFinetunedModel( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UpdateFinetunedModelResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, UpdateFinetunedModelResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -418,11 +410,9 @@ public CohereHttpResponse updateFinetunedModel( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -484,11 +474,11 @@ public CohereHttpResponse listEvents( } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListEventsResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListEventsResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -513,11 +503,9 @@ public CohereHttpResponse listEvents( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -576,13 +564,12 @@ public CohereHttpResponse listTrainingStepMetri } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), ListTrainingStepMetricsResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListTrainingStepMetricsResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -607,11 +594,9 @@ public CohereHttpResponse listTrainingStepMetri } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseType.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseType.java index 015386d..6a9c4ce 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseType.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/BaseType.java @@ -3,28 +3,113 @@ */ package com.cohere.api.resources.finetuning.finetuning.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum BaseType { - BASE_TYPE_UNSPECIFIED("BASE_TYPE_UNSPECIFIED"), +public final class BaseType { + public static final BaseType BASE_TYPE_RERANK = new BaseType(Value.BASE_TYPE_RERANK, "BASE_TYPE_RERANK"); - BASE_TYPE_GENERATIVE("BASE_TYPE_GENERATIVE"), + public static final BaseType BASE_TYPE_CHAT = new BaseType(Value.BASE_TYPE_CHAT, "BASE_TYPE_CHAT"); - BASE_TYPE_CLASSIFICATION("BASE_TYPE_CLASSIFICATION"), + public static final BaseType BASE_TYPE_UNSPECIFIED = + new BaseType(Value.BASE_TYPE_UNSPECIFIED, "BASE_TYPE_UNSPECIFIED"); - BASE_TYPE_RERANK("BASE_TYPE_RERANK"), + public static final BaseType BASE_TYPE_GENERATIVE = + new BaseType(Value.BASE_TYPE_GENERATIVE, "BASE_TYPE_GENERATIVE"); - BASE_TYPE_CHAT("BASE_TYPE_CHAT"); + public static final BaseType BASE_TYPE_CLASSIFICATION = + new BaseType(Value.BASE_TYPE_CLASSIFICATION, "BASE_TYPE_CLASSIFICATION"); - private final String value; + private final Value value; - BaseType(String value) { + private final String string; + + BaseType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof BaseType && this.string.equals(((BaseType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BASE_TYPE_RERANK: + return visitor.visitBaseTypeRerank(); + case BASE_TYPE_CHAT: + return visitor.visitBaseTypeChat(); + case BASE_TYPE_UNSPECIFIED: + return visitor.visitBaseTypeUnspecified(); + case BASE_TYPE_GENERATIVE: + return visitor.visitBaseTypeGenerative(); + case BASE_TYPE_CLASSIFICATION: + return visitor.visitBaseTypeClassification(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static BaseType valueOf(String value) { + switch (value) { + case "BASE_TYPE_RERANK": + return BASE_TYPE_RERANK; + case "BASE_TYPE_CHAT": + return BASE_TYPE_CHAT; + case "BASE_TYPE_UNSPECIFIED": + return BASE_TYPE_UNSPECIFIED; + case "BASE_TYPE_GENERATIVE": + return BASE_TYPE_GENERATIVE; + case "BASE_TYPE_CLASSIFICATION": + return BASE_TYPE_CLASSIFICATION; + default: + return new BaseType(Value.UNKNOWN, value); + } + } + + public enum Value { + BASE_TYPE_UNSPECIFIED, + + BASE_TYPE_GENERATIVE, + + BASE_TYPE_CLASSIFICATION, + + BASE_TYPE_RERANK, + + BASE_TYPE_CHAT, + + UNKNOWN + } + + public interface Visitor { + T visitBaseTypeUnspecified(); + + T visitBaseTypeGenerative(); + + T visitBaseTypeClassification(); + + T visitBaseTypeRerank(); + + T visitBaseTypeChat(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/LoraTargetModules.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/LoraTargetModules.java index 4ebf4db..d781607 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/LoraTargetModules.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/LoraTargetModules.java @@ -3,26 +3,105 @@ */ package com.cohere.api.resources.finetuning.finetuning.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum LoraTargetModules { - LORA_TARGET_MODULES_UNSPECIFIED("LORA_TARGET_MODULES_UNSPECIFIED"), +public final class LoraTargetModules { + public static final LoraTargetModules LORA_TARGET_MODULES_UNSPECIFIED = + new LoraTargetModules(Value.LORA_TARGET_MODULES_UNSPECIFIED, "LORA_TARGET_MODULES_UNSPECIFIED"); - LORA_TARGET_MODULES_QV("LORA_TARGET_MODULES_QV"), + public static final LoraTargetModules LORA_TARGET_MODULES_QV = + new LoraTargetModules(Value.LORA_TARGET_MODULES_QV, "LORA_TARGET_MODULES_QV"); - LORA_TARGET_MODULES_QKVO("LORA_TARGET_MODULES_QKVO"), + public static final LoraTargetModules LORA_TARGET_MODULES_QKVO_FFN = + new LoraTargetModules(Value.LORA_TARGET_MODULES_QKVO_FFN, "LORA_TARGET_MODULES_QKVO_FFN"); - LORA_TARGET_MODULES_QKVO_FFN("LORA_TARGET_MODULES_QKVO_FFN"); + public static final LoraTargetModules LORA_TARGET_MODULES_QKVO = + new LoraTargetModules(Value.LORA_TARGET_MODULES_QKVO, "LORA_TARGET_MODULES_QKVO"); - private final String value; + private final Value value; - LoraTargetModules(String value) { + private final String string; + + LoraTargetModules(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof LoraTargetModules && this.string.equals(((LoraTargetModules) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case LORA_TARGET_MODULES_UNSPECIFIED: + return visitor.visitLoraTargetModulesUnspecified(); + case LORA_TARGET_MODULES_QV: + return visitor.visitLoraTargetModulesQv(); + case LORA_TARGET_MODULES_QKVO_FFN: + return visitor.visitLoraTargetModulesQkvoFfn(); + case LORA_TARGET_MODULES_QKVO: + return visitor.visitLoraTargetModulesQkvo(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static LoraTargetModules valueOf(String value) { + switch (value) { + case "LORA_TARGET_MODULES_UNSPECIFIED": + return LORA_TARGET_MODULES_UNSPECIFIED; + case "LORA_TARGET_MODULES_QV": + return LORA_TARGET_MODULES_QV; + case "LORA_TARGET_MODULES_QKVO_FFN": + return LORA_TARGET_MODULES_QKVO_FFN; + case "LORA_TARGET_MODULES_QKVO": + return LORA_TARGET_MODULES_QKVO; + default: + return new LoraTargetModules(Value.UNKNOWN, value); + } + } + + public enum Value { + LORA_TARGET_MODULES_UNSPECIFIED, + + LORA_TARGET_MODULES_QV, + + LORA_TARGET_MODULES_QKVO, + + LORA_TARGET_MODULES_QKVO_FFN, + + UNKNOWN + } + + public interface Visitor { + T visitLoraTargetModulesUnspecified(); + + T visitLoraTargetModulesQv(); + + T visitLoraTargetModulesQkvo(); + + T visitLoraTargetModulesQkvoFfn(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Status.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Status.java index 386fe0f..ca0a1ef 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Status.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Status.java @@ -3,36 +3,151 @@ */ package com.cohere.api.resources.finetuning.finetuning.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum Status { - STATUS_UNSPECIFIED("STATUS_UNSPECIFIED"), +public final class Status { + public static final Status STATUS_TEMPORARILY_OFFLINE = + new Status(Value.STATUS_TEMPORARILY_OFFLINE, "STATUS_TEMPORARILY_OFFLINE"); - STATUS_FINETUNING("STATUS_FINETUNING"), + public static final Status STATUS_FAILED = new Status(Value.STATUS_FAILED, "STATUS_FAILED"); - STATUS_DEPLOYING_API("STATUS_DEPLOYING_API"), + public static final Status STATUS_FINETUNING = new Status(Value.STATUS_FINETUNING, "STATUS_FINETUNING"); - STATUS_READY("STATUS_READY"), + public static final Status STATUS_READY = new Status(Value.STATUS_READY, "STATUS_READY"); - STATUS_FAILED("STATUS_FAILED"), + public static final Status STATUS_DELETED = new Status(Value.STATUS_DELETED, "STATUS_DELETED"); - STATUS_DELETED("STATUS_DELETED"), + public static final Status STATUS_DEPLOYING_API = new Status(Value.STATUS_DEPLOYING_API, "STATUS_DEPLOYING_API"); - STATUS_TEMPORARILY_OFFLINE("STATUS_TEMPORARILY_OFFLINE"), + public static final Status STATUS_PAUSED = new Status(Value.STATUS_PAUSED, "STATUS_PAUSED"); - STATUS_PAUSED("STATUS_PAUSED"), + public static final Status STATUS_QUEUED = new Status(Value.STATUS_QUEUED, "STATUS_QUEUED"); - STATUS_QUEUED("STATUS_QUEUED"); + public static final Status STATUS_UNSPECIFIED = new Status(Value.STATUS_UNSPECIFIED, "STATUS_UNSPECIFIED"); - private final String value; + private final Value value; - Status(String value) { + private final String string; + + Status(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof Status && this.string.equals(((Status) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case STATUS_TEMPORARILY_OFFLINE: + return visitor.visitStatusTemporarilyOffline(); + case STATUS_FAILED: + return visitor.visitStatusFailed(); + case STATUS_FINETUNING: + return visitor.visitStatusFinetuning(); + case STATUS_READY: + return visitor.visitStatusReady(); + case STATUS_DELETED: + return visitor.visitStatusDeleted(); + case STATUS_DEPLOYING_API: + return visitor.visitStatusDeployingApi(); + case STATUS_PAUSED: + return visitor.visitStatusPaused(); + case STATUS_QUEUED: + return visitor.visitStatusQueued(); + case STATUS_UNSPECIFIED: + return visitor.visitStatusUnspecified(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static Status valueOf(String value) { + switch (value) { + case "STATUS_TEMPORARILY_OFFLINE": + return STATUS_TEMPORARILY_OFFLINE; + case "STATUS_FAILED": + return STATUS_FAILED; + case "STATUS_FINETUNING": + return STATUS_FINETUNING; + case "STATUS_READY": + return STATUS_READY; + case "STATUS_DELETED": + return STATUS_DELETED; + case "STATUS_DEPLOYING_API": + return STATUS_DEPLOYING_API; + case "STATUS_PAUSED": + return STATUS_PAUSED; + case "STATUS_QUEUED": + return STATUS_QUEUED; + case "STATUS_UNSPECIFIED": + return STATUS_UNSPECIFIED; + default: + return new Status(Value.UNKNOWN, value); + } + } + + public enum Value { + STATUS_UNSPECIFIED, + + STATUS_FINETUNING, + + STATUS_DEPLOYING_API, + + STATUS_READY, + + STATUS_FAILED, + + STATUS_DELETED, + + STATUS_TEMPORARILY_OFFLINE, + + STATUS_PAUSED, + + STATUS_QUEUED, + + UNKNOWN + } + + public interface Visitor { + T visitStatusUnspecified(); + + T visitStatusFinetuning(); + + T visitStatusDeployingApi(); + + T visitStatusReady(); + + T visitStatusFailed(); + + T visitStatusDeleted(); + + T visitStatusTemporarilyOffline(); + + T visitStatusPaused(); + + T visitStatusQueued(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Strategy.java b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Strategy.java index 33f2cee..c7cd26c 100644 --- a/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Strategy.java +++ b/src/main/java/com/cohere/api/resources/finetuning/finetuning/types/Strategy.java @@ -3,24 +3,91 @@ */ package com.cohere.api.resources.finetuning.finetuning.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum Strategy { - STRATEGY_UNSPECIFIED("STRATEGY_UNSPECIFIED"), +public final class Strategy { + public static final Strategy STRATEGY_UNSPECIFIED = + new Strategy(Value.STRATEGY_UNSPECIFIED, "STRATEGY_UNSPECIFIED"); - STRATEGY_VANILLA("STRATEGY_VANILLA"), + public static final Strategy STRATEGY_TFEW = new Strategy(Value.STRATEGY_TFEW, "STRATEGY_TFEW"); - STRATEGY_TFEW("STRATEGY_TFEW"); + public static final Strategy STRATEGY_VANILLA = new Strategy(Value.STRATEGY_VANILLA, "STRATEGY_VANILLA"); - private final String value; + private final Value value; - Strategy(String value) { + private final String string; + + Strategy(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof Strategy && this.string.equals(((Strategy) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case STRATEGY_UNSPECIFIED: + return visitor.visitStrategyUnspecified(); + case STRATEGY_TFEW: + return visitor.visitStrategyTfew(); + case STRATEGY_VANILLA: + return visitor.visitStrategyVanilla(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static Strategy valueOf(String value) { + switch (value) { + case "STRATEGY_UNSPECIFIED": + return STRATEGY_UNSPECIFIED; + case "STRATEGY_TFEW": + return STRATEGY_TFEW; + case "STRATEGY_VANILLA": + return STRATEGY_VANILLA; + default: + return new Strategy(Value.UNKNOWN, value); + } + } + + public enum Value { + STRATEGY_UNSPECIFIED, + + STRATEGY_VANILLA, + + STRATEGY_TFEW, + + UNKNOWN + } + + public interface Visitor { + T visitStrategyUnspecified(); + + T visitStrategyVanilla(); + + T visitStrategyTfew(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java b/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java index a5ec2e9..135c199 100644 --- a/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java +++ b/src/main/java/com/cohere/api/resources/models/AsyncModelsClient.java @@ -42,21 +42,21 @@ public CompletableFuture get(String model, RequestOptions requ } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CompletableFuture list() { return this.rawClient.list().thenApply(response -> response.body()); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CompletableFuture list(ModelsListRequest request) { return this.rawClient.list(request).thenApply(response -> response.body()); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CompletableFuture list(ModelsListRequest request, RequestOptions requestOptions) { return this.rawClient.list(request, requestOptions).thenApply(response -> response.body()); diff --git a/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java b/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java index 0a3801a..016b831 100644 --- a/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java +++ b/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java @@ -76,13 +76,13 @@ public CompletableFuture> get(String model, @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetModelResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetModelResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -149,11 +149,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -169,21 +167,21 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CompletableFuture> list() { return list(ModelsListRequest.builder().build()); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CompletableFuture> list(ModelsListRequest request) { return list(request, null); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CompletableFuture> list( ModelsListRequest request, RequestOptions requestOptions) { @@ -221,13 +219,13 @@ public CompletableFuture> list( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListModelsResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListModelsResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -294,11 +292,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/resources/models/ModelsClient.java b/src/main/java/com/cohere/api/resources/models/ModelsClient.java index b73cf49..237e9ff 100644 --- a/src/main/java/com/cohere/api/resources/models/ModelsClient.java +++ b/src/main/java/com/cohere/api/resources/models/ModelsClient.java @@ -41,21 +41,21 @@ public GetModelResponse get(String model, RequestOptions requestOptions) { } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public ListModelsResponse list() { return this.rawClient.list().body(); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public ListModelsResponse list(ModelsListRequest request) { return this.rawClient.list(request).body(); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public ListModelsResponse list(ModelsListRequest request, RequestOptions requestOptions) { return this.rawClient.list(request, requestOptions).body(); diff --git a/src/main/java/com/cohere/api/resources/models/RawModelsClient.java b/src/main/java/com/cohere/api/resources/models/RawModelsClient.java index a094ca9..3fbcbfa 100644 --- a/src/main/java/com/cohere/api/resources/models/RawModelsClient.java +++ b/src/main/java/com/cohere/api/resources/models/RawModelsClient.java @@ -69,11 +69,11 @@ public CohereHttpResponse get(String model, RequestOptions req } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), GetModelResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetModelResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -116,32 +116,30 @@ public CohereHttpResponse get(String model, RequestOptions req } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CohereHttpResponse list() { return list(ModelsListRequest.builder().build()); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CohereHttpResponse list(ModelsListRequest request) { return list(request, null); } /** - * Returns a list of models available for use. The list contains models from Cohere as well as your fine-tuned models. + * Returns a list of models available for use. */ public CohereHttpResponse list(ModelsListRequest request, RequestOptions requestOptions) { HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) @@ -175,11 +173,11 @@ public CohereHttpResponse list(ModelsListRequest request, Re } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ListModelsResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListModelsResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -222,11 +220,9 @@ public CohereHttpResponse list(ModelsListRequest request, Re } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java b/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java index 0004660..0addea0 100644 --- a/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java +++ b/src/main/java/com/cohere/api/resources/v2/AsyncRawV2Client.java @@ -169,11 +169,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -229,13 +227,13 @@ public CompletableFuture> chat( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2ChatResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, V2ChatResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -302,11 +300,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -364,13 +360,13 @@ public CompletableFuture> embed( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedByTypeResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmbedByTypeResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -437,11 +433,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); @@ -495,13 +489,13 @@ public CompletableFuture> rerank( @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { try (ResponseBody responseBody = response.body()) { + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { future.complete(new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2RerankResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, V2RerankResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -568,11 +562,9 @@ public void onResponse(@NotNull Call call, @NotNull Response response) throws IO } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); future.completeExceptionally(new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); + "Error with status code " + response.code(), response.code(), errorBody, response)); return; } catch (IOException e) { future.completeExceptionally(new CohereException("Network error executing HTTP request", e)); diff --git a/src/main/java/com/cohere/api/resources/v2/RawV2Client.java b/src/main/java/com/cohere/api/resources/v2/RawV2Client.java index 5f4d0cd..ab9d1a1 100644 --- a/src/main/java/com/cohere/api/resources/v2/RawV2Client.java +++ b/src/main/java/com/cohere/api/resources/v2/RawV2Client.java @@ -135,11 +135,9 @@ public CohereHttpResponse> chatStream( } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -182,11 +180,11 @@ public CohereHttpResponse chat(V2ChatRequest request, RequestOpt } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2ChatResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, V2ChatResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -229,11 +227,9 @@ public CohereHttpResponse chat(V2ChatRequest request, RequestOpt } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -278,12 +274,11 @@ public CohereHttpResponse embed(V2EmbedRequest request, Req } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), EmbedByTypeResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, EmbedByTypeResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -326,11 +321,9 @@ public CohereHttpResponse embed(V2EmbedRequest request, Req } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } @@ -371,11 +364,11 @@ public CohereHttpResponse rerank(V2RerankRequest request, Requ } try (Response response = client.newCall(okhttpRequest).execute()) { ResponseBody responseBody = response.body(); + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; if (response.isSuccessful()) { return new CohereHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V2RerankResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, V2RerankResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -418,11 +411,9 @@ public CohereHttpResponse rerank(V2RerankRequest request, Requ } catch (JsonProcessingException ignored) { // unable to map error response, throwing generic error } + Object errorBody = ObjectMappers.parseErrorBody(responseBodyString); throw new CohereApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); + "Error with status code " + response.code(), response.code(), errorBody, response); } catch (IOException e) { throw new CohereException("Network error executing HTTP request", e); } diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2ChatRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2ChatRequest.java index 1d6b6b8..a458783 100644 --- a/src/main/java/com/cohere/api/resources/v2/requests/V2ChatRequest.java +++ b/src/main/java/com/cohere/api/resources/v2/requests/V2ChatRequest.java @@ -69,6 +69,8 @@ public final class V2ChatRequest { private final Optional thinking; + private final Optional priority; + private final Map additionalProperties; private V2ChatRequest( @@ -91,6 +93,7 @@ private V2ChatRequest( Optional logprobs, Optional toolChoice, Optional thinking, + Optional priority, Map additionalProperties) { this.model = model; this.messages = messages; @@ -111,6 +114,7 @@ private V2ChatRequest( this.logprobs = logprobs; this.toolChoice = toolChoice; this.thinking = thinking; + this.priority = priority; this.additionalProperties = additionalProperties; } @@ -125,7 +129,7 @@ public Boolean getStream() { } /** - * @return The name of a compatible Cohere model or the ID of a fine-tuned model. + * @return The name of a compatible Cohere model. */ @JsonProperty("model") public String getModel() { @@ -284,6 +288,15 @@ public Optional getThinking() { return thinking; } + /** + * @return The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load. + */ + @JsonProperty("priority") + public Optional getPriority() { + return priority; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -314,7 +327,8 @@ private boolean equalTo(V2ChatRequest other) { && p.equals(other.p) && logprobs.equals(other.logprobs) && toolChoice.equals(other.toolChoice) - && thinking.equals(other.thinking); + && thinking.equals(other.thinking) + && priority.equals(other.priority); } @java.lang.Override @@ -338,7 +352,8 @@ public int hashCode() { this.p, this.logprobs, this.toolChoice, - this.thinking); + this.thinking, + this.priority); } @java.lang.Override @@ -352,7 +367,7 @@ public static ModelStage builder() { public interface ModelStage { /** - *

The name of a compatible Cohere model or the ID of a fine-tuned model.

+ *

The name of a compatible Cohere model.

*/ _FinalStage model(@NotNull String model); @@ -497,12 +512,22 @@ public interface _FinalStage { _FinalStage thinking(Optional thinking); _FinalStage thinking(Thinking thinking); + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + _FinalStage priority(Optional priority); + + _FinalStage priority(Integer priority); } @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder implements ModelStage, _FinalStage { private String model; + private Optional priority = Optional.empty(); + private Optional thinking = Optional.empty(); private Optional toolChoice = Optional.empty(); @@ -565,12 +590,13 @@ public Builder from(V2ChatRequest other) { logprobs(other.getLogprobs()); toolChoice(other.getToolChoice()); thinking(other.getThinking()); + priority(other.getPriority()); return this; } /** - *

The name of a compatible Cohere model or the ID of a fine-tuned model.

- *

The name of a compatible Cohere model or the ID of a fine-tuned model.

+ *

The name of a compatible Cohere model.

+ *

The name of a compatible Cohere model.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @@ -580,6 +606,28 @@ public _FinalStage model(@NotNull String model) { return this; } + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage priority(Integer priority) { + this.priority = Optional.ofNullable(priority); + return this; + } + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + @java.lang.Override + @JsonSetter(value = "priority", nulls = Nulls.SKIP) + public _FinalStage priority(Optional priority) { + this.priority = priority; + return this; + } + @java.lang.Override public _FinalStage thinking(Thinking thinking) { this.thinking = Optional.ofNullable(thinking); @@ -941,7 +989,9 @@ public _FinalStage tools(Optional> tools) { @java.lang.Override public _FinalStage addAllMessages(List messages) { - this.messages.addAll(messages); + if (messages != null) { + this.messages.addAll(messages); + } return this; } @@ -955,7 +1005,9 @@ public _FinalStage addMessages(ChatMessageV2 messages) { @JsonSetter(value = "messages", nulls = Nulls.SKIP) public _FinalStage messages(List messages) { this.messages.clear(); - this.messages.addAll(messages); + if (messages != null) { + this.messages.addAll(messages); + } return this; } @@ -981,6 +1033,7 @@ public V2ChatRequest build() { logprobs, toolChoice, thinking, + priority, additionalProperties); } } diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2ChatStreamRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2ChatStreamRequest.java index 8bae398..9274dfc 100644 --- a/src/main/java/com/cohere/api/resources/v2/requests/V2ChatStreamRequest.java +++ b/src/main/java/com/cohere/api/resources/v2/requests/V2ChatStreamRequest.java @@ -69,6 +69,8 @@ public final class V2ChatStreamRequest { private final Optional thinking; + private final Optional priority; + private final Map additionalProperties; private V2ChatStreamRequest( @@ -91,6 +93,7 @@ private V2ChatStreamRequest( Optional logprobs, Optional toolChoice, Optional thinking, + Optional priority, Map additionalProperties) { this.model = model; this.messages = messages; @@ -111,6 +114,7 @@ private V2ChatStreamRequest( this.logprobs = logprobs; this.toolChoice = toolChoice; this.thinking = thinking; + this.priority = priority; this.additionalProperties = additionalProperties; } @@ -125,7 +129,7 @@ public Boolean getStream() { } /** - * @return The name of a compatible Cohere model or the ID of a fine-tuned model. + * @return The name of a compatible Cohere model. */ @JsonProperty("model") public String getModel() { @@ -284,6 +288,15 @@ public Optional getThinking() { return thinking; } + /** + * @return The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load. + */ + @JsonProperty("priority") + public Optional getPriority() { + return priority; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -314,7 +327,8 @@ private boolean equalTo(V2ChatStreamRequest other) { && p.equals(other.p) && logprobs.equals(other.logprobs) && toolChoice.equals(other.toolChoice) - && thinking.equals(other.thinking); + && thinking.equals(other.thinking) + && priority.equals(other.priority); } @java.lang.Override @@ -338,7 +352,8 @@ public int hashCode() { this.p, this.logprobs, this.toolChoice, - this.thinking); + this.thinking, + this.priority); } @java.lang.Override @@ -352,7 +367,7 @@ public static ModelStage builder() { public interface ModelStage { /** - *

The name of a compatible Cohere model or the ID of a fine-tuned model.

+ *

The name of a compatible Cohere model.

*/ _FinalStage model(@NotNull String model); @@ -497,12 +512,22 @@ public interface _FinalStage { _FinalStage thinking(Optional thinking); _FinalStage thinking(Thinking thinking); + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + _FinalStage priority(Optional priority); + + _FinalStage priority(Integer priority); } @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder implements ModelStage, _FinalStage { private String model; + private Optional priority = Optional.empty(); + private Optional thinking = Optional.empty(); private Optional toolChoice = Optional.empty(); @@ -565,12 +590,13 @@ public Builder from(V2ChatStreamRequest other) { logprobs(other.getLogprobs()); toolChoice(other.getToolChoice()); thinking(other.getThinking()); + priority(other.getPriority()); return this; } /** - *

The name of a compatible Cohere model or the ID of a fine-tuned model.

- *

The name of a compatible Cohere model or the ID of a fine-tuned model.

+ *

The name of a compatible Cohere model.

+ *

The name of a compatible Cohere model.

* @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override @@ -580,6 +606,28 @@ public _FinalStage model(@NotNull String model) { return this; } + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage priority(Integer priority) { + this.priority = Optional.ofNullable(priority); + return this; + } + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + @java.lang.Override + @JsonSetter(value = "priority", nulls = Nulls.SKIP) + public _FinalStage priority(Optional priority) { + this.priority = priority; + return this; + } + @java.lang.Override public _FinalStage thinking(Thinking thinking) { this.thinking = Optional.ofNullable(thinking); @@ -941,7 +989,9 @@ public _FinalStage tools(Optional> tools) { @java.lang.Override public _FinalStage addAllMessages(List messages) { - this.messages.addAll(messages); + if (messages != null) { + this.messages.addAll(messages); + } return this; } @@ -955,7 +1005,9 @@ public _FinalStage addMessages(ChatMessageV2 messages) { @JsonSetter(value = "messages", nulls = Nulls.SKIP) public _FinalStage messages(List messages) { this.messages.clear(); - this.messages.addAll(messages); + if (messages != null) { + this.messages.addAll(messages); + } return this; } @@ -981,6 +1033,7 @@ public V2ChatStreamRequest build() { logprobs, toolChoice, thinking, + priority, additionalProperties); } } diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java index aeb1df6..d7cf1a7 100644 --- a/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java +++ b/src/main/java/com/cohere/api/resources/v2/requests/V2EmbedRequest.java @@ -44,6 +44,8 @@ public final class V2EmbedRequest { private final Optional truncate; + private final Optional priority; + private final Map additionalProperties; private V2EmbedRequest( @@ -56,6 +58,7 @@ private V2EmbedRequest( Optional outputDimension, Optional> embeddingTypes, Optional truncate, + Optional priority, Map additionalProperties) { this.texts = texts; this.images = images; @@ -66,6 +69,7 @@ private V2EmbedRequest( this.outputDimension = outputDimension; this.embeddingTypes = embeddingTypes; this.truncate = truncate; + this.priority = priority; this.additionalProperties = additionalProperties; } @@ -79,7 +83,7 @@ public Optional> getTexts() { /** * @return An array of image data URIs for the model to embed. Maximum number of images per call is 1. - *

The image must be a valid data URI. The image must be in either image/jpeg or image/png format and has a maximum size of 5MB.

+ *

The image must be a valid data URI. The image must be in either image/jpeg, image/png, image/webp, or image/gif format and has a maximum size of 5MB.

*

Image embeddings are supported with Embed v3.0 and newer models.

*/ @JsonProperty("images") @@ -151,6 +155,15 @@ public Optional getTruncate() { return truncate; } + /** + * @return The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load. + */ + @JsonProperty("priority") + public Optional getPriority() { + return priority; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -171,7 +184,8 @@ private boolean equalTo(V2EmbedRequest other) { && maxTokens.equals(other.maxTokens) && outputDimension.equals(other.outputDimension) && embeddingTypes.equals(other.embeddingTypes) - && truncate.equals(other.truncate); + && truncate.equals(other.truncate) + && priority.equals(other.priority); } @java.lang.Override @@ -185,7 +199,8 @@ public int hashCode() { this.maxTokens, this.outputDimension, this.embeddingTypes, - this.truncate); + this.truncate, + this.priority); } @java.lang.Override @@ -222,7 +237,7 @@ public interface _FinalStage { /** *

An array of image data URIs for the model to embed. Maximum number of images per call is 1.

- *

The image must be a valid data URI. The image must be in either image/jpeg or image/png format and has a maximum size of 5MB.

+ *

The image must be a valid data URI. The image must be in either image/jpeg, image/png, image/webp, or image/gif format and has a maximum size of 5MB.

*

Image embeddings are supported with Embed v3.0 and newer models.

*/ _FinalStage images(Optional> images); @@ -274,6 +289,14 @@ public interface _FinalStage { _FinalStage truncate(Optional truncate); _FinalStage truncate(V2EmbedRequestTruncate truncate); + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + _FinalStage priority(Optional priority); + + _FinalStage priority(Integer priority); } @JsonIgnoreProperties(ignoreUnknown = true) @@ -282,6 +305,8 @@ public static final class Builder implements ModelStage, InputTypeStage, _FinalS private EmbedInputType inputType; + private Optional priority = Optional.empty(); + private Optional truncate = Optional.empty(); private Optional> embeddingTypes = Optional.empty(); @@ -312,6 +337,7 @@ public Builder from(V2EmbedRequest other) { outputDimension(other.getOutputDimension()); embeddingTypes(other.getEmbeddingTypes()); truncate(other.getTruncate()); + priority(other.getPriority()); return this; } @@ -334,6 +360,28 @@ public _FinalStage inputType(@NotNull EmbedInputType inputType) { return this; } + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage priority(Integer priority) { + this.priority = Optional.ofNullable(priority); + return this; + } + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + @java.lang.Override + @JsonSetter(value = "priority", nulls = Nulls.SKIP) + public _FinalStage priority(Optional priority) { + this.priority = priority; + return this; + } + /** *

One of NONE|START|END to specify how the API will handle inputs longer than the maximum token length.

*

Passing START will discard the start of the input. END will discard the end of the input. In both cases, input is discarded until the remaining input is exactly the maximum input token length for the model.

@@ -458,7 +506,7 @@ public _FinalStage inputs(Optional> inputs) { /** *

An array of image data URIs for the model to embed. Maximum number of images per call is 1.

- *

The image must be a valid data URI. The image must be in either image/jpeg or image/png format and has a maximum size of 5MB.

+ *

The image must be a valid data URI. The image must be in either image/jpeg, image/png, image/webp, or image/gif format and has a maximum size of 5MB.

*

Image embeddings are supported with Embed v3.0 and newer models.

* @return Reference to {@code this} so that method calls can be chained together. */ @@ -470,7 +518,7 @@ public _FinalStage images(List images) { /** *

An array of image data URIs for the model to embed. Maximum number of images per call is 1.

- *

The image must be a valid data URI. The image must be in either image/jpeg or image/png format and has a maximum size of 5MB.

+ *

The image must be a valid data URI. The image must be in either image/jpeg, image/png, image/webp, or image/gif format and has a maximum size of 5MB.

*

Image embeddings are supported with Embed v3.0 and newer models.

*/ @java.lang.Override @@ -512,6 +560,7 @@ public V2EmbedRequest build() { outputDimension, embeddingTypes, truncate, + priority, additionalProperties); } } diff --git a/src/main/java/com/cohere/api/resources/v2/requests/V2RerankRequest.java b/src/main/java/com/cohere/api/resources/v2/requests/V2RerankRequest.java index 0089220..0b7a969 100644 --- a/src/main/java/com/cohere/api/resources/v2/requests/V2RerankRequest.java +++ b/src/main/java/com/cohere/api/resources/v2/requests/V2RerankRequest.java @@ -33,6 +33,8 @@ public final class V2RerankRequest { private final Optional maxTokensPerDoc; + private final Optional priority; + private final Map additionalProperties; private V2RerankRequest( @@ -41,12 +43,14 @@ private V2RerankRequest( List documents, Optional topN, Optional maxTokensPerDoc, + Optional priority, Map additionalProperties) { this.model = model; this.query = query; this.documents = documents; this.topN = topN; this.maxTokensPerDoc = maxTokensPerDoc; + this.priority = priority; this.additionalProperties = additionalProperties; } @@ -93,6 +97,15 @@ public Optional getMaxTokensPerDoc() { return maxTokensPerDoc; } + /** + * @return The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load. + */ + @JsonProperty("priority") + public Optional getPriority() { + return priority; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -109,12 +122,13 @@ private boolean equalTo(V2RerankRequest other) { && query.equals(other.query) && documents.equals(other.documents) && topN.equals(other.topN) - && maxTokensPerDoc.equals(other.maxTokensPerDoc); + && maxTokensPerDoc.equals(other.maxTokensPerDoc) + && priority.equals(other.priority); } @java.lang.Override public int hashCode() { - return Objects.hash(this.model, this.query, this.documents, this.topN, this.maxTokensPerDoc); + return Objects.hash(this.model, this.query, this.documents, this.topN, this.maxTokensPerDoc, this.priority); } @java.lang.Override @@ -170,6 +184,14 @@ public interface _FinalStage { _FinalStage maxTokensPerDoc(Optional maxTokensPerDoc); _FinalStage maxTokensPerDoc(Integer maxTokensPerDoc); + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + _FinalStage priority(Optional priority); + + _FinalStage priority(Integer priority); } @JsonIgnoreProperties(ignoreUnknown = true) @@ -178,6 +200,8 @@ public static final class Builder implements ModelStage, QueryStage, _FinalStage private String query; + private Optional priority = Optional.empty(); + private Optional maxTokensPerDoc = Optional.empty(); private Optional topN = Optional.empty(); @@ -196,6 +220,7 @@ public Builder from(V2RerankRequest other) { documents(other.getDocuments()); topN(other.getTopN()); maxTokensPerDoc(other.getMaxTokensPerDoc()); + priority(other.getPriority()); return this; } @@ -223,6 +248,28 @@ public _FinalStage query(@NotNull String query) { return this; } + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage priority(Integer priority) { + this.priority = Optional.ofNullable(priority); + return this; + } + + /** + *

The priority of the request (lower means earlier handling; default 0 highest priority). + * Higher priority requests are handled first, and dropped last when the system is under load.

+ */ + @java.lang.Override + @JsonSetter(value = "priority", nulls = Nulls.SKIP) + public _FinalStage priority(Optional priority) { + this.priority = priority; + return this; + } + /** *

Defaults to 4096. Long documents will be automatically truncated to the specified number of tokens.

* @return Reference to {@code this} so that method calls can be chained together. @@ -272,7 +319,9 @@ public _FinalStage topN(Optional topN) { */ @java.lang.Override public _FinalStage addAllDocuments(List documents) { - this.documents.addAll(documents); + if (documents != null) { + this.documents.addAll(documents); + } return this; } @@ -299,13 +348,15 @@ public _FinalStage addDocuments(String documents) { @JsonSetter(value = "documents", nulls = Nulls.SKIP) public _FinalStage documents(List documents) { this.documents.clear(); - this.documents.addAll(documents); + if (documents != null) { + this.documents.addAll(documents); + } return this; } @java.lang.Override public V2RerankRequest build() { - return new V2RerankRequest(model, query, documents, topN, maxTokensPerDoc, additionalProperties); + return new V2RerankRequest(model, query, documents, topN, maxTokensPerDoc, priority, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestDocumentsItem.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestDocumentsItem.java index 6a0d6fd..17c8a11 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestDocumentsItem.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestDocumentsItem.java @@ -84,11 +84,11 @@ public V2ChatRequestDocumentsItem deserialize(JsonParser p, DeserializationConte Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, Document.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestSafetyMode.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestSafetyMode.java index ff9faca..dc48244 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestSafetyMode.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestSafetyMode.java @@ -3,24 +3,93 @@ */ package com.cohere.api.resources.v2.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum V2ChatRequestSafetyMode { - CONTEXTUAL("CONTEXTUAL"), +public final class V2ChatRequestSafetyMode { + public static final V2ChatRequestSafetyMode OFF = new V2ChatRequestSafetyMode(Value.OFF, "OFF"); - STRICT("STRICT"), + public static final V2ChatRequestSafetyMode STRICT = new V2ChatRequestSafetyMode(Value.STRICT, "STRICT"); - OFF("OFF"); + public static final V2ChatRequestSafetyMode CONTEXTUAL = + new V2ChatRequestSafetyMode(Value.CONTEXTUAL, "CONTEXTUAL"); - private final String value; + private final Value value; - V2ChatRequestSafetyMode(String value) { + private final String string; + + V2ChatRequestSafetyMode(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof V2ChatRequestSafetyMode + && this.string.equals(((V2ChatRequestSafetyMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case OFF: + return visitor.visitOff(); + case STRICT: + return visitor.visitStrict(); + case CONTEXTUAL: + return visitor.visitContextual(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static V2ChatRequestSafetyMode valueOf(String value) { + switch (value) { + case "OFF": + return OFF; + case "STRICT": + return STRICT; + case "CONTEXTUAL": + return CONTEXTUAL; + default: + return new V2ChatRequestSafetyMode(Value.UNKNOWN, value); + } + } + + public enum Value { + CONTEXTUAL, + + STRICT, + + OFF, + + UNKNOWN + } + + public interface Visitor { + T visitContextual(); + + T visitStrict(); + + T visitOff(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestToolChoice.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestToolChoice.java index 61f49c3..55c8a72 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestToolChoice.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2ChatRequestToolChoice.java @@ -3,22 +3,82 @@ */ package com.cohere.api.resources.v2.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum V2ChatRequestToolChoice { - REQUIRED("REQUIRED"), +public final class V2ChatRequestToolChoice { + public static final V2ChatRequestToolChoice REQUIRED = new V2ChatRequestToolChoice(Value.REQUIRED, "REQUIRED"); - NONE("NONE"); + public static final V2ChatRequestToolChoice NONE = new V2ChatRequestToolChoice(Value.NONE, "NONE"); - private final String value; + private final Value value; - V2ChatRequestToolChoice(String value) { + private final String string; + + V2ChatRequestToolChoice(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof V2ChatRequestToolChoice + && this.string.equals(((V2ChatRequestToolChoice) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case REQUIRED: + return visitor.visitRequired(); + case NONE: + return visitor.visitNone(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static V2ChatRequestToolChoice valueOf(String value) { + switch (value) { + case "REQUIRED": + return REQUIRED; + case "NONE": + return NONE; + default: + return new V2ChatRequestToolChoice(Value.UNKNOWN, value); + } + } + + public enum Value { + REQUIRED, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitRequired(); + + T visitNone(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestDocumentsItem.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestDocumentsItem.java index da5b5ff..82bd850 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestDocumentsItem.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestDocumentsItem.java @@ -85,11 +85,11 @@ public V2ChatStreamRequestDocumentsItem deserialize(JsonParser p, Deserializatio Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, Document.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestSafetyMode.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestSafetyMode.java index d7b2404..e2797f5 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestSafetyMode.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestSafetyMode.java @@ -3,24 +3,94 @@ */ package com.cohere.api.resources.v2.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum V2ChatStreamRequestSafetyMode { - CONTEXTUAL("CONTEXTUAL"), +public final class V2ChatStreamRequestSafetyMode { + public static final V2ChatStreamRequestSafetyMode OFF = new V2ChatStreamRequestSafetyMode(Value.OFF, "OFF"); - STRICT("STRICT"), + public static final V2ChatStreamRequestSafetyMode STRICT = + new V2ChatStreamRequestSafetyMode(Value.STRICT, "STRICT"); - OFF("OFF"); + public static final V2ChatStreamRequestSafetyMode CONTEXTUAL = + new V2ChatStreamRequestSafetyMode(Value.CONTEXTUAL, "CONTEXTUAL"); - private final String value; + private final Value value; - V2ChatStreamRequestSafetyMode(String value) { + private final String string; + + V2ChatStreamRequestSafetyMode(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof V2ChatStreamRequestSafetyMode + && this.string.equals(((V2ChatStreamRequestSafetyMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case OFF: + return visitor.visitOff(); + case STRICT: + return visitor.visitStrict(); + case CONTEXTUAL: + return visitor.visitContextual(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static V2ChatStreamRequestSafetyMode valueOf(String value) { + switch (value) { + case "OFF": + return OFF; + case "STRICT": + return STRICT; + case "CONTEXTUAL": + return CONTEXTUAL; + default: + return new V2ChatStreamRequestSafetyMode(Value.UNKNOWN, value); + } + } + + public enum Value { + CONTEXTUAL, + + STRICT, + + OFF, + + UNKNOWN + } + + public interface Visitor { + T visitContextual(); + + T visitStrict(); + + T visitOff(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestToolChoice.java b/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestToolChoice.java index 04e5463..d4f9075 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestToolChoice.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2ChatStreamRequestToolChoice.java @@ -3,22 +3,83 @@ */ package com.cohere.api.resources.v2.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum V2ChatStreamRequestToolChoice { - REQUIRED("REQUIRED"), +public final class V2ChatStreamRequestToolChoice { + public static final V2ChatStreamRequestToolChoice REQUIRED = + new V2ChatStreamRequestToolChoice(Value.REQUIRED, "REQUIRED"); - NONE("NONE"); + public static final V2ChatStreamRequestToolChoice NONE = new V2ChatStreamRequestToolChoice(Value.NONE, "NONE"); - private final String value; + private final Value value; - V2ChatStreamRequestToolChoice(String value) { + private final String string; + + V2ChatStreamRequestToolChoice(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof V2ChatStreamRequestToolChoice + && this.string.equals(((V2ChatStreamRequestToolChoice) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case REQUIRED: + return visitor.visitRequired(); + case NONE: + return visitor.visitNone(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static V2ChatStreamRequestToolChoice valueOf(String value) { + switch (value) { + case "REQUIRED": + return REQUIRED; + case "NONE": + return NONE; + default: + return new V2ChatStreamRequestToolChoice(Value.UNKNOWN, value); + } + } + + public enum Value { + REQUIRED, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitRequired(); + + T visitNone(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2EmbedRequestTruncate.java b/src/main/java/com/cohere/api/resources/v2/types/V2EmbedRequestTruncate.java index fd47c31..1f89b4a 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2EmbedRequestTruncate.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2EmbedRequestTruncate.java @@ -3,24 +3,92 @@ */ package com.cohere.api.resources.v2.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum V2EmbedRequestTruncate { - NONE("NONE"), +public final class V2EmbedRequestTruncate { + public static final V2EmbedRequestTruncate END = new V2EmbedRequestTruncate(Value.END, "END"); - START("START"), + public static final V2EmbedRequestTruncate NONE = new V2EmbedRequestTruncate(Value.NONE, "NONE"); - END("END"); + public static final V2EmbedRequestTruncate START = new V2EmbedRequestTruncate(Value.START, "START"); - private final String value; + private final Value value; - V2EmbedRequestTruncate(String value) { + private final String string; + + V2EmbedRequestTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof V2EmbedRequestTruncate + && this.string.equals(((V2EmbedRequestTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case NONE: + return visitor.visitNone(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static V2EmbedRequestTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "NONE": + return NONE; + case "START": + return START; + default: + return new V2EmbedRequestTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponse.java b/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponse.java index c8546cb..18f6935 100644 --- a/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponse.java +++ b/src/main/java/com/cohere/api/resources/v2/types/V2RerankResponse.java @@ -126,7 +126,9 @@ public Builder id(String id) { @JsonSetter(value = "results", nulls = Nulls.SKIP) public Builder results(List results) { this.results.clear(); - this.results.addAll(results); + if (results != null) { + this.results.addAll(results); + } return this; } @@ -136,7 +138,9 @@ public Builder addResults(V2RerankResponseResultsItem results) { } public Builder addAllResults(List results) { - this.results.addAll(results); + if (results != null) { + this.results.addAll(results); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ApiMeta.java b/src/main/java/com/cohere/api/types/ApiMeta.java index a10d9da..2efc6a9 100644 --- a/src/main/java/com/cohere/api/types/ApiMeta.java +++ b/src/main/java/com/cohere/api/types/ApiMeta.java @@ -27,6 +27,8 @@ public final class ApiMeta { private final Optional tokens; + private final Optional cachedTokens; + private final Optional> warnings; private final Map additionalProperties; @@ -35,11 +37,13 @@ private ApiMeta( Optional apiVersion, Optional billedUnits, Optional tokens, + Optional cachedTokens, Optional> warnings, Map additionalProperties) { this.apiVersion = apiVersion; this.billedUnits = billedUnits; this.tokens = tokens; + this.cachedTokens = cachedTokens; this.warnings = warnings; this.additionalProperties = additionalProperties; } @@ -59,6 +63,14 @@ public Optional getTokens() { return tokens; } + /** + * @return The number of prompt tokens that hit the inference cache. + */ + @JsonProperty("cached_tokens") + public Optional getCachedTokens() { + return cachedTokens; + } + @JsonProperty("warnings") public Optional> getWarnings() { return warnings; @@ -79,12 +91,13 @@ private boolean equalTo(ApiMeta other) { return apiVersion.equals(other.apiVersion) && billedUnits.equals(other.billedUnits) && tokens.equals(other.tokens) + && cachedTokens.equals(other.cachedTokens) && warnings.equals(other.warnings); } @java.lang.Override public int hashCode() { - return Objects.hash(this.apiVersion, this.billedUnits, this.tokens, this.warnings); + return Objects.hash(this.apiVersion, this.billedUnits, this.tokens, this.cachedTokens, this.warnings); } @java.lang.Override @@ -104,6 +117,8 @@ public static final class Builder { private Optional tokens = Optional.empty(); + private Optional cachedTokens = Optional.empty(); + private Optional> warnings = Optional.empty(); @JsonAnySetter @@ -115,6 +130,7 @@ public Builder from(ApiMeta other) { apiVersion(other.getApiVersion()); billedUnits(other.getBilledUnits()); tokens(other.getTokens()); + cachedTokens(other.getCachedTokens()); warnings(other.getWarnings()); return this; } @@ -152,6 +168,20 @@ public Builder tokens(ApiMetaTokens tokens) { return this; } + /** + *

The number of prompt tokens that hit the inference cache.

+ */ + @JsonSetter(value = "cached_tokens", nulls = Nulls.SKIP) + public Builder cachedTokens(Optional cachedTokens) { + this.cachedTokens = cachedTokens; + return this; + } + + public Builder cachedTokens(Double cachedTokens) { + this.cachedTokens = Optional.ofNullable(cachedTokens); + return this; + } + @JsonSetter(value = "warnings", nulls = Nulls.SKIP) public Builder warnings(Optional> warnings) { this.warnings = warnings; @@ -164,7 +194,7 @@ public Builder warnings(List warnings) { } public ApiMeta build() { - return new ApiMeta(apiVersion, billedUnits, tokens, warnings, additionalProperties); + return new ApiMeta(apiVersion, billedUnits, tokens, cachedTokens, warnings, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java b/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java index 369df33..8641074 100644 --- a/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/AssistantMessageV2Content.java @@ -85,12 +85,12 @@ public AssistantMessageV2Content deserialize(JsonParser p, DeserializationContex Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue( value, new TypeReference>() {})); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/cohere/api/types/AuthTokenType.java b/src/main/java/com/cohere/api/types/AuthTokenType.java index 1b40260..b47e5f2 100644 --- a/src/main/java/com/cohere/api/types/AuthTokenType.java +++ b/src/main/java/com/cohere/api/types/AuthTokenType.java @@ -3,24 +3,91 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum AuthTokenType { - BEARER("bearer"), +public final class AuthTokenType { + public static final AuthTokenType BEARER = new AuthTokenType(Value.BEARER, "bearer"); - BASIC("basic"), + public static final AuthTokenType BASIC = new AuthTokenType(Value.BASIC, "basic"); - NOSCHEME("noscheme"); + public static final AuthTokenType NOSCHEME = new AuthTokenType(Value.NOSCHEME, "noscheme"); - private final String value; + private final Value value; - AuthTokenType(String value) { + private final String string; + + AuthTokenType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof AuthTokenType && this.string.equals(((AuthTokenType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BEARER: + return visitor.visitBearer(); + case BASIC: + return visitor.visitBasic(); + case NOSCHEME: + return visitor.visitNoscheme(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static AuthTokenType valueOf(String value) { + switch (value) { + case "bearer": + return BEARER; + case "basic": + return BASIC; + case "noscheme": + return NOSCHEME; + default: + return new AuthTokenType(Value.UNKNOWN, value); + } + } + + public enum Value { + BEARER, + + BASIC, + + NOSCHEME, + + UNKNOWN + } + + public interface Visitor { + T visitBearer(); + + T visitBasic(); + + T visitNoscheme(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatCitation.java b/src/main/java/com/cohere/api/types/ChatCitation.java index d79307d..5ef8e07 100644 --- a/src/main/java/com/cohere/api/types/ChatCitation.java +++ b/src/main/java/com/cohere/api/types/ChatCitation.java @@ -255,7 +255,9 @@ public _FinalStage type(Optional type) { */ @java.lang.Override public _FinalStage addAllDocumentIds(List documentIds) { - this.documentIds.addAll(documentIds); + if (documentIds != null) { + this.documentIds.addAll(documentIds); + } return this; } @@ -276,7 +278,9 @@ public _FinalStage addDocumentIds(String documentIds) { @JsonSetter(value = "document_ids", nulls = Nulls.SKIP) public _FinalStage documentIds(List documentIds) { this.documentIds.clear(); - this.documentIds.addAll(documentIds); + if (documentIds != null) { + this.documentIds.addAll(documentIds); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java index 588a6cd..3d3f8ca 100644 --- a/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatCitationGenerationEvent.java @@ -87,7 +87,9 @@ public Builder from(ChatCitationGenerationEvent other) { @JsonSetter(value = "citations", nulls = Nulls.SKIP) public Builder citations(List citations) { this.citations.clear(); - this.citations.addAll(citations); + if (citations != null) { + this.citations.addAll(citations); + } return this; } @@ -97,7 +99,9 @@ public Builder addCitations(ChatCitation citations) { } public Builder addAllCitations(List citations) { - this.citations.addAll(citations); + if (citations != null) { + this.citations.addAll(citations); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ChatCitationType.java b/src/main/java/com/cohere/api/types/ChatCitationType.java index f705c77..5acf62a 100644 --- a/src/main/java/com/cohere/api/types/ChatCitationType.java +++ b/src/main/java/com/cohere/api/types/ChatCitationType.java @@ -3,22 +3,81 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatCitationType { - TEXT_CONTENT("TEXT_CONTENT"), +public final class ChatCitationType { + public static final ChatCitationType PLAN = new ChatCitationType(Value.PLAN, "PLAN"); - PLAN("PLAN"); + public static final ChatCitationType TEXT_CONTENT = new ChatCitationType(Value.TEXT_CONTENT, "TEXT_CONTENT"); - private final String value; + private final Value value; - ChatCitationType(String value) { + private final String string; + + ChatCitationType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatCitationType && this.string.equals(((ChatCitationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PLAN: + return visitor.visitPlan(); + case TEXT_CONTENT: + return visitor.visitTextContent(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatCitationType valueOf(String value) { + switch (value) { + case "PLAN": + return PLAN; + case "TEXT_CONTENT": + return TEXT_CONTENT; + default: + return new ChatCitationType(Value.UNKNOWN, value); + } + } + + public enum Value { + TEXT_CONTENT, + + PLAN, + + UNKNOWN + } + + public interface Visitor { + T visitTextContent(); + + T visitPlan(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContentType.java b/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContentType.java index ff1c8ef..eb9672c 100644 --- a/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContentType.java +++ b/src/main/java/com/cohere/api/types/ChatContentStartEventDeltaMessageContentType.java @@ -3,22 +3,84 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatContentStartEventDeltaMessageContentType { - TEXT("text"), +public final class ChatContentStartEventDeltaMessageContentType { + public static final ChatContentStartEventDeltaMessageContentType TEXT = + new ChatContentStartEventDeltaMessageContentType(Value.TEXT, "text"); - THINKING("thinking"); + public static final ChatContentStartEventDeltaMessageContentType THINKING = + new ChatContentStartEventDeltaMessageContentType(Value.THINKING, "thinking"); - private final String value; + private final Value value; - ChatContentStartEventDeltaMessageContentType(String value) { + private final String string; + + ChatContentStartEventDeltaMessageContentType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatContentStartEventDeltaMessageContentType + && this.string.equals(((ChatContentStartEventDeltaMessageContentType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case TEXT: + return visitor.visitText(); + case THINKING: + return visitor.visitThinking(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatContentStartEventDeltaMessageContentType valueOf(String value) { + switch (value) { + case "text": + return TEXT; + case "thinking": + return THINKING; + default: + return new ChatContentStartEventDeltaMessageContentType(Value.UNKNOWN, value); + } + } + + public enum Value { + TEXT, + + THINKING, + + UNKNOWN + } + + public interface Visitor { + T visitText(); + + T visitThinking(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatFinishReason.java b/src/main/java/com/cohere/api/types/ChatFinishReason.java index e289f1b..d50b09f 100644 --- a/src/main/java/com/cohere/api/types/ChatFinishReason.java +++ b/src/main/java/com/cohere/api/types/ChatFinishReason.java @@ -3,28 +3,121 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatFinishReason { - COMPLETE("COMPLETE"), +public final class ChatFinishReason { + public static final ChatFinishReason STOP_SEQUENCE = new ChatFinishReason(Value.STOP_SEQUENCE, "STOP_SEQUENCE"); - STOP_SEQUENCE("STOP_SEQUENCE"), + public static final ChatFinishReason TOOL_CALL = new ChatFinishReason(Value.TOOL_CALL, "TOOL_CALL"); - MAX_TOKENS("MAX_TOKENS"), + public static final ChatFinishReason TIMEOUT = new ChatFinishReason(Value.TIMEOUT, "TIMEOUT"); - TOOL_CALL("TOOL_CALL"), + public static final ChatFinishReason COMPLETE = new ChatFinishReason(Value.COMPLETE, "COMPLETE"); - ERROR("ERROR"); + public static final ChatFinishReason MAX_TOKENS = new ChatFinishReason(Value.MAX_TOKENS, "MAX_TOKENS"); - private final String value; + public static final ChatFinishReason ERROR = new ChatFinishReason(Value.ERROR, "ERROR"); - ChatFinishReason(String value) { + private final Value value; + + private final String string; + + ChatFinishReason(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatFinishReason && this.string.equals(((ChatFinishReason) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case STOP_SEQUENCE: + return visitor.visitStopSequence(); + case TOOL_CALL: + return visitor.visitToolCall(); + case TIMEOUT: + return visitor.visitTimeout(); + case COMPLETE: + return visitor.visitComplete(); + case MAX_TOKENS: + return visitor.visitMaxTokens(); + case ERROR: + return visitor.visitError(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatFinishReason valueOf(String value) { + switch (value) { + case "STOP_SEQUENCE": + return STOP_SEQUENCE; + case "TOOL_CALL": + return TOOL_CALL; + case "TIMEOUT": + return TIMEOUT; + case "COMPLETE": + return COMPLETE; + case "MAX_TOKENS": + return MAX_TOKENS; + case "ERROR": + return ERROR; + default: + return new ChatFinishReason(Value.UNKNOWN, value); + } + } + + public enum Value { + COMPLETE, + + STOP_SEQUENCE, + + MAX_TOKENS, + + TOOL_CALL, + + ERROR, + + TIMEOUT, + + UNKNOWN + } + + public interface Visitor { + T visitComplete(); + + T visitStopSequence(); + + T visitMaxTokens(); + + T visitToolCall(); + + T visitError(); + + T visitTimeout(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatRequestCitationQuality.java b/src/main/java/com/cohere/api/types/ChatRequestCitationQuality.java index 214309f..c29b4f0 100644 --- a/src/main/java/com/cohere/api/types/ChatRequestCitationQuality.java +++ b/src/main/java/com/cohere/api/types/ChatRequestCitationQuality.java @@ -3,24 +3,114 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatRequestCitationQuality { - FAST("fast"), +public final class ChatRequestCitationQuality { + public static final ChatRequestCitationQuality FAST = new ChatRequestCitationQuality(Value.FAST, "FAST"); - ACCURATE("accurate"), + public static final ChatRequestCitationQuality DISABLED = + new ChatRequestCitationQuality(Value.DISABLED, "DISABLED"); - OFF("off"); + public static final ChatRequestCitationQuality ENABLED = new ChatRequestCitationQuality(Value.ENABLED, "ENABLED"); - private final String value; + public static final ChatRequestCitationQuality OFF = new ChatRequestCitationQuality(Value.OFF, "OFF"); - ChatRequestCitationQuality(String value) { + public static final ChatRequestCitationQuality ACCURATE = + new ChatRequestCitationQuality(Value.ACCURATE, "ACCURATE"); + + private final Value value; + + private final String string; + + ChatRequestCitationQuality(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatRequestCitationQuality + && this.string.equals(((ChatRequestCitationQuality) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FAST: + return visitor.visitFast(); + case DISABLED: + return visitor.visitDisabled(); + case ENABLED: + return visitor.visitEnabled(); + case OFF: + return visitor.visitOff(); + case ACCURATE: + return visitor.visitAccurate(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatRequestCitationQuality valueOf(String value) { + switch (value) { + case "FAST": + return FAST; + case "DISABLED": + return DISABLED; + case "ENABLED": + return ENABLED; + case "OFF": + return OFF; + case "ACCURATE": + return ACCURATE; + default: + return new ChatRequestCitationQuality(Value.UNKNOWN, value); + } + } + + public enum Value { + ENABLED, + + DISABLED, + + FAST, + + ACCURATE, + + OFF, + + UNKNOWN + } + + public interface Visitor { + T visitEnabled(); + + T visitDisabled(); + + T visitFast(); + + T visitAccurate(); + + T visitOff(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatRequestPromptTruncation.java b/src/main/java/com/cohere/api/types/ChatRequestPromptTruncation.java index 4c58859..b0c86c0 100644 --- a/src/main/java/com/cohere/api/types/ChatRequestPromptTruncation.java +++ b/src/main/java/com/cohere/api/types/ChatRequestPromptTruncation.java @@ -3,24 +3,93 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatRequestPromptTruncation { - OFF("OFF"), +public final class ChatRequestPromptTruncation { + public static final ChatRequestPromptTruncation AUTO = new ChatRequestPromptTruncation(Value.AUTO, "AUTO"); - AUTO("AUTO"), + public static final ChatRequestPromptTruncation AUTO_PRESERVE_ORDER = + new ChatRequestPromptTruncation(Value.AUTO_PRESERVE_ORDER, "AUTO_PRESERVE_ORDER"); - AUTO_PRESERVE_ORDER("AUTO_PRESERVE_ORDER"); + public static final ChatRequestPromptTruncation OFF = new ChatRequestPromptTruncation(Value.OFF, "OFF"); - private final String value; + private final Value value; - ChatRequestPromptTruncation(String value) { + private final String string; + + ChatRequestPromptTruncation(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatRequestPromptTruncation + && this.string.equals(((ChatRequestPromptTruncation) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case AUTO: + return visitor.visitAuto(); + case AUTO_PRESERVE_ORDER: + return visitor.visitAutoPreserveOrder(); + case OFF: + return visitor.visitOff(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatRequestPromptTruncation valueOf(String value) { + switch (value) { + case "AUTO": + return AUTO; + case "AUTO_PRESERVE_ORDER": + return AUTO_PRESERVE_ORDER; + case "OFF": + return OFF; + default: + return new ChatRequestPromptTruncation(Value.UNKNOWN, value); + } + } + + public enum Value { + OFF, + + AUTO, + + AUTO_PRESERVE_ORDER, + + UNKNOWN + } + + public interface Visitor { + T visitOff(); + + T visitAuto(); + + T visitAutoPreserveOrder(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatRequestSafetyMode.java b/src/main/java/com/cohere/api/types/ChatRequestSafetyMode.java index c28c3ff..726e7d4 100644 --- a/src/main/java/com/cohere/api/types/ChatRequestSafetyMode.java +++ b/src/main/java/com/cohere/api/types/ChatRequestSafetyMode.java @@ -3,24 +3,92 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatRequestSafetyMode { - CONTEXTUAL("CONTEXTUAL"), +public final class ChatRequestSafetyMode { + public static final ChatRequestSafetyMode NONE = new ChatRequestSafetyMode(Value.NONE, "NONE"); - STRICT("STRICT"), + public static final ChatRequestSafetyMode STRICT = new ChatRequestSafetyMode(Value.STRICT, "STRICT"); - NONE("NONE"); + public static final ChatRequestSafetyMode CONTEXTUAL = new ChatRequestSafetyMode(Value.CONTEXTUAL, "CONTEXTUAL"); - private final String value; + private final Value value; - ChatRequestSafetyMode(String value) { + private final String string; + + ChatRequestSafetyMode(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatRequestSafetyMode + && this.string.equals(((ChatRequestSafetyMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case NONE: + return visitor.visitNone(); + case STRICT: + return visitor.visitStrict(); + case CONTEXTUAL: + return visitor.visitContextual(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatRequestSafetyMode valueOf(String value) { + switch (value) { + case "NONE": + return NONE; + case "STRICT": + return STRICT; + case "CONTEXTUAL": + return CONTEXTUAL; + default: + return new ChatRequestSafetyMode(Value.UNKNOWN, value); + } + } + + public enum Value { + CONTEXTUAL, + + STRICT, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitContextual(); + + T visitStrict(); + + T visitNone(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java index 6bd704c..263b2ed 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatSearchQueriesGenerationEvent.java @@ -88,7 +88,9 @@ public Builder from(ChatSearchQueriesGenerationEvent other) { @JsonSetter(value = "search_queries", nulls = Nulls.SKIP) public Builder searchQueries(List searchQueries) { this.searchQueries.clear(); - this.searchQueries.addAll(searchQueries); + if (searchQueries != null) { + this.searchQueries.addAll(searchQueries); + } return this; } @@ -98,7 +100,9 @@ public Builder addSearchQueries(ChatSearchQuery searchQueries) { } public Builder addAllSearchQueries(List searchQueries) { - this.searchQueries.addAll(searchQueries); + if (searchQueries != null) { + this.searchQueries.addAll(searchQueries); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ChatSearchResult.java b/src/main/java/com/cohere/api/types/ChatSearchResult.java index 19c3619..e162362 100644 --- a/src/main/java/com/cohere/api/types/ChatSearchResult.java +++ b/src/main/java/com/cohere/api/types/ChatSearchResult.java @@ -246,7 +246,9 @@ public _FinalStage errorMessage(Optional errorMessage) { */ @java.lang.Override public _FinalStage addAllDocumentIds(List documentIds) { - this.documentIds.addAll(documentIds); + if (documentIds != null) { + this.documentIds.addAll(documentIds); + } return this; } @@ -267,7 +269,9 @@ public _FinalStage addDocumentIds(String documentIds) { @JsonSetter(value = "document_ids", nulls = Nulls.SKIP) public _FinalStage documentIds(List documentIds) { this.documentIds.clear(); - this.documentIds.addAll(documentIds); + if (documentIds != null) { + this.documentIds.addAll(documentIds); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ChatStreamEndEventFinishReason.java b/src/main/java/com/cohere/api/types/ChatStreamEndEventFinishReason.java index 1dd7b70..7ba6115 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamEndEventFinishReason.java +++ b/src/main/java/com/cohere/api/types/ChatStreamEndEventFinishReason.java @@ -3,28 +3,116 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatStreamEndEventFinishReason { - COMPLETE("COMPLETE"), +public final class ChatStreamEndEventFinishReason { + public static final ChatStreamEndEventFinishReason ERROR_LIMIT = + new ChatStreamEndEventFinishReason(Value.ERROR_LIMIT, "ERROR_LIMIT"); - ERROR_LIMIT("ERROR_LIMIT"), + public static final ChatStreamEndEventFinishReason ERROR_TOXIC = + new ChatStreamEndEventFinishReason(Value.ERROR_TOXIC, "ERROR_TOXIC"); - MAX_TOKENS("MAX_TOKENS"), + public static final ChatStreamEndEventFinishReason COMPLETE = + new ChatStreamEndEventFinishReason(Value.COMPLETE, "COMPLETE"); - ERROR("ERROR"), + public static final ChatStreamEndEventFinishReason MAX_TOKENS = + new ChatStreamEndEventFinishReason(Value.MAX_TOKENS, "MAX_TOKENS"); - ERROR_TOXIC("ERROR_TOXIC"); + public static final ChatStreamEndEventFinishReason ERROR = new ChatStreamEndEventFinishReason(Value.ERROR, "ERROR"); - private final String value; + private final Value value; - ChatStreamEndEventFinishReason(String value) { + private final String string; + + ChatStreamEndEventFinishReason(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatStreamEndEventFinishReason + && this.string.equals(((ChatStreamEndEventFinishReason) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ERROR_LIMIT: + return visitor.visitErrorLimit(); + case ERROR_TOXIC: + return visitor.visitErrorToxic(); + case COMPLETE: + return visitor.visitComplete(); + case MAX_TOKENS: + return visitor.visitMaxTokens(); + case ERROR: + return visitor.visitError(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatStreamEndEventFinishReason valueOf(String value) { + switch (value) { + case "ERROR_LIMIT": + return ERROR_LIMIT; + case "ERROR_TOXIC": + return ERROR_TOXIC; + case "COMPLETE": + return COMPLETE; + case "MAX_TOKENS": + return MAX_TOKENS; + case "ERROR": + return ERROR; + default: + return new ChatStreamEndEventFinishReason(Value.UNKNOWN, value); + } + } + + public enum Value { + COMPLETE, + + ERROR_LIMIT, + + MAX_TOKENS, + + ERROR, + + ERROR_TOXIC, + + UNKNOWN + } + + public interface Visitor { + T visitComplete(); + + T visitErrorLimit(); + + T visitMaxTokens(); + + T visitError(); + + T visitErrorToxic(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatStreamRequestCitationQuality.java b/src/main/java/com/cohere/api/types/ChatStreamRequestCitationQuality.java index 3fca8b3..10f3595 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamRequestCitationQuality.java +++ b/src/main/java/com/cohere/api/types/ChatStreamRequestCitationQuality.java @@ -3,24 +3,116 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatStreamRequestCitationQuality { - FAST("fast"), +public final class ChatStreamRequestCitationQuality { + public static final ChatStreamRequestCitationQuality FAST = + new ChatStreamRequestCitationQuality(Value.FAST, "FAST"); - ACCURATE("accurate"), + public static final ChatStreamRequestCitationQuality DISABLED = + new ChatStreamRequestCitationQuality(Value.DISABLED, "DISABLED"); - OFF("off"); + public static final ChatStreamRequestCitationQuality ENABLED = + new ChatStreamRequestCitationQuality(Value.ENABLED, "ENABLED"); - private final String value; + public static final ChatStreamRequestCitationQuality OFF = new ChatStreamRequestCitationQuality(Value.OFF, "OFF"); - ChatStreamRequestCitationQuality(String value) { + public static final ChatStreamRequestCitationQuality ACCURATE = + new ChatStreamRequestCitationQuality(Value.ACCURATE, "ACCURATE"); + + private final Value value; + + private final String string; + + ChatStreamRequestCitationQuality(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatStreamRequestCitationQuality + && this.string.equals(((ChatStreamRequestCitationQuality) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FAST: + return visitor.visitFast(); + case DISABLED: + return visitor.visitDisabled(); + case ENABLED: + return visitor.visitEnabled(); + case OFF: + return visitor.visitOff(); + case ACCURATE: + return visitor.visitAccurate(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatStreamRequestCitationQuality valueOf(String value) { + switch (value) { + case "FAST": + return FAST; + case "DISABLED": + return DISABLED; + case "ENABLED": + return ENABLED; + case "OFF": + return OFF; + case "ACCURATE": + return ACCURATE; + default: + return new ChatStreamRequestCitationQuality(Value.UNKNOWN, value); + } + } + + public enum Value { + ENABLED, + + DISABLED, + + FAST, + + ACCURATE, + + OFF, + + UNKNOWN + } + + public interface Visitor { + T visitEnabled(); + + T visitDisabled(); + + T visitFast(); + + T visitAccurate(); + + T visitOff(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatStreamRequestPromptTruncation.java b/src/main/java/com/cohere/api/types/ChatStreamRequestPromptTruncation.java index 0e9f8e9..7eb1d7e 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamRequestPromptTruncation.java +++ b/src/main/java/com/cohere/api/types/ChatStreamRequestPromptTruncation.java @@ -3,24 +3,94 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatStreamRequestPromptTruncation { - OFF("OFF"), +public final class ChatStreamRequestPromptTruncation { + public static final ChatStreamRequestPromptTruncation AUTO = + new ChatStreamRequestPromptTruncation(Value.AUTO, "AUTO"); - AUTO("AUTO"), + public static final ChatStreamRequestPromptTruncation AUTO_PRESERVE_ORDER = + new ChatStreamRequestPromptTruncation(Value.AUTO_PRESERVE_ORDER, "AUTO_PRESERVE_ORDER"); - AUTO_PRESERVE_ORDER("AUTO_PRESERVE_ORDER"); + public static final ChatStreamRequestPromptTruncation OFF = new ChatStreamRequestPromptTruncation(Value.OFF, "OFF"); - private final String value; + private final Value value; - ChatStreamRequestPromptTruncation(String value) { + private final String string; + + ChatStreamRequestPromptTruncation(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatStreamRequestPromptTruncation + && this.string.equals(((ChatStreamRequestPromptTruncation) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case AUTO: + return visitor.visitAuto(); + case AUTO_PRESERVE_ORDER: + return visitor.visitAutoPreserveOrder(); + case OFF: + return visitor.visitOff(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatStreamRequestPromptTruncation valueOf(String value) { + switch (value) { + case "AUTO": + return AUTO; + case "AUTO_PRESERVE_ORDER": + return AUTO_PRESERVE_ORDER; + case "OFF": + return OFF; + default: + return new ChatStreamRequestPromptTruncation(Value.UNKNOWN, value); + } + } + + public enum Value { + OFF, + + AUTO, + + AUTO_PRESERVE_ORDER, + + UNKNOWN + } + + public interface Visitor { + T visitOff(); + + T visitAuto(); + + T visitAutoPreserveOrder(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatStreamRequestSafetyMode.java b/src/main/java/com/cohere/api/types/ChatStreamRequestSafetyMode.java index ec3f4a9..bc7048a 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamRequestSafetyMode.java +++ b/src/main/java/com/cohere/api/types/ChatStreamRequestSafetyMode.java @@ -3,24 +3,93 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatStreamRequestSafetyMode { - CONTEXTUAL("CONTEXTUAL"), +public final class ChatStreamRequestSafetyMode { + public static final ChatStreamRequestSafetyMode NONE = new ChatStreamRequestSafetyMode(Value.NONE, "NONE"); - STRICT("STRICT"), + public static final ChatStreamRequestSafetyMode STRICT = new ChatStreamRequestSafetyMode(Value.STRICT, "STRICT"); - NONE("NONE"); + public static final ChatStreamRequestSafetyMode CONTEXTUAL = + new ChatStreamRequestSafetyMode(Value.CONTEXTUAL, "CONTEXTUAL"); - private final String value; + private final Value value; - ChatStreamRequestSafetyMode(String value) { + private final String string; + + ChatStreamRequestSafetyMode(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ChatStreamRequestSafetyMode + && this.string.equals(((ChatStreamRequestSafetyMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case NONE: + return visitor.visitNone(); + case STRICT: + return visitor.visitStrict(); + case CONTEXTUAL: + return visitor.visitContextual(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ChatStreamRequestSafetyMode valueOf(String value) { + switch (value) { + case "NONE": + return NONE; + case "STRICT": + return STRICT; + case "CONTEXTUAL": + return CONTEXTUAL; + default: + return new ChatStreamRequestSafetyMode(Value.UNKNOWN, value); + } + } + + public enum Value { + CONTEXTUAL, + + STRICT, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitContextual(); + + T visitStrict(); + + T visitNone(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java b/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java index ebea921..c147064 100644 --- a/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java +++ b/src/main/java/com/cohere/api/types/ChatToolCallsGenerationEvent.java @@ -111,7 +111,9 @@ public Builder text(String text) { @JsonSetter(value = "tool_calls", nulls = Nulls.SKIP) public Builder toolCalls(List toolCalls) { this.toolCalls.clear(); - this.toolCalls.addAll(toolCalls); + if (toolCalls != null) { + this.toolCalls.addAll(toolCalls); + } return this; } @@ -121,7 +123,9 @@ public Builder addToolCalls(ToolCall toolCalls) { } public Builder addAllToolCalls(List toolCalls) { - this.toolCalls.addAll(toolCalls); + if (toolCalls != null) { + this.toolCalls.addAll(toolCalls); + } return this; } diff --git a/src/main/java/com/cohere/api/types/CitationOptions.java b/src/main/java/com/cohere/api/types/CitationOptions.java index f6f2ade..dd7153c 100644 --- a/src/main/java/com/cohere/api/types/CitationOptions.java +++ b/src/main/java/com/cohere/api/types/CitationOptions.java @@ -30,9 +30,8 @@ private CitationOptions(Optional mode, Map } /** - * @return Defaults to "accurate". - * Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results. - *

Note: command-r7b-12-2024 and command-a-03-2025 only support "fast" and "off" modes. The default is "fast".

+ * @return Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled". */ @JsonProperty("mode") public Optional getMode() { @@ -83,9 +82,8 @@ public Builder from(CitationOptions other) { } /** - *

Defaults to "accurate". - * Dictates the approach taken to generating citations as part of the RAG flow by allowing the user to specify whether they want "accurate" results, "fast" results or no results.

- *

Note: command-r7b-12-2024 and command-a-03-2025 only support "fast" and "off" modes. The default is "fast".

+ *

Defaults to "enabled". + * Citations are enabled by default for models that support it, but can be turned off by setting "type": "disabled".

*/ @JsonSetter(value = "mode", nulls = Nulls.SKIP) public Builder mode(Optional mode) { diff --git a/src/main/java/com/cohere/api/types/CitationOptionsMode.java b/src/main/java/com/cohere/api/types/CitationOptionsMode.java index a07df70..2accb45 100644 --- a/src/main/java/com/cohere/api/types/CitationOptionsMode.java +++ b/src/main/java/com/cohere/api/types/CitationOptionsMode.java @@ -3,24 +3,111 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum CitationOptionsMode { - FAST("FAST"), +public final class CitationOptionsMode { + public static final CitationOptionsMode FAST = new CitationOptionsMode(Value.FAST, "FAST"); - ACCURATE("ACCURATE"), + public static final CitationOptionsMode DISABLED = new CitationOptionsMode(Value.DISABLED, "DISABLED"); - OFF("OFF"); + public static final CitationOptionsMode ENABLED = new CitationOptionsMode(Value.ENABLED, "ENABLED"); - private final String value; + public static final CitationOptionsMode OFF = new CitationOptionsMode(Value.OFF, "OFF"); - CitationOptionsMode(String value) { + public static final CitationOptionsMode ACCURATE = new CitationOptionsMode(Value.ACCURATE, "ACCURATE"); + + private final Value value; + + private final String string; + + CitationOptionsMode(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof CitationOptionsMode && this.string.equals(((CitationOptionsMode) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FAST: + return visitor.visitFast(); + case DISABLED: + return visitor.visitDisabled(); + case ENABLED: + return visitor.visitEnabled(); + case OFF: + return visitor.visitOff(); + case ACCURATE: + return visitor.visitAccurate(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static CitationOptionsMode valueOf(String value) { + switch (value) { + case "FAST": + return FAST; + case "DISABLED": + return DISABLED; + case "ENABLED": + return ENABLED; + case "OFF": + return OFF; + case "ACCURATE": + return ACCURATE; + default: + return new CitationOptionsMode(Value.UNKNOWN, value); + } + } + + public enum Value { + ENABLED, + + DISABLED, + + FAST, + + ACCURATE, + + OFF, + + UNKNOWN + } + + public interface Visitor { + T visitEnabled(); + + T visitDisabled(); + + T visitFast(); + + T visitAccurate(); + + T visitOff(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/CitationType.java b/src/main/java/com/cohere/api/types/CitationType.java index 1498629..1c9758a 100644 --- a/src/main/java/com/cohere/api/types/CitationType.java +++ b/src/main/java/com/cohere/api/types/CitationType.java @@ -3,24 +3,90 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum CitationType { - TEXT_CONTENT("TEXT_CONTENT"), +public final class CitationType { + public static final CitationType PLAN = new CitationType(Value.PLAN, "PLAN"); - THINKING_CONTENT("THINKING_CONTENT"), + public static final CitationType TEXT_CONTENT = new CitationType(Value.TEXT_CONTENT, "TEXT_CONTENT"); - PLAN("PLAN"); + public static final CitationType THINKING_CONTENT = new CitationType(Value.THINKING_CONTENT, "THINKING_CONTENT"); - private final String value; + private final Value value; - CitationType(String value) { + private final String string; + + CitationType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof CitationType && this.string.equals(((CitationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case PLAN: + return visitor.visitPlan(); + case TEXT_CONTENT: + return visitor.visitTextContent(); + case THINKING_CONTENT: + return visitor.visitThinkingContent(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static CitationType valueOf(String value) { + switch (value) { + case "PLAN": + return PLAN; + case "TEXT_CONTENT": + return TEXT_CONTENT; + case "THINKING_CONTENT": + return THINKING_CONTENT; + default: + return new CitationType(Value.UNKNOWN, value); + } + } + + public enum Value { + TEXT_CONTENT, + + THINKING_CONTENT, + + PLAN, + + UNKNOWN + } + + public interface Visitor { + T visitTextContent(); + + T visitThinkingContent(); + + T visitPlan(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ClassifyRequestTruncate.java b/src/main/java/com/cohere/api/types/ClassifyRequestTruncate.java index 0065233..4477555 100644 --- a/src/main/java/com/cohere/api/types/ClassifyRequestTruncate.java +++ b/src/main/java/com/cohere/api/types/ClassifyRequestTruncate.java @@ -3,24 +3,92 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ClassifyRequestTruncate { - NONE("NONE"), +public final class ClassifyRequestTruncate { + public static final ClassifyRequestTruncate END = new ClassifyRequestTruncate(Value.END, "END"); - START("START"), + public static final ClassifyRequestTruncate NONE = new ClassifyRequestTruncate(Value.NONE, "NONE"); - END("END"); + public static final ClassifyRequestTruncate START = new ClassifyRequestTruncate(Value.START, "START"); - private final String value; + private final Value value; - ClassifyRequestTruncate(String value) { + private final String string; + + ClassifyRequestTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ClassifyRequestTruncate + && this.string.equals(((ClassifyRequestTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case NONE: + return visitor.visitNone(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ClassifyRequestTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "NONE": + return NONE; + case "START": + return START; + default: + return new ClassifyRequestTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ClassifyResponse.java b/src/main/java/com/cohere/api/types/ClassifyResponse.java index 5482e74..41a9446 100644 --- a/src/main/java/com/cohere/api/types/ClassifyResponse.java +++ b/src/main/java/com/cohere/api/types/ClassifyResponse.java @@ -149,7 +149,9 @@ public _FinalStage meta(Optional meta) { @java.lang.Override public _FinalStage addAllClassifications(List classifications) { - this.classifications.addAll(classifications); + if (classifications != null) { + this.classifications.addAll(classifications); + } return this; } @@ -163,7 +165,9 @@ public _FinalStage addClassifications(ClassifyResponseClassificationsItem classi @JsonSetter(value = "classifications", nulls = Nulls.SKIP) public _FinalStage classifications(List classifications) { this.classifications.clear(); - this.classifications.addAll(classifications); + if (classifications != null) { + this.classifications.addAll(classifications); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java b/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java index b697dae..ae9ebb3 100644 --- a/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java +++ b/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItem.java @@ -307,7 +307,9 @@ public _FinalStage labels(String key, ClassifyResponseClassificationsItemLabelsV */ @java.lang.Override public _FinalStage putAllLabels(Map labels) { - this.labels.putAll(labels); + if (labels != null) { + this.labels.putAll(labels); + } return this; } @@ -318,7 +320,9 @@ public _FinalStage putAllLabels(Map labels) { this.labels.clear(); - this.labels.putAll(labels); + if (labels != null) { + this.labels.putAll(labels); + } return this; } @@ -328,7 +332,9 @@ public _FinalStage labels(Map confidences) { - this.confidences.addAll(confidences); + if (confidences != null) { + this.confidences.addAll(confidences); + } return this; } @@ -349,7 +355,9 @@ public _FinalStage addConfidences(Float confidences) { @JsonSetter(value = "confidences", nulls = Nulls.SKIP) public _FinalStage confidences(List confidences) { this.confidences.clear(); - this.confidences.addAll(confidences); + if (confidences != null) { + this.confidences.addAll(confidences); + } return this; } @@ -379,7 +387,9 @@ public _FinalStage confidence(Optional confidence) { */ @java.lang.Override public _FinalStage addAllPredictions(List predictions) { - this.predictions.addAll(predictions); + if (predictions != null) { + this.predictions.addAll(predictions); + } return this; } @@ -400,7 +410,9 @@ public _FinalStage addPredictions(String predictions) { @JsonSetter(value = "predictions", nulls = Nulls.SKIP) public _FinalStage predictions(List predictions) { this.predictions.clear(); - this.predictions.addAll(predictions); + if (predictions != null) { + this.predictions.addAll(predictions); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItemClassificationType.java b/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItemClassificationType.java index 3ffff13..a7170b5 100644 --- a/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItemClassificationType.java +++ b/src/main/java/com/cohere/api/types/ClassifyResponseClassificationsItemClassificationType.java @@ -3,22 +3,84 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ClassifyResponseClassificationsItemClassificationType { - SINGLE_LABEL("single-label"), +public final class ClassifyResponseClassificationsItemClassificationType { + public static final ClassifyResponseClassificationsItemClassificationType MULTI_LABEL = + new ClassifyResponseClassificationsItemClassificationType(Value.MULTI_LABEL, "multi-label"); - MULTI_LABEL("multi-label"); + public static final ClassifyResponseClassificationsItemClassificationType SINGLE_LABEL = + new ClassifyResponseClassificationsItemClassificationType(Value.SINGLE_LABEL, "single-label"); - private final String value; + private final Value value; - ClassifyResponseClassificationsItemClassificationType(String value) { + private final String string; + + ClassifyResponseClassificationsItemClassificationType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ClassifyResponseClassificationsItemClassificationType + && this.string.equals(((ClassifyResponseClassificationsItemClassificationType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case MULTI_LABEL: + return visitor.visitMultiLabel(); + case SINGLE_LABEL: + return visitor.visitSingleLabel(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ClassifyResponseClassificationsItemClassificationType valueOf(String value) { + switch (value) { + case "multi-label": + return MULTI_LABEL; + case "single-label": + return SINGLE_LABEL; + default: + return new ClassifyResponseClassificationsItemClassificationType(Value.UNKNOWN, value); + } + } + + public enum Value { + SINGLE_LABEL, + + MULTI_LABEL, + + UNKNOWN + } + + public interface Visitor { + T visitSingleLabel(); + + T visitMultiLabel(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/CompatibleEndpoint.java b/src/main/java/com/cohere/api/types/CompatibleEndpoint.java index 215e96c..9825202 100644 --- a/src/main/java/com/cohere/api/types/CompatibleEndpoint.java +++ b/src/main/java/com/cohere/api/types/CompatibleEndpoint.java @@ -3,32 +3,131 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum CompatibleEndpoint { - CHAT("chat"), +public final class CompatibleEndpoint { + public static final CompatibleEndpoint EMBED = new CompatibleEndpoint(Value.EMBED, "embed"); - EMBED("embed"), + public static final CompatibleEndpoint RERANK = new CompatibleEndpoint(Value.RERANK, "rerank"); - CLASSIFY("classify"), + public static final CompatibleEndpoint GENERATE = new CompatibleEndpoint(Value.GENERATE, "generate"); - SUMMARIZE("summarize"), + public static final CompatibleEndpoint SUMMARIZE = new CompatibleEndpoint(Value.SUMMARIZE, "summarize"); - RERANK("rerank"), + public static final CompatibleEndpoint CLASSIFY = new CompatibleEndpoint(Value.CLASSIFY, "classify"); - RATE("rate"), + public static final CompatibleEndpoint RATE = new CompatibleEndpoint(Value.RATE, "rate"); - GENERATE("generate"); + public static final CompatibleEndpoint CHAT = new CompatibleEndpoint(Value.CHAT, "chat"); - private final String value; + private final Value value; - CompatibleEndpoint(String value) { + private final String string; + + CompatibleEndpoint(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof CompatibleEndpoint && this.string.equals(((CompatibleEndpoint) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case EMBED: + return visitor.visitEmbed(); + case RERANK: + return visitor.visitRerank(); + case GENERATE: + return visitor.visitGenerate(); + case SUMMARIZE: + return visitor.visitSummarize(); + case CLASSIFY: + return visitor.visitClassify(); + case RATE: + return visitor.visitRate(); + case CHAT: + return visitor.visitChat(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static CompatibleEndpoint valueOf(String value) { + switch (value) { + case "embed": + return EMBED; + case "rerank": + return RERANK; + case "generate": + return GENERATE; + case "summarize": + return SUMMARIZE; + case "classify": + return CLASSIFY; + case "rate": + return RATE; + case "chat": + return CHAT; + default: + return new CompatibleEndpoint(Value.UNKNOWN, value); + } + } + + public enum Value { + CHAT, + + EMBED, + + CLASSIFY, + + SUMMARIZE, + + RERANK, + + RATE, + + GENERATE, + + UNKNOWN + } + + public interface Visitor { + T visitChat(); + + T visitEmbed(); + + T visitClassify(); + + T visitSummarize(); + + T visitRerank(); + + T visitRate(); + + T visitGenerate(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ConnectorAuthStatus.java b/src/main/java/com/cohere/api/types/ConnectorAuthStatus.java index 2f0a4f1..e06081c 100644 --- a/src/main/java/com/cohere/api/types/ConnectorAuthStatus.java +++ b/src/main/java/com/cohere/api/types/ConnectorAuthStatus.java @@ -3,22 +3,81 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ConnectorAuthStatus { - VALID("valid"), +public final class ConnectorAuthStatus { + public static final ConnectorAuthStatus EXPIRED = new ConnectorAuthStatus(Value.EXPIRED, "expired"); - EXPIRED("expired"); + public static final ConnectorAuthStatus VALID = new ConnectorAuthStatus(Value.VALID, "valid"); - private final String value; + private final Value value; - ConnectorAuthStatus(String value) { + private final String string; + + ConnectorAuthStatus(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ConnectorAuthStatus && this.string.equals(((ConnectorAuthStatus) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case EXPIRED: + return visitor.visitExpired(); + case VALID: + return visitor.visitValid(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ConnectorAuthStatus valueOf(String value) { + switch (value) { + case "expired": + return EXPIRED; + case "valid": + return VALID; + default: + return new ConnectorAuthStatus(Value.UNKNOWN, value); + } + } + + public enum Value { + VALID, + + EXPIRED, + + UNKNOWN + } + + public interface Visitor { + T visitValid(); + + T visitExpired(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/DatasetType.java b/src/main/java/com/cohere/api/types/DatasetType.java index a2dc4e7..fb510c4 100644 --- a/src/main/java/com/cohere/api/types/DatasetType.java +++ b/src/main/java/com/cohere/api/types/DatasetType.java @@ -3,34 +3,187 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum DatasetType { - EMBED_INPUT("embed-input"), +public final class DatasetType { + public static final DatasetType EMBED_INPUT = new DatasetType(Value.EMBED_INPUT, "embed-input"); - EMBED_RESULT("embed-result"), + public static final DatasetType SINGLE_LABEL_CLASSIFICATION_FINETUNE_INPUT = new DatasetType( + Value.SINGLE_LABEL_CLASSIFICATION_FINETUNE_INPUT, "single-label-classification-finetune-input"); - CLUSTER_RESULT("cluster-result"), + public static final DatasetType EMBED_RESULT = new DatasetType(Value.EMBED_RESULT, "embed-result"); - CLUSTER_OUTLIERS("cluster-outliers"), + public static final DatasetType BATCH_CHAT_INPUT = new DatasetType(Value.BATCH_CHAT_INPUT, "batch-chat-input"); - RERANKER_FINETUNE_INPUT("reranker-finetune-input"), + public static final DatasetType BATCH_OPENAI_CHAT_INPUT = + new DatasetType(Value.BATCH_OPENAI_CHAT_INPUT, "batch-openai-chat-input"); - SINGLE_LABEL_CLASSIFICATION_FINETUNE_INPUT("single-label-classification-finetune-input"), + public static final DatasetType MULTI_LABEL_CLASSIFICATION_FINETUNE_INPUT = new DatasetType( + Value.MULTI_LABEL_CLASSIFICATION_FINETUNE_INPUT, "multi-label-classification-finetune-input"); - CHAT_FINETUNE_INPUT("chat-finetune-input"), + public static final DatasetType RERANKER_FINETUNE_INPUT = + new DatasetType(Value.RERANKER_FINETUNE_INPUT, "reranker-finetune-input"); - MULTI_LABEL_CLASSIFICATION_FINETUNE_INPUT("multi-label-classification-finetune-input"); + public static final DatasetType BATCH_EMBED_V_2_INPUT = + new DatasetType(Value.BATCH_EMBED_V_2_INPUT, "batch-embed-v2-input"); - private final String value; + public static final DatasetType BATCH_CHAT_V_2_INPUT = + new DatasetType(Value.BATCH_CHAT_V_2_INPUT, "batch-chat-v2-input"); - DatasetType(String value) { + public static final DatasetType CLUSTER_RESULT = new DatasetType(Value.CLUSTER_RESULT, "cluster-result"); + + public static final DatasetType CLUSTER_OUTLIERS = new DatasetType(Value.CLUSTER_OUTLIERS, "cluster-outliers"); + + public static final DatasetType CHAT_FINETUNE_INPUT = + new DatasetType(Value.CHAT_FINETUNE_INPUT, "chat-finetune-input"); + + private final Value value; + + private final String string; + + DatasetType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof DatasetType && this.string.equals(((DatasetType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case EMBED_INPUT: + return visitor.visitEmbedInput(); + case SINGLE_LABEL_CLASSIFICATION_FINETUNE_INPUT: + return visitor.visitSingleLabelClassificationFinetuneInput(); + case EMBED_RESULT: + return visitor.visitEmbedResult(); + case BATCH_CHAT_INPUT: + return visitor.visitBatchChatInput(); + case BATCH_OPENAI_CHAT_INPUT: + return visitor.visitBatchOpenaiChatInput(); + case MULTI_LABEL_CLASSIFICATION_FINETUNE_INPUT: + return visitor.visitMultiLabelClassificationFinetuneInput(); + case RERANKER_FINETUNE_INPUT: + return visitor.visitRerankerFinetuneInput(); + case BATCH_EMBED_V_2_INPUT: + return visitor.visitBatchEmbedV2Input(); + case BATCH_CHAT_V_2_INPUT: + return visitor.visitBatchChatV2Input(); + case CLUSTER_RESULT: + return visitor.visitClusterResult(); + case CLUSTER_OUTLIERS: + return visitor.visitClusterOutliers(); + case CHAT_FINETUNE_INPUT: + return visitor.visitChatFinetuneInput(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DatasetType valueOf(String value) { + switch (value) { + case "embed-input": + return EMBED_INPUT; + case "single-label-classification-finetune-input": + return SINGLE_LABEL_CLASSIFICATION_FINETUNE_INPUT; + case "embed-result": + return EMBED_RESULT; + case "batch-chat-input": + return BATCH_CHAT_INPUT; + case "batch-openai-chat-input": + return BATCH_OPENAI_CHAT_INPUT; + case "multi-label-classification-finetune-input": + return MULTI_LABEL_CLASSIFICATION_FINETUNE_INPUT; + case "reranker-finetune-input": + return RERANKER_FINETUNE_INPUT; + case "batch-embed-v2-input": + return BATCH_EMBED_V_2_INPUT; + case "batch-chat-v2-input": + return BATCH_CHAT_V_2_INPUT; + case "cluster-result": + return CLUSTER_RESULT; + case "cluster-outliers": + return CLUSTER_OUTLIERS; + case "chat-finetune-input": + return CHAT_FINETUNE_INPUT; + default: + return new DatasetType(Value.UNKNOWN, value); + } + } + + public enum Value { + EMBED_INPUT, + + EMBED_RESULT, + + CLUSTER_RESULT, + + CLUSTER_OUTLIERS, + + RERANKER_FINETUNE_INPUT, + + SINGLE_LABEL_CLASSIFICATION_FINETUNE_INPUT, + + CHAT_FINETUNE_INPUT, + + MULTI_LABEL_CLASSIFICATION_FINETUNE_INPUT, + + BATCH_CHAT_INPUT, + + BATCH_OPENAI_CHAT_INPUT, + + BATCH_EMBED_V_2_INPUT, + + BATCH_CHAT_V_2_INPUT, + + UNKNOWN + } + + public interface Visitor { + T visitEmbedInput(); + + T visitEmbedResult(); + + T visitClusterResult(); + + T visitClusterOutliers(); + + T visitRerankerFinetuneInput(); + + T visitSingleLabelClassificationFinetuneInput(); + + T visitChatFinetuneInput(); + + T visitMultiLabelClassificationFinetuneInput(); + + T visitBatchChatInput(); + + T visitBatchOpenaiChatInput(); + + T visitBatchEmbedV2Input(); + + T visitBatchChatV2Input(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/DatasetValidationStatus.java b/src/main/java/com/cohere/api/types/DatasetValidationStatus.java index 5b041aa..8c922b6 100644 --- a/src/main/java/com/cohere/api/types/DatasetValidationStatus.java +++ b/src/main/java/com/cohere/api/types/DatasetValidationStatus.java @@ -3,30 +3,123 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum DatasetValidationStatus { - UNKNOWN("unknown"), +public final class DatasetValidationStatus { + public static final DatasetValidationStatus SKIPPED = new DatasetValidationStatus(Value.SKIPPED, "skipped"); - QUEUED("queued"), + public static final DatasetValidationStatus FAILED = new DatasetValidationStatus(Value.FAILED, "failed"); - PROCESSING("processing"), + public static final DatasetValidationStatus UNKNOWN = new DatasetValidationStatus(Value.UNKNOWN, "unknown"); - FAILED("failed"), + public static final DatasetValidationStatus PROCESSING = + new DatasetValidationStatus(Value.PROCESSING, "processing"); - VALIDATED("validated"), + public static final DatasetValidationStatus QUEUED = new DatasetValidationStatus(Value.QUEUED, "queued"); - SKIPPED("skipped"); + public static final DatasetValidationStatus VALIDATED = new DatasetValidationStatus(Value.VALIDATED, "validated"); - private final String value; + private final Value value; - DatasetValidationStatus(String value) { + private final String string; + + DatasetValidationStatus(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof DatasetValidationStatus + && this.string.equals(((DatasetValidationStatus) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case SKIPPED: + return visitor.visitSkipped(); + case FAILED: + return visitor.visitFailed(); + case UNKNOWN: + return visitor.visitUnknown(); + case PROCESSING: + return visitor.visitProcessing(); + case QUEUED: + return visitor.visitQueued(); + case VALIDATED: + return visitor.visitValidated(); + case _UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static DatasetValidationStatus valueOf(String value) { + switch (value) { + case "skipped": + return SKIPPED; + case "failed": + return FAILED; + case "unknown": + return UNKNOWN; + case "processing": + return PROCESSING; + case "queued": + return QUEUED; + case "validated": + return VALIDATED; + default: + return new DatasetValidationStatus(Value._UNKNOWN, value); + } + } + + public enum Value { + UNKNOWN, + + QUEUED, + + PROCESSING, + + FAILED, + + VALIDATED, + + SKIPPED, + + _UNKNOWN + } + + public interface Visitor { + T visitUnknown(); + + T visitQueued(); + + T visitProcessing(); + + T visitFailed(); + + T visitValidated(); + + T visitSkipped(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/Document.java b/src/main/java/com/cohere/api/types/Document.java index 07e618d..9e1367a 100644 --- a/src/main/java/com/cohere/api/types/Document.java +++ b/src/main/java/com/cohere/api/types/Document.java @@ -101,12 +101,16 @@ public Builder from(Document other) { @JsonSetter(value = "data", nulls = Nulls.SKIP) public Builder data(Map data) { this.data.clear(); - this.data.putAll(data); + if (data != null) { + this.data.putAll(data); + } return this; } public Builder putAllData(Map data) { - this.data.putAll(data); + if (data != null) { + this.data.putAll(data); + } return this; } diff --git a/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java b/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java index bb95964..01e2042 100644 --- a/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java +++ b/src/main/java/com/cohere/api/types/EmbedFloatsResponse.java @@ -229,7 +229,9 @@ public _FinalStage images(Optional> images) { */ @java.lang.Override public _FinalStage addAllTexts(List texts) { - this.texts.addAll(texts); + if (texts != null) { + this.texts.addAll(texts); + } return this; } @@ -250,7 +252,9 @@ public _FinalStage addTexts(String texts) { @JsonSetter(value = "texts", nulls = Nulls.SKIP) public _FinalStage texts(List texts) { this.texts.clear(); - this.texts.addAll(texts); + if (texts != null) { + this.texts.addAll(texts); + } return this; } @@ -260,7 +264,9 @@ public _FinalStage texts(List texts) { */ @java.lang.Override public _FinalStage addAllEmbeddings(List> embeddings) { - this.embeddings.addAll(embeddings); + if (embeddings != null) { + this.embeddings.addAll(embeddings); + } return this; } @@ -281,7 +287,9 @@ public _FinalStage addEmbeddings(List embeddings) { @JsonSetter(value = "embeddings", nulls = Nulls.SKIP) public _FinalStage embeddings(List> embeddings) { this.embeddings.clear(); - this.embeddings.addAll(embeddings); + if (embeddings != null) { + this.embeddings.addAll(embeddings); + } return this; } diff --git a/src/main/java/com/cohere/api/types/EmbedInput.java b/src/main/java/com/cohere/api/types/EmbedInput.java index 8f4898f..b41d426 100644 --- a/src/main/java/com/cohere/api/types/EmbedInput.java +++ b/src/main/java/com/cohere/api/types/EmbedInput.java @@ -87,7 +87,9 @@ public Builder from(EmbedInput other) { @JsonSetter(value = "content", nulls = Nulls.SKIP) public Builder content(List content) { this.content.clear(); - this.content.addAll(content); + if (content != null) { + this.content.addAll(content); + } return this; } @@ -97,7 +99,9 @@ public Builder addContent(EmbedContent content) { } public Builder addAllContent(List content) { - this.content.addAll(content); + if (content != null) { + this.content.addAll(content); + } return this; } diff --git a/src/main/java/com/cohere/api/types/EmbedInputType.java b/src/main/java/com/cohere/api/types/EmbedInputType.java index 305319a..bf9336b 100644 --- a/src/main/java/com/cohere/api/types/EmbedInputType.java +++ b/src/main/java/com/cohere/api/types/EmbedInputType.java @@ -3,28 +3,111 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum EmbedInputType { - SEARCH_DOCUMENT("search_document"), +public final class EmbedInputType { + public static final EmbedInputType SEARCH_QUERY = new EmbedInputType(Value.SEARCH_QUERY, "search_query"); - SEARCH_QUERY("search_query"), + public static final EmbedInputType SEARCH_DOCUMENT = new EmbedInputType(Value.SEARCH_DOCUMENT, "search_document"); - CLASSIFICATION("classification"), + public static final EmbedInputType CLUSTERING = new EmbedInputType(Value.CLUSTERING, "clustering"); - CLUSTERING("clustering"), + public static final EmbedInputType IMAGE = new EmbedInputType(Value.IMAGE, "image"); - IMAGE("image"); + public static final EmbedInputType CLASSIFICATION = new EmbedInputType(Value.CLASSIFICATION, "classification"); - private final String value; + private final Value value; - EmbedInputType(String value) { + private final String string; + + EmbedInputType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof EmbedInputType && this.string.equals(((EmbedInputType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case SEARCH_QUERY: + return visitor.visitSearchQuery(); + case SEARCH_DOCUMENT: + return visitor.visitSearchDocument(); + case CLUSTERING: + return visitor.visitClustering(); + case IMAGE: + return visitor.visitImage(); + case CLASSIFICATION: + return visitor.visitClassification(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static EmbedInputType valueOf(String value) { + switch (value) { + case "search_query": + return SEARCH_QUERY; + case "search_document": + return SEARCH_DOCUMENT; + case "clustering": + return CLUSTERING; + case "image": + return IMAGE; + case "classification": + return CLASSIFICATION; + default: + return new EmbedInputType(Value.UNKNOWN, value); + } + } + + public enum Value { + SEARCH_DOCUMENT, + + SEARCH_QUERY, + + CLASSIFICATION, + + CLUSTERING, + + IMAGE, + + UNKNOWN + } + + public interface Visitor { + T visitSearchDocument(); + + T visitSearchQuery(); + + T visitClassification(); + + T visitClustering(); + + T visitImage(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/EmbedJobStatus.java b/src/main/java/com/cohere/api/types/EmbedJobStatus.java index b24b7f1..834bd84 100644 --- a/src/main/java/com/cohere/api/types/EmbedJobStatus.java +++ b/src/main/java/com/cohere/api/types/EmbedJobStatus.java @@ -3,28 +3,111 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum EmbedJobStatus { - PROCESSING("processing"), +public final class EmbedJobStatus { + public static final EmbedJobStatus FAILED = new EmbedJobStatus(Value.FAILED, "failed"); - COMPLETE("complete"), + public static final EmbedJobStatus COMPLETE = new EmbedJobStatus(Value.COMPLETE, "complete"); - CANCELLING("cancelling"), + public static final EmbedJobStatus PROCESSING = new EmbedJobStatus(Value.PROCESSING, "processing"); - CANCELLED("cancelled"), + public static final EmbedJobStatus CANCELLING = new EmbedJobStatus(Value.CANCELLING, "cancelling"); - FAILED("failed"); + public static final EmbedJobStatus CANCELLED = new EmbedJobStatus(Value.CANCELLED, "cancelled"); - private final String value; + private final Value value; - EmbedJobStatus(String value) { + private final String string; + + EmbedJobStatus(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof EmbedJobStatus && this.string.equals(((EmbedJobStatus) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FAILED: + return visitor.visitFailed(); + case COMPLETE: + return visitor.visitComplete(); + case PROCESSING: + return visitor.visitProcessing(); + case CANCELLING: + return visitor.visitCancelling(); + case CANCELLED: + return visitor.visitCancelled(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static EmbedJobStatus valueOf(String value) { + switch (value) { + case "failed": + return FAILED; + case "complete": + return COMPLETE; + case "processing": + return PROCESSING; + case "cancelling": + return CANCELLING; + case "cancelled": + return CANCELLED; + default: + return new EmbedJobStatus(Value.UNKNOWN, value); + } + } + + public enum Value { + PROCESSING, + + COMPLETE, + + CANCELLING, + + CANCELLED, + + FAILED, + + UNKNOWN + } + + public interface Visitor { + T visitProcessing(); + + T visitComplete(); + + T visitCancelling(); + + T visitCancelled(); + + T visitFailed(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/EmbedJobTruncate.java b/src/main/java/com/cohere/api/types/EmbedJobTruncate.java index 8309552..54702ea 100644 --- a/src/main/java/com/cohere/api/types/EmbedJobTruncate.java +++ b/src/main/java/com/cohere/api/types/EmbedJobTruncate.java @@ -3,22 +3,81 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum EmbedJobTruncate { - START("START"), +public final class EmbedJobTruncate { + public static final EmbedJobTruncate END = new EmbedJobTruncate(Value.END, "END"); - END("END"); + public static final EmbedJobTruncate START = new EmbedJobTruncate(Value.START, "START"); - private final String value; + private final Value value; - EmbedJobTruncate(String value) { + private final String string; + + EmbedJobTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof EmbedJobTruncate && this.string.equals(((EmbedJobTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static EmbedJobTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "START": + return START; + default: + return new EmbedJobTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/EmbedRequestTruncate.java b/src/main/java/com/cohere/api/types/EmbedRequestTruncate.java index 9475444..b411b31 100644 --- a/src/main/java/com/cohere/api/types/EmbedRequestTruncate.java +++ b/src/main/java/com/cohere/api/types/EmbedRequestTruncate.java @@ -3,24 +3,91 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum EmbedRequestTruncate { - NONE("NONE"), +public final class EmbedRequestTruncate { + public static final EmbedRequestTruncate END = new EmbedRequestTruncate(Value.END, "END"); - START("START"), + public static final EmbedRequestTruncate NONE = new EmbedRequestTruncate(Value.NONE, "NONE"); - END("END"); + public static final EmbedRequestTruncate START = new EmbedRequestTruncate(Value.START, "START"); - private final String value; + private final Value value; - EmbedRequestTruncate(String value) { + private final String string; + + EmbedRequestTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof EmbedRequestTruncate && this.string.equals(((EmbedRequestTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case NONE: + return visitor.visitNone(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static EmbedRequestTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "NONE": + return NONE; + case "START": + return START; + default: + return new EmbedRequestTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/EmbeddingType.java b/src/main/java/com/cohere/api/types/EmbeddingType.java index daa98e1..741c788 100644 --- a/src/main/java/com/cohere/api/types/EmbeddingType.java +++ b/src/main/java/com/cohere/api/types/EmbeddingType.java @@ -3,30 +3,121 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum EmbeddingType { - FLOAT("float"), +public final class EmbeddingType { + public static final EmbeddingType FLOAT = new EmbeddingType(Value.FLOAT, "float"); - INT_8("int8"), + public static final EmbeddingType BASE_64 = new EmbeddingType(Value.BASE_64, "base64"); - UINT_8("uint8"), + public static final EmbeddingType BINARY = new EmbeddingType(Value.BINARY, "binary"); - BINARY("binary"), + public static final EmbeddingType UINT_8 = new EmbeddingType(Value.UINT_8, "uint8"); - UBINARY("ubinary"), + public static final EmbeddingType UBINARY = new EmbeddingType(Value.UBINARY, "ubinary"); - BASE_64("base64"); + public static final EmbeddingType INT_8 = new EmbeddingType(Value.INT_8, "int8"); - private final String value; + private final Value value; - EmbeddingType(String value) { + private final String string; + + EmbeddingType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof EmbeddingType && this.string.equals(((EmbeddingType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case FLOAT: + return visitor.visitFloat(); + case BASE_64: + return visitor.visitBase64(); + case BINARY: + return visitor.visitBinary(); + case UINT_8: + return visitor.visitUint8(); + case UBINARY: + return visitor.visitUbinary(); + case INT_8: + return visitor.visitInt8(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static EmbeddingType valueOf(String value) { + switch (value) { + case "float": + return FLOAT; + case "base64": + return BASE_64; + case "binary": + return BINARY; + case "uint8": + return UINT_8; + case "ubinary": + return UBINARY; + case "int8": + return INT_8; + default: + return new EmbeddingType(Value.UNKNOWN, value); + } + } + + public enum Value { + FLOAT, + + INT_8, + + UINT_8, + + BINARY, + + UBINARY, + + BASE_64, + + UNKNOWN + } + + public interface Visitor { + T visitFloat(); + + T visitInt8(); + + T visitUint8(); + + T visitBinary(); + + T visitUbinary(); + + T visitBase64(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/FinishReason.java b/src/main/java/com/cohere/api/types/FinishReason.java index 951b334..d46a06b 100644 --- a/src/main/java/com/cohere/api/types/FinishReason.java +++ b/src/main/java/com/cohere/api/types/FinishReason.java @@ -3,32 +3,140 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum FinishReason { - COMPLETE("COMPLETE"), +public final class FinishReason { + public static final FinishReason ERROR_TOXIC = new FinishReason(Value.ERROR_TOXIC, "ERROR_TOXIC"); - STOP_SEQUENCE("STOP_SEQUENCE"), + public static final FinishReason ERROR_LIMIT = new FinishReason(Value.ERROR_LIMIT, "ERROR_LIMIT"); - ERROR("ERROR"), + public static final FinishReason STOP_SEQUENCE = new FinishReason(Value.STOP_SEQUENCE, "STOP_SEQUENCE"); - ERROR_TOXIC("ERROR_TOXIC"), + public static final FinishReason USER_CANCEL = new FinishReason(Value.USER_CANCEL, "USER_CANCEL"); - ERROR_LIMIT("ERROR_LIMIT"), + public static final FinishReason TIMEOUT = new FinishReason(Value.TIMEOUT, "TIMEOUT"); - USER_CANCEL("USER_CANCEL"), + public static final FinishReason COMPLETE = new FinishReason(Value.COMPLETE, "COMPLETE"); - MAX_TOKENS("MAX_TOKENS"); + public static final FinishReason MAX_TOKENS = new FinishReason(Value.MAX_TOKENS, "MAX_TOKENS"); - private final String value; + public static final FinishReason ERROR = new FinishReason(Value.ERROR, "ERROR"); - FinishReason(String value) { + private final Value value; + + private final String string; + + FinishReason(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof FinishReason && this.string.equals(((FinishReason) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ERROR_TOXIC: + return visitor.visitErrorToxic(); + case ERROR_LIMIT: + return visitor.visitErrorLimit(); + case STOP_SEQUENCE: + return visitor.visitStopSequence(); + case USER_CANCEL: + return visitor.visitUserCancel(); + case TIMEOUT: + return visitor.visitTimeout(); + case COMPLETE: + return visitor.visitComplete(); + case MAX_TOKENS: + return visitor.visitMaxTokens(); + case ERROR: + return visitor.visitError(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static FinishReason valueOf(String value) { + switch (value) { + case "ERROR_TOXIC": + return ERROR_TOXIC; + case "ERROR_LIMIT": + return ERROR_LIMIT; + case "STOP_SEQUENCE": + return STOP_SEQUENCE; + case "USER_CANCEL": + return USER_CANCEL; + case "TIMEOUT": + return TIMEOUT; + case "COMPLETE": + return COMPLETE; + case "MAX_TOKENS": + return MAX_TOKENS; + case "ERROR": + return ERROR; + default: + return new FinishReason(Value.UNKNOWN, value); + } + } + + public enum Value { + COMPLETE, + + STOP_SEQUENCE, + + ERROR, + + ERROR_TOXIC, + + ERROR_LIMIT, + + USER_CANCEL, + + MAX_TOKENS, + + TIMEOUT, + + UNKNOWN + } + + public interface Visitor { + T visitComplete(); + + T visitStopSequence(); + + T visitError(); + + T visitErrorToxic(); + + T visitErrorLimit(); + + T visitUserCancel(); + + T visitMaxTokens(); + + T visitTimeout(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/GenerateRequestReturnLikelihoods.java b/src/main/java/com/cohere/api/types/GenerateRequestReturnLikelihoods.java index 1e1f986..8258b92 100644 --- a/src/main/java/com/cohere/api/types/GenerateRequestReturnLikelihoods.java +++ b/src/main/java/com/cohere/api/types/GenerateRequestReturnLikelihoods.java @@ -3,24 +3,94 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum GenerateRequestReturnLikelihoods { - GENERATION("GENERATION"), +public final class GenerateRequestReturnLikelihoods { + public static final GenerateRequestReturnLikelihoods ALL = new GenerateRequestReturnLikelihoods(Value.ALL, "ALL"); - ALL("ALL"), + public static final GenerateRequestReturnLikelihoods NONE = + new GenerateRequestReturnLikelihoods(Value.NONE, "NONE"); - NONE("NONE"); + public static final GenerateRequestReturnLikelihoods GENERATION = + new GenerateRequestReturnLikelihoods(Value.GENERATION, "GENERATION"); - private final String value; + private final Value value; - GenerateRequestReturnLikelihoods(String value) { + private final String string; + + GenerateRequestReturnLikelihoods(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GenerateRequestReturnLikelihoods + && this.string.equals(((GenerateRequestReturnLikelihoods) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ALL: + return visitor.visitAll(); + case NONE: + return visitor.visitNone(); + case GENERATION: + return visitor.visitGeneration(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GenerateRequestReturnLikelihoods valueOf(String value) { + switch (value) { + case "ALL": + return ALL; + case "NONE": + return NONE; + case "GENERATION": + return GENERATION; + default: + return new GenerateRequestReturnLikelihoods(Value.UNKNOWN, value); + } + } + + public enum Value { + GENERATION, + + ALL, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitGeneration(); + + T visitAll(); + + T visitNone(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/GenerateRequestTruncate.java b/src/main/java/com/cohere/api/types/GenerateRequestTruncate.java index 2e1dc45..00ca8e0 100644 --- a/src/main/java/com/cohere/api/types/GenerateRequestTruncate.java +++ b/src/main/java/com/cohere/api/types/GenerateRequestTruncate.java @@ -3,24 +3,92 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum GenerateRequestTruncate { - NONE("NONE"), +public final class GenerateRequestTruncate { + public static final GenerateRequestTruncate END = new GenerateRequestTruncate(Value.END, "END"); - START("START"), + public static final GenerateRequestTruncate NONE = new GenerateRequestTruncate(Value.NONE, "NONE"); - END("END"); + public static final GenerateRequestTruncate START = new GenerateRequestTruncate(Value.START, "START"); - private final String value; + private final Value value; - GenerateRequestTruncate(String value) { + private final String string; + + GenerateRequestTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GenerateRequestTruncate + && this.string.equals(((GenerateRequestTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case NONE: + return visitor.visitNone(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GenerateRequestTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "NONE": + return NONE; + case "START": + return START; + default: + return new GenerateRequestTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/GenerateStreamRequestReturnLikelihoods.java b/src/main/java/com/cohere/api/types/GenerateStreamRequestReturnLikelihoods.java index face700..00b42ab 100644 --- a/src/main/java/com/cohere/api/types/GenerateStreamRequestReturnLikelihoods.java +++ b/src/main/java/com/cohere/api/types/GenerateStreamRequestReturnLikelihoods.java @@ -3,24 +3,95 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum GenerateStreamRequestReturnLikelihoods { - GENERATION("GENERATION"), +public final class GenerateStreamRequestReturnLikelihoods { + public static final GenerateStreamRequestReturnLikelihoods ALL = + new GenerateStreamRequestReturnLikelihoods(Value.ALL, "ALL"); - ALL("ALL"), + public static final GenerateStreamRequestReturnLikelihoods NONE = + new GenerateStreamRequestReturnLikelihoods(Value.NONE, "NONE"); - NONE("NONE"); + public static final GenerateStreamRequestReturnLikelihoods GENERATION = + new GenerateStreamRequestReturnLikelihoods(Value.GENERATION, "GENERATION"); - private final String value; + private final Value value; - GenerateStreamRequestReturnLikelihoods(String value) { + private final String string; + + GenerateStreamRequestReturnLikelihoods(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GenerateStreamRequestReturnLikelihoods + && this.string.equals(((GenerateStreamRequestReturnLikelihoods) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ALL: + return visitor.visitAll(); + case NONE: + return visitor.visitNone(); + case GENERATION: + return visitor.visitGeneration(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GenerateStreamRequestReturnLikelihoods valueOf(String value) { + switch (value) { + case "ALL": + return ALL; + case "NONE": + return NONE; + case "GENERATION": + return GENERATION; + default: + return new GenerateStreamRequestReturnLikelihoods(Value.UNKNOWN, value); + } + } + + public enum Value { + GENERATION, + + ALL, + + NONE, + + UNKNOWN + } + + public interface Visitor { + T visitGeneration(); + + T visitAll(); + + T visitNone(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/GenerateStreamRequestTruncate.java b/src/main/java/com/cohere/api/types/GenerateStreamRequestTruncate.java index cefed5a..83c834f 100644 --- a/src/main/java/com/cohere/api/types/GenerateStreamRequestTruncate.java +++ b/src/main/java/com/cohere/api/types/GenerateStreamRequestTruncate.java @@ -3,24 +3,92 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum GenerateStreamRequestTruncate { - NONE("NONE"), +public final class GenerateStreamRequestTruncate { + public static final GenerateStreamRequestTruncate END = new GenerateStreamRequestTruncate(Value.END, "END"); - START("START"), + public static final GenerateStreamRequestTruncate NONE = new GenerateStreamRequestTruncate(Value.NONE, "NONE"); - END("END"); + public static final GenerateStreamRequestTruncate START = new GenerateStreamRequestTruncate(Value.START, "START"); - private final String value; + private final Value value; - GenerateStreamRequestTruncate(String value) { + private final String string; + + GenerateStreamRequestTruncate(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof GenerateStreamRequestTruncate + && this.string.equals(((GenerateStreamRequestTruncate) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case END: + return visitor.visitEnd(); + case NONE: + return visitor.visitNone(); + case START: + return visitor.visitStart(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static GenerateStreamRequestTruncate valueOf(String value) { + switch (value) { + case "END": + return END; + case "NONE": + return NONE; + case "START": + return START; + default: + return new GenerateStreamRequestTruncate(Value.UNKNOWN, value); + } + } + + public enum Value { + NONE, + + START, + + END, + + UNKNOWN + } + + public interface Visitor { + T visitNone(); + + T visitStart(); + + T visitEnd(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/Generation.java b/src/main/java/com/cohere/api/types/Generation.java index 543aa4e..31799f7 100644 --- a/src/main/java/com/cohere/api/types/Generation.java +++ b/src/main/java/com/cohere/api/types/Generation.java @@ -184,7 +184,9 @@ public _FinalStage meta(Optional meta) { */ @java.lang.Override public _FinalStage addAllGenerations(List generations) { - this.generations.addAll(generations); + if (generations != null) { + this.generations.addAll(generations); + } return this; } @@ -205,7 +207,9 @@ public _FinalStage addGenerations(SingleGeneration generations) { @JsonSetter(value = "generations", nulls = Nulls.SKIP) public _FinalStage generations(List generations) { this.generations.clear(); - this.generations.addAll(generations); + if (generations != null) { + this.generations.addAll(generations); + } return this; } diff --git a/src/main/java/com/cohere/api/types/GetModelResponse.java b/src/main/java/com/cohere/api/types/GetModelResponse.java index bd067c6..da79af7 100644 --- a/src/main/java/com/cohere/api/types/GetModelResponse.java +++ b/src/main/java/com/cohere/api/types/GetModelResponse.java @@ -33,8 +33,6 @@ public final class GetModelResponse { private final Optional tokenizerUrl; - private final Optional supportsVision; - private final Optional> defaultEndpoints; private final Optional> features; @@ -48,7 +46,6 @@ private GetModelResponse( Optional finetuned, Optional contextLength, Optional tokenizerUrl, - Optional supportsVision, Optional> defaultEndpoints, Optional> features, Map additionalProperties) { @@ -58,7 +55,6 @@ private GetModelResponse( this.finetuned = finetuned; this.contextLength = contextLength; this.tokenizerUrl = tokenizerUrl; - this.supportsVision = supportsVision; this.defaultEndpoints = defaultEndpoints; this.features = features; this.additionalProperties = additionalProperties; @@ -112,14 +108,6 @@ public Optional getTokenizerUrl() { return tokenizerUrl; } - /** - * @return Whether the model supports image inputs or not. - */ - @JsonProperty("supports_vision") - public Optional getSupportsVision() { - return supportsVision; - } - /** * @return The API endpoints that the model is default to. */ @@ -154,7 +142,6 @@ private boolean equalTo(GetModelResponse other) { && finetuned.equals(other.finetuned) && contextLength.equals(other.contextLength) && tokenizerUrl.equals(other.tokenizerUrl) - && supportsVision.equals(other.supportsVision) && defaultEndpoints.equals(other.defaultEndpoints) && features.equals(other.features); } @@ -168,7 +155,6 @@ public int hashCode() { this.finetuned, this.contextLength, this.tokenizerUrl, - this.supportsVision, this.defaultEndpoints, this.features); } @@ -196,8 +182,6 @@ public static final class Builder { private Optional tokenizerUrl = Optional.empty(); - private Optional supportsVision = Optional.empty(); - private Optional> defaultEndpoints = Optional.empty(); private Optional> features = Optional.empty(); @@ -214,7 +198,6 @@ public Builder from(GetModelResponse other) { finetuned(other.getFinetuned()); contextLength(other.getContextLength()); tokenizerUrl(other.getTokenizerUrl()); - supportsVision(other.getSupportsVision()); defaultEndpoints(other.getDefaultEndpoints()); features(other.getFeatures()); return this; @@ -304,20 +287,6 @@ public Builder tokenizerUrl(String tokenizerUrl) { return this; } - /** - *

Whether the model supports image inputs or not.

- */ - @JsonSetter(value = "supports_vision", nulls = Nulls.SKIP) - public Builder supportsVision(Optional supportsVision) { - this.supportsVision = supportsVision; - return this; - } - - public Builder supportsVision(Boolean supportsVision) { - this.supportsVision = Optional.ofNullable(supportsVision); - return this; - } - /** *

The API endpoints that the model is default to.

*/ @@ -354,7 +323,6 @@ public GetModelResponse build() { finetuned, contextLength, tokenizerUrl, - supportsVision, defaultEndpoints, features, additionalProperties); diff --git a/src/main/java/com/cohere/api/types/ImageUrlDetail.java b/src/main/java/com/cohere/api/types/ImageUrlDetail.java index c74524f..aff0406 100644 --- a/src/main/java/com/cohere/api/types/ImageUrlDetail.java +++ b/src/main/java/com/cohere/api/types/ImageUrlDetail.java @@ -3,24 +3,91 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ImageUrlDetail { - AUTO("auto"), +public final class ImageUrlDetail { + public static final ImageUrlDetail LOW = new ImageUrlDetail(Value.LOW, "low"); - LOW("low"), + public static final ImageUrlDetail AUTO = new ImageUrlDetail(Value.AUTO, "auto"); - HIGH("high"); + public static final ImageUrlDetail HIGH = new ImageUrlDetail(Value.HIGH, "high"); - private final String value; + private final Value value; - ImageUrlDetail(String value) { + private final String string; + + ImageUrlDetail(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof ImageUrlDetail && this.string.equals(((ImageUrlDetail) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case LOW: + return visitor.visitLow(); + case AUTO: + return visitor.visitAuto(); + case HIGH: + return visitor.visitHigh(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ImageUrlDetail valueOf(String value) { + switch (value) { + case "low": + return LOW; + case "auto": + return AUTO; + case "high": + return HIGH; + default: + return new ImageUrlDetail(Value.UNKNOWN, value); + } + } + + public enum Value { + AUTO, + + LOW, + + HIGH, + + UNKNOWN + } + + public interface Visitor { + T visitAuto(); + + T visitLow(); + + T visitHigh(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/ListConnectorsResponse.java b/src/main/java/com/cohere/api/types/ListConnectorsResponse.java index 32bfe06..c84e990 100644 --- a/src/main/java/com/cohere/api/types/ListConnectorsResponse.java +++ b/src/main/java/com/cohere/api/types/ListConnectorsResponse.java @@ -97,7 +97,9 @@ public Builder from(ListConnectorsResponse other) { @JsonSetter(value = "connectors", nulls = Nulls.SKIP) public Builder connectors(List connectors) { this.connectors.clear(); - this.connectors.addAll(connectors); + if (connectors != null) { + this.connectors.addAll(connectors); + } return this; } @@ -107,7 +109,9 @@ public Builder addConnectors(Connector connectors) { } public Builder addAllConnectors(List connectors) { - this.connectors.addAll(connectors); + if (connectors != null) { + this.connectors.addAll(connectors); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ListModelsResponse.java b/src/main/java/com/cohere/api/types/ListModelsResponse.java index d0b7c91..c3f70f9 100644 --- a/src/main/java/com/cohere/api/types/ListModelsResponse.java +++ b/src/main/java/com/cohere/api/types/ListModelsResponse.java @@ -97,7 +97,9 @@ public Builder from(ListModelsResponse other) { @JsonSetter(value = "models", nulls = Nulls.SKIP) public Builder models(List models) { this.models.clear(); - this.models.addAll(models); + if (models != null) { + this.models.addAll(models); + } return this; } @@ -107,7 +109,9 @@ public Builder addModels(GetModelResponse models) { } public Builder addAllModels(List models) { - this.models.addAll(models); + if (models != null) { + this.models.addAll(models); + } return this; } diff --git a/src/main/java/com/cohere/api/types/LogprobItem.java b/src/main/java/com/cohere/api/types/LogprobItem.java index eff8c7b..c69f863 100644 --- a/src/main/java/com/cohere/api/types/LogprobItem.java +++ b/src/main/java/com/cohere/api/types/LogprobItem.java @@ -134,7 +134,9 @@ public Builder text(String text) { @JsonSetter(value = "token_ids", nulls = Nulls.SKIP) public Builder tokenIds(List tokenIds) { this.tokenIds.clear(); - this.tokenIds.addAll(tokenIds); + if (tokenIds != null) { + this.tokenIds.addAll(tokenIds); + } return this; } @@ -144,7 +146,9 @@ public Builder addTokenIds(Integer tokenIds) { } public Builder addAllTokenIds(List tokenIds) { - this.tokenIds.addAll(tokenIds); + if (tokenIds != null) { + this.tokenIds.addAll(tokenIds); + } return this; } diff --git a/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java b/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java index 0daa723..bcd0de9 100644 --- a/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java +++ b/src/main/java/com/cohere/api/types/RerankRequestDocumentsItem.java @@ -85,11 +85,11 @@ public RerankRequestDocumentsItem deserialize(JsonParser p, DeserializationConte Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/cohere/api/types/RerankResponse.java b/src/main/java/com/cohere/api/types/RerankResponse.java index e399257..b36f676 100644 --- a/src/main/java/com/cohere/api/types/RerankResponse.java +++ b/src/main/java/com/cohere/api/types/RerankResponse.java @@ -125,7 +125,9 @@ public Builder id(String id) { @JsonSetter(value = "results", nulls = Nulls.SKIP) public Builder results(List results) { this.results.clear(); - this.results.addAll(results); + if (results != null) { + this.results.addAll(results); + } return this; } @@ -135,7 +137,9 @@ public Builder addResults(RerankResponseResultsItem results) { } public Builder addAllResults(List results) { - this.results.addAll(results); + if (results != null) { + this.results.addAll(results); + } return this; } diff --git a/src/main/java/com/cohere/api/types/SummarizeRequestExtractiveness.java b/src/main/java/com/cohere/api/types/SummarizeRequestExtractiveness.java index cad2968..0170ffd 100644 --- a/src/main/java/com/cohere/api/types/SummarizeRequestExtractiveness.java +++ b/src/main/java/com/cohere/api/types/SummarizeRequestExtractiveness.java @@ -3,24 +3,93 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum SummarizeRequestExtractiveness { - LOW("low"), +public final class SummarizeRequestExtractiveness { + public static final SummarizeRequestExtractiveness MEDIUM = + new SummarizeRequestExtractiveness(Value.MEDIUM, "medium"); - MEDIUM("medium"), + public static final SummarizeRequestExtractiveness LOW = new SummarizeRequestExtractiveness(Value.LOW, "low"); - HIGH("high"); + public static final SummarizeRequestExtractiveness HIGH = new SummarizeRequestExtractiveness(Value.HIGH, "high"); - private final String value; + private final Value value; - SummarizeRequestExtractiveness(String value) { + private final String string; + + SummarizeRequestExtractiveness(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof SummarizeRequestExtractiveness + && this.string.equals(((SummarizeRequestExtractiveness) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case MEDIUM: + return visitor.visitMedium(); + case LOW: + return visitor.visitLow(); + case HIGH: + return visitor.visitHigh(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static SummarizeRequestExtractiveness valueOf(String value) { + switch (value) { + case "medium": + return MEDIUM; + case "low": + return LOW; + case "high": + return HIGH; + default: + return new SummarizeRequestExtractiveness(Value.UNKNOWN, value); + } + } + + public enum Value { + LOW, + + MEDIUM, + + HIGH, + + UNKNOWN + } + + public interface Visitor { + T visitLow(); + + T visitMedium(); + + T visitHigh(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/SummarizeRequestFormat.java b/src/main/java/com/cohere/api/types/SummarizeRequestFormat.java index 8be83d8..4c38a6c 100644 --- a/src/main/java/com/cohere/api/types/SummarizeRequestFormat.java +++ b/src/main/java/com/cohere/api/types/SummarizeRequestFormat.java @@ -3,22 +3,82 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum SummarizeRequestFormat { - PARAGRAPH("paragraph"), +public final class SummarizeRequestFormat { + public static final SummarizeRequestFormat BULLETS = new SummarizeRequestFormat(Value.BULLETS, "bullets"); - BULLETS("bullets"); + public static final SummarizeRequestFormat PARAGRAPH = new SummarizeRequestFormat(Value.PARAGRAPH, "paragraph"); - private final String value; + private final Value value; - SummarizeRequestFormat(String value) { + private final String string; + + SummarizeRequestFormat(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof SummarizeRequestFormat + && this.string.equals(((SummarizeRequestFormat) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case BULLETS: + return visitor.visitBullets(); + case PARAGRAPH: + return visitor.visitParagraph(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static SummarizeRequestFormat valueOf(String value) { + switch (value) { + case "bullets": + return BULLETS; + case "paragraph": + return PARAGRAPH; + default: + return new SummarizeRequestFormat(Value.UNKNOWN, value); + } + } + + public enum Value { + PARAGRAPH, + + BULLETS, + + UNKNOWN + } + + public interface Visitor { + T visitParagraph(); + + T visitBullets(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/SummarizeRequestLength.java b/src/main/java/com/cohere/api/types/SummarizeRequestLength.java index fd552e2..6ce8e50 100644 --- a/src/main/java/com/cohere/api/types/SummarizeRequestLength.java +++ b/src/main/java/com/cohere/api/types/SummarizeRequestLength.java @@ -3,24 +3,92 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum SummarizeRequestLength { - SHORT("short"), +public final class SummarizeRequestLength { + public static final SummarizeRequestLength LONG = new SummarizeRequestLength(Value.LONG, "long"); - MEDIUM("medium"), + public static final SummarizeRequestLength MEDIUM = new SummarizeRequestLength(Value.MEDIUM, "medium"); - LONG("long"); + public static final SummarizeRequestLength SHORT = new SummarizeRequestLength(Value.SHORT, "short"); - private final String value; + private final Value value; - SummarizeRequestLength(String value) { + private final String string; + + SummarizeRequestLength(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) + || (other instanceof SummarizeRequestLength + && this.string.equals(((SummarizeRequestLength) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case LONG: + return visitor.visitLong(); + case MEDIUM: + return visitor.visitMedium(); + case SHORT: + return visitor.visitShort(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static SummarizeRequestLength valueOf(String value) { + switch (value) { + case "long": + return LONG; + case "medium": + return MEDIUM; + case "short": + return SHORT; + default: + return new SummarizeRequestLength(Value.UNKNOWN, value); + } + } + + public enum Value { + SHORT, + + MEDIUM, + + LONG, + + UNKNOWN + } + + public interface Visitor { + T visitShort(); + + T visitMedium(); + + T visitLong(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/SystemMessageV2Content.java b/src/main/java/com/cohere/api/types/SystemMessageV2Content.java index ba0cf55..2803cbd 100644 --- a/src/main/java/com/cohere/api/types/SystemMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/SystemMessageV2Content.java @@ -85,12 +85,12 @@ public SystemMessageV2Content deserialize(JsonParser p, DeserializationContext c Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue( value, new TypeReference>() {})); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/cohere/api/types/ThinkingType.java b/src/main/java/com/cohere/api/types/ThinkingType.java index dff8242..fb26171 100644 --- a/src/main/java/com/cohere/api/types/ThinkingType.java +++ b/src/main/java/com/cohere/api/types/ThinkingType.java @@ -3,22 +3,80 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ThinkingType { - ENABLED("enabled"), +public final class ThinkingType { + public static final ThinkingType ENABLED = new ThinkingType(Value.ENABLED, "enabled"); - DISABLED("disabled"); + public static final ThinkingType DISABLED = new ThinkingType(Value.DISABLED, "disabled"); - private final String value; + private final Value value; - ThinkingType(String value) { + private final String string; + + ThinkingType(Value value, String string) { this.value = value; + this.string = string; + } + + public Value getEnumValue() { + return value; } - @JsonValue @java.lang.Override + @JsonValue public String toString() { - return this.value; + return this.string; + } + + @java.lang.Override + public boolean equals(Object other) { + return (this == other) || (other instanceof ThinkingType && this.string.equals(((ThinkingType) other).string)); + } + + @java.lang.Override + public int hashCode() { + return this.string.hashCode(); + } + + public T visit(Visitor visitor) { + switch (value) { + case ENABLED: + return visitor.visitEnabled(); + case DISABLED: + return visitor.visitDisabled(); + case UNKNOWN: + default: + return visitor.visitUnknown(string); + } + } + + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) + public static ThinkingType valueOf(String value) { + switch (value) { + case "enabled": + return ENABLED; + case "disabled": + return DISABLED; + default: + return new ThinkingType(Value.UNKNOWN, value); + } + } + + public enum Value { + ENABLED, + + DISABLED, + + UNKNOWN + } + + public interface Visitor { + T visitEnabled(); + + T visitDisabled(); + + T visitUnknown(String unknownType); } } diff --git a/src/main/java/com/cohere/api/types/TokenizeResponse.java b/src/main/java/com/cohere/api/types/TokenizeResponse.java index 031661e..07a2505 100644 --- a/src/main/java/com/cohere/api/types/TokenizeResponse.java +++ b/src/main/java/com/cohere/api/types/TokenizeResponse.java @@ -114,7 +114,9 @@ public Builder from(TokenizeResponse other) { @JsonSetter(value = "tokens", nulls = Nulls.SKIP) public Builder tokens(List tokens) { this.tokens.clear(); - this.tokens.addAll(tokens); + if (tokens != null) { + this.tokens.addAll(tokens); + } return this; } @@ -124,14 +126,18 @@ public Builder addTokens(Integer tokens) { } public Builder addAllTokens(List tokens) { - this.tokens.addAll(tokens); + if (tokens != null) { + this.tokens.addAll(tokens); + } return this; } @JsonSetter(value = "token_strings", nulls = Nulls.SKIP) public Builder tokenStrings(List tokenStrings) { this.tokenStrings.clear(); - this.tokenStrings.addAll(tokenStrings); + if (tokenStrings != null) { + this.tokenStrings.addAll(tokenStrings); + } return this; } @@ -141,7 +147,9 @@ public Builder addTokenStrings(String tokenStrings) { } public Builder addAllTokenStrings(List tokenStrings) { - this.tokenStrings.addAll(tokenStrings); + if (tokenStrings != null) { + this.tokenStrings.addAll(tokenStrings); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ToolCall.java b/src/main/java/com/cohere/api/types/ToolCall.java index 3805f60..f8a08d8 100644 --- a/src/main/java/com/cohere/api/types/ToolCall.java +++ b/src/main/java/com/cohere/api/types/ToolCall.java @@ -146,7 +146,9 @@ public _FinalStage parameters(String key, Object value) { */ @java.lang.Override public _FinalStage putAllParameters(Map parameters) { - this.parameters.putAll(parameters); + if (parameters != null) { + this.parameters.putAll(parameters); + } return this; } @@ -157,7 +159,9 @@ public _FinalStage putAllParameters(Map parameters) { @JsonSetter(value = "parameters", nulls = Nulls.SKIP) public _FinalStage parameters(Map parameters) { this.parameters.clear(); - this.parameters.putAll(parameters); + if (parameters != null) { + this.parameters.putAll(parameters); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ToolCallV2.java b/src/main/java/com/cohere/api/types/ToolCallV2.java index ac097ab..9181ce9 100644 --- a/src/main/java/com/cohere/api/types/ToolCallV2.java +++ b/src/main/java/com/cohere/api/types/ToolCallV2.java @@ -16,37 +16,31 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import org.jetbrains.annotations.NotNull; @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = ToolCallV2.Builder.class) public final class ToolCallV2 { - private final Optional id; - - private final Optional type; + private final String id; private final Optional function; private final Map additionalProperties; - private ToolCallV2( - Optional id, - Optional type, - Optional function, - Map additionalProperties) { + private ToolCallV2(String id, Optional function, Map additionalProperties) { this.id = id; - this.type = type; this.function = function; this.additionalProperties = additionalProperties; } @JsonProperty("id") - public Optional getId() { + public String getId() { return id; } @JsonProperty("type") - public Optional getType() { - return type; + public String getType() { + return "function"; } @JsonProperty("function") @@ -66,12 +60,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(ToolCallV2 other) { - return id.equals(other.id) && type.equals(other.type) && function.equals(other.function); + return id.equals(other.id) && function.equals(other.function); } @java.lang.Override public int hashCode() { - return Objects.hash(this.id, this.type, this.function); + return Objects.hash(this.id, this.function); } @java.lang.Override @@ -79,15 +73,27 @@ public String toString() { return ObjectMappers.stringify(this); } - public static Builder builder() { + public static IdStage builder() { return new Builder(); } - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional id = Optional.empty(); + public interface IdStage { + _FinalStage id(@NotNull String id); + + Builder from(ToolCallV2 other); + } + + public interface _FinalStage { + ToolCallV2 build(); - private Optional type = Optional.empty(); + _FinalStage function(Optional function); + + _FinalStage function(ToolCallV2Function function); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements IdStage, _FinalStage { + private String id; private Optional function = Optional.empty(); @@ -96,48 +102,36 @@ public static final class Builder { private Builder() {} + @java.lang.Override public Builder from(ToolCallV2 other) { id(other.getId()); - type(other.getType()); function(other.getFunction()); return this; } - @JsonSetter(value = "id", nulls = Nulls.SKIP) - public Builder id(Optional id) { - this.id = id; - return this; - } - - public Builder id(String id) { - this.id = Optional.ofNullable(id); - return this; - } - - @JsonSetter(value = "type", nulls = Nulls.SKIP) - public Builder type(Optional type) { - this.type = type; + @java.lang.Override + @JsonSetter("id") + public _FinalStage id(@NotNull String id) { + this.id = Objects.requireNonNull(id, "id must not be null"); return this; } - public Builder type(String type) { - this.type = Optional.ofNullable(type); + @java.lang.Override + public _FinalStage function(ToolCallV2Function function) { + this.function = Optional.ofNullable(function); return this; } + @java.lang.Override @JsonSetter(value = "function", nulls = Nulls.SKIP) - public Builder function(Optional function) { + public _FinalStage function(Optional function) { this.function = function; return this; } - public Builder function(ToolCallV2Function function) { - this.function = Optional.ofNullable(function); - return this; - } - + @java.lang.Override public ToolCallV2 build() { - return new ToolCallV2(id, type, function, additionalProperties); + return new ToolCallV2(id, function, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/ToolMessageV2Content.java b/src/main/java/com/cohere/api/types/ToolMessageV2Content.java index 67b1e9f..8c59cd0 100644 --- a/src/main/java/com/cohere/api/types/ToolMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/ToolMessageV2Content.java @@ -85,11 +85,11 @@ public ToolMessageV2Content deserialize(JsonParser p, DeserializationContext con Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); } diff --git a/src/main/java/com/cohere/api/types/ToolResult.java b/src/main/java/com/cohere/api/types/ToolResult.java index b4eeb45..5385b67 100644 --- a/src/main/java/com/cohere/api/types/ToolResult.java +++ b/src/main/java/com/cohere/api/types/ToolResult.java @@ -116,7 +116,9 @@ public _FinalStage call(@NotNull ToolCall call) { @java.lang.Override public _FinalStage addAllOutputs(List> outputs) { - this.outputs.addAll(outputs); + if (outputs != null) { + this.outputs.addAll(outputs); + } return this; } @@ -130,7 +132,9 @@ public _FinalStage addOutputs(Map outputs) { @JsonSetter(value = "outputs", nulls = Nulls.SKIP) public _FinalStage outputs(List> outputs) { this.outputs.clear(); - this.outputs.addAll(outputs); + if (outputs != null) { + this.outputs.addAll(outputs); + } return this; } diff --git a/src/main/java/com/cohere/api/types/ToolV2.java b/src/main/java/com/cohere/api/types/ToolV2.java index 38c6063..e3b09dd 100644 --- a/src/main/java/com/cohere/api/types/ToolV2.java +++ b/src/main/java/com/cohere/api/types/ToolV2.java @@ -20,21 +20,18 @@ @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = ToolV2.Builder.class) public final class ToolV2 { - private final Optional type; - private final Optional function; private final Map additionalProperties; - private ToolV2(Optional type, Optional function, Map additionalProperties) { - this.type = type; + private ToolV2(Optional function, Map additionalProperties) { this.function = function; this.additionalProperties = additionalProperties; } @JsonProperty("type") - public Optional getType() { - return type; + public String getType() { + return "function"; } /** @@ -57,12 +54,12 @@ public Map getAdditionalProperties() { } private boolean equalTo(ToolV2 other) { - return type.equals(other.type) && function.equals(other.function); + return function.equals(other.function); } @java.lang.Override public int hashCode() { - return Objects.hash(this.type, this.function); + return Objects.hash(this.function); } @java.lang.Override @@ -76,8 +73,6 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { - private Optional type = Optional.empty(); - private Optional function = Optional.empty(); @JsonAnySetter @@ -86,22 +81,10 @@ public static final class Builder { private Builder() {} public Builder from(ToolV2 other) { - type(other.getType()); function(other.getFunction()); return this; } - @JsonSetter(value = "type", nulls = Nulls.SKIP) - public Builder type(Optional type) { - this.type = type; - return this; - } - - public Builder type(String type) { - this.type = Optional.ofNullable(type); - return this; - } - /** *

The function to be executed.

*/ @@ -117,7 +100,7 @@ public Builder function(ToolV2Function function) { } public ToolV2 build() { - return new ToolV2(type, function, additionalProperties); + return new ToolV2(function, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/ToolV2Function.java b/src/main/java/com/cohere/api/types/ToolV2Function.java index 9af8fac..16b14a1 100644 --- a/src/main/java/com/cohere/api/types/ToolV2Function.java +++ b/src/main/java/com/cohere/api/types/ToolV2Function.java @@ -172,7 +172,9 @@ public _FinalStage parameters(String key, Object value) { */ @java.lang.Override public _FinalStage putAllParameters(Map parameters) { - this.parameters.putAll(parameters); + if (parameters != null) { + this.parameters.putAll(parameters); + } return this; } @@ -183,7 +185,9 @@ public _FinalStage putAllParameters(Map parameters) { @JsonSetter(value = "parameters", nulls = Nulls.SKIP) public _FinalStage parameters(Map parameters) { this.parameters.clear(); - this.parameters.putAll(parameters); + if (parameters != null) { + this.parameters.putAll(parameters); + } return this; } diff --git a/src/main/java/com/cohere/api/types/Usage.java b/src/main/java/com/cohere/api/types/Usage.java index 331d08b..ab9464e 100644 --- a/src/main/java/com/cohere/api/types/Usage.java +++ b/src/main/java/com/cohere/api/types/Usage.java @@ -24,14 +24,18 @@ public final class Usage { private final Optional tokens; + private final Optional cachedTokens; + private final Map additionalProperties; private Usage( Optional billedUnits, Optional tokens, + Optional cachedTokens, Map additionalProperties) { this.billedUnits = billedUnits; this.tokens = tokens; + this.cachedTokens = cachedTokens; this.additionalProperties = additionalProperties; } @@ -45,6 +49,14 @@ public Optional getTokens() { return tokens; } + /** + * @return The number of prompt tokens that hit the inference cache. + */ + @JsonProperty("cached_tokens") + public Optional getCachedTokens() { + return cachedTokens; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; @@ -57,12 +69,14 @@ public Map getAdditionalProperties() { } private boolean equalTo(Usage other) { - return billedUnits.equals(other.billedUnits) && tokens.equals(other.tokens); + return billedUnits.equals(other.billedUnits) + && tokens.equals(other.tokens) + && cachedTokens.equals(other.cachedTokens); } @java.lang.Override public int hashCode() { - return Objects.hash(this.billedUnits, this.tokens); + return Objects.hash(this.billedUnits, this.tokens, this.cachedTokens); } @java.lang.Override @@ -80,6 +94,8 @@ public static final class Builder { private Optional tokens = Optional.empty(); + private Optional cachedTokens = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -88,6 +104,7 @@ private Builder() {} public Builder from(Usage other) { billedUnits(other.getBilledUnits()); tokens(other.getTokens()); + cachedTokens(other.getCachedTokens()); return this; } @@ -113,8 +130,22 @@ public Builder tokens(UsageTokens tokens) { return this; } + /** + *

The number of prompt tokens that hit the inference cache.

+ */ + @JsonSetter(value = "cached_tokens", nulls = Nulls.SKIP) + public Builder cachedTokens(Optional cachedTokens) { + this.cachedTokens = cachedTokens; + return this; + } + + public Builder cachedTokens(Double cachedTokens) { + this.cachedTokens = Optional.ofNullable(cachedTokens); + return this; + } + public Usage build() { - return new Usage(billedUnits, tokens, additionalProperties); + return new Usage(billedUnits, tokens, cachedTokens, additionalProperties); } } } diff --git a/src/main/java/com/cohere/api/types/UserMessageV2Content.java b/src/main/java/com/cohere/api/types/UserMessageV2Content.java index 3862999..acde60f 100644 --- a/src/main/java/com/cohere/api/types/UserMessageV2Content.java +++ b/src/main/java/com/cohere/api/types/UserMessageV2Content.java @@ -85,11 +85,11 @@ public UserMessageV2Content deserialize(JsonParser p, DeserializationContext con Object value = p.readValueAs(Object.class); try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, String.class)); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } try { return of(ObjectMappers.JSON_MAPPER.convertValue(value, new TypeReference>() {})); - } catch (IllegalArgumentException e) { + } catch (RuntimeException e) { } throw new JsonParseException(p, "Failed to deserialize"); }