diff --git a/.fern/metadata.json b/.fern/metadata.json new file mode 100644 index 0000000..71d1ec6 --- /dev/null +++ b/.fern/metadata.json @@ -0,0 +1,8 @@ +{ + "cliVersion": "0.112.1", + "generatorName": "fernapi/fern-java-sdk", + "generatorVersion": "3.14.2", + "generatorConfig": { + "client-class-name": "Cohere" + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 3c5788d..eb378aa 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.9.2' +version = '1.9.3' jar { dependsOn(":generatePomFileForMavenPublication") @@ -77,7 +78,7 @@ publishing { maven(MavenPublication) { groupId = 'com.cohere' artifactId = 'cohere-java' - version = '1.9.2' + version = '1.9.3' 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 3468658..578cd07 100644 --- a/reference.md +++ b/reference.md @@ -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`. @@ -746,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`. @@ -786,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`. @@ -800,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`. @@ -1037,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`. @@ -1100,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`. @@ -1111,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. @@ -1123,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`. @@ -1288,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`. @@ -1351,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`. @@ -1362,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. @@ -1374,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`. @@ -1449,7 +1449,7 @@ client.embed( EmbedRequest .builder() .texts( - new ArrayList( + Optional.of( Arrays.asList("hello", "goodbye") ) ) @@ -1574,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?") @@ -1705,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() @@ -1929,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.
@@ -2048,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() @@ -2163,16 +2157,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() ) ) ) @@ -2460,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() ) ) ) @@ -2760,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) ) ) @@ -2927,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") @@ -3617,7 +3605,7 @@ client.datasets().list(
-**limit:** `Optional` — optional limit to number of results +**limit:** `Optional` — optional limit to number of results
@@ -3625,7 +3613,7 @@ client.datasets().list(
-**offset:** `Optional` — optional offset to start of results +**offset:** `Optional` — optional offset to start of results
@@ -3961,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].
@@ -3969,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].
@@ -4493,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`. diff --git a/src/main/java/com/cohere/api/AsyncCohereBuilder.java b/src/main/java/com/cohere/api/AsyncCohereBuilder.java index 231aa21..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(); } 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/CohereBuilder.java b/src/main/java/com/cohere/api/CohereBuilder.java index 041d384..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(); } 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..1333deb 100644 --- a/src/main/java/com/cohere/api/core/ClientOptions.java +++ b/src/main/java/com/cohere/api/core/ClientOptions.java @@ -21,26 +21,30 @@ public final class ClientOptions { private final int timeout; + private final int maxRetries; + private ClientOptions( Environment environment, Map headers, Map> headerSuppliers, OkHttpClient httpClient, - int timeout) { + int timeout, + int maxRetries) { this.environment = environment; this.headers = new HashMap<>(); 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.3"); 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.3"); } }); this.headerSuppliers = headerSuppliers; this.httpClient = httpClient; this.timeout = timeout; + this.maxRetries = maxRetries; } public Environment environment() { @@ -82,6 +86,10 @@ public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) { .build(); } + public int maxRetries() { + return this.maxRetries; + } + public static Builder builder() { return new Builder(); } @@ -165,7 +173,8 @@ public ClientOptions build() { this.httpClient = httpClientBuilder.build(); this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); - return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get()); + return new ClientOptions( + environment, headers, headerSuppliers, httpClient, this.timeout.get(), this.maxRetries); } /** 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/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/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/AsyncRawBatchesClient.java b/src/main/java/com/cohere/api/resources/batches/AsyncRawBatchesClient.java index 8983224..7b1d79d 100644 --- a/src/main/java/com/cohere/api/resources/batches/AsyncRawBatchesClient.java +++ b/src/main/java/com/cohere/api/resources/batches/AsyncRawBatchesClient.java @@ -94,13 +94,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(), ListBatchesResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListBatchesResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -137,11 +137,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)); @@ -195,13 +193,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(), CreateBatchResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateBatchResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -238,11 +236,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)); @@ -288,13 +284,13 @@ public CompletableFuture> retrieve(String i @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(), GetBatchResponse.class), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetBatchResponse.class), response)); return; } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -331,11 +327,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)); @@ -382,14 +376,14 @@ public CompletableFuture>> cancel(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: @@ -426,11 +420,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/batches/RawBatchesClient.java b/src/main/java/com/cohere/api/resources/batches/RawBatchesClient.java index 374cf81..6dfed17 100644 --- a/src/main/java/com/cohere/api/resources/batches/RawBatchesClient.java +++ b/src/main/java/com/cohere/api/resources/batches/RawBatchesClient.java @@ -87,12 +87,11 @@ 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(), ListBatchesResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ListBatchesResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -117,11 +116,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); } @@ -162,12 +159,11 @@ public CohereHttpResponse create(Batch 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(), CreateBatchResponse.class), - response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, CreateBatchResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -192,11 +188,9 @@ public CohereHttpResponse create(Batch 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); } @@ -230,11 +224,11 @@ public CohereHttpResponse retrieve(String id, RequestOptions 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(), GetBatchResponse.class), response); + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, GetBatchResponse.class), response); } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; try { switch (response.code()) { case 400: @@ -259,11 +253,9 @@ public CohereHttpResponse retrieve(String id, RequestOptions 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); } @@ -298,13 +290,13 @@ public CohereHttpResponse> cancel(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: @@ -329,11 +321,9 @@ public CohereHttpResponse> cancel(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/batches/types/BatchStatus.java b/src/main/java/com/cohere/api/resources/batches/types/BatchStatus.java index e0dd5f1..5688c1c 100644 --- a/src/main/java/com/cohere/api/resources/batches/types/BatchStatus.java +++ b/src/main/java/com/cohere/api/resources/batches/types/BatchStatus.java @@ -3,32 +3,137 @@ */ package com.cohere.api.resources.batches.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum BatchStatus { - BATCH_STATUS_UNSPECIFIED("BATCH_STATUS_UNSPECIFIED"), +public final class BatchStatus { + public static final BatchStatus BATCH_STATUS_QUEUED = + new BatchStatus(Value.BATCH_STATUS_QUEUED, "BATCH_STATUS_QUEUED"); - 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"); - BATCH_STATUS_IN_PROGRESS("BATCH_STATUS_IN_PROGRESS"), + public static final BatchStatus BATCH_STATUS_UNSPECIFIED = + new BatchStatus(Value.BATCH_STATUS_UNSPECIFIED, "BATCH_STATUS_UNSPECIFIED"); - BATCH_STATUS_CANCELING("BATCH_STATUS_CANCELING"), + public static final BatchStatus BATCH_STATUS_FAILED = + new BatchStatus(Value.BATCH_STATUS_FAILED, "BATCH_STATUS_FAILED"); - BATCH_STATUS_COMPLETED("BATCH_STATUS_COMPLETED"), + public static final BatchStatus BATCH_STATUS_CANCELING = + new BatchStatus(Value.BATCH_STATUS_CANCELING, "BATCH_STATUS_CANCELING"); - BATCH_STATUS_FAILED("BATCH_STATUS_FAILED"), + public static final BatchStatus BATCH_STATUS_CANCELED = + new BatchStatus(Value.BATCH_STATUS_CANCELED, "BATCH_STATUS_CANCELED"); - BATCH_STATUS_CANCELED("BATCH_STATUS_CANCELED"); + public static final BatchStatus BATCH_STATUS_COMPLETED = + new BatchStatus(Value.BATCH_STATUS_COMPLETED, "BATCH_STATUS_COMPLETED"); - private final String value; + private final Value value; - BatchStatus(String value) { + private final String string; + + BatchStatus(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 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/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/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/AsyncRawModelsClient.java b/src/main/java/com/cohere/api/resources/models/AsyncRawModelsClient.java index 1746203..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)); @@ -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/RawModelsClient.java b/src/main/java/com/cohere/api/resources/models/RawModelsClient.java index 861f471..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,11 +116,9 @@ 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); } @@ -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 04007e7..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 @@ -989,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; } @@ -1003,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; } 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 2e6ab7b..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 @@ -989,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; } @@ -1003,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; } 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 53d5108..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 @@ -319,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; } @@ -346,7 +348,9 @@ 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; } 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/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 a692121..d50b09f 100644 --- a/src/main/java/com/cohere/api/types/ChatFinishReason.java +++ b/src/main/java/com/cohere/api/types/ChatFinishReason.java @@ -3,30 +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"); - TIMEOUT("TIMEOUT"); + public static final ChatFinishReason ERROR = new ChatFinishReason(Value.ERROR, "ERROR"); - private final String value; + private final Value value; - ChatFinishReason(String 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 77abb7f..c29b4f0 100644 --- a/src/main/java/com/cohere/api/types/ChatRequestCitationQuality.java +++ b/src/main/java/com/cohere/api/types/ChatRequestCitationQuality.java @@ -3,28 +3,114 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatRequestCitationQuality { - ENABLED("ENABLED"), +public final class ChatRequestCitationQuality { + public static final ChatRequestCitationQuality FAST = new ChatRequestCitationQuality(Value.FAST, "FAST"); - DISABLED("DISABLED"), + public static final ChatRequestCitationQuality DISABLED = + new ChatRequestCitationQuality(Value.DISABLED, "DISABLED"); - FAST("FAST"), + public static final ChatRequestCitationQuality ENABLED = new ChatRequestCitationQuality(Value.ENABLED, "ENABLED"); - ACCURATE("ACCURATE"), + public static final ChatRequestCitationQuality OFF = new ChatRequestCitationQuality(Value.OFF, "OFF"); - OFF("OFF"); + public static final ChatRequestCitationQuality ACCURATE = + new ChatRequestCitationQuality(Value.ACCURATE, "ACCURATE"); - private final String value; + private final Value value; - ChatRequestCitationQuality(String 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 7a3c415..10f3595 100644 --- a/src/main/java/com/cohere/api/types/ChatStreamRequestCitationQuality.java +++ b/src/main/java/com/cohere/api/types/ChatStreamRequestCitationQuality.java @@ -3,28 +3,116 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum ChatStreamRequestCitationQuality { - ENABLED("ENABLED"), +public final class ChatStreamRequestCitationQuality { + public static final ChatStreamRequestCitationQuality FAST = + new ChatStreamRequestCitationQuality(Value.FAST, "FAST"); - DISABLED("DISABLED"), + public static final ChatStreamRequestCitationQuality DISABLED = + new ChatStreamRequestCitationQuality(Value.DISABLED, "DISABLED"); - FAST("FAST"), + public static final ChatStreamRequestCitationQuality ENABLED = + new ChatStreamRequestCitationQuality(Value.ENABLED, "ENABLED"); - ACCURATE("ACCURATE"), + public static final ChatStreamRequestCitationQuality OFF = new ChatStreamRequestCitationQuality(Value.OFF, "OFF"); - OFF("OFF"); + public static final ChatStreamRequestCitationQuality ACCURATE = + new ChatStreamRequestCitationQuality(Value.ACCURATE, "ACCURATE"); - private final String value; + private final Value value; - ChatStreamRequestCitationQuality(String 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/CitationOptionsMode.java b/src/main/java/com/cohere/api/types/CitationOptionsMode.java index 12e8edd..2accb45 100644 --- a/src/main/java/com/cohere/api/types/CitationOptionsMode.java +++ b/src/main/java/com/cohere/api/types/CitationOptionsMode.java @@ -3,28 +3,111 @@ */ package com.cohere.api.types; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -public enum CitationOptionsMode { - ENABLED("ENABLED"), +public final class CitationOptionsMode { + public static final CitationOptionsMode FAST = new CitationOptionsMode(Value.FAST, "FAST"); - DISABLED("DISABLED"), + public static final CitationOptionsMode DISABLED = new CitationOptionsMode(Value.DISABLED, "DISABLED"); - FAST("FAST"), + public static final CitationOptionsMode ENABLED = new CitationOptionsMode(Value.ENABLED, "ENABLED"); - ACCURATE("ACCURATE"), + public static final CitationOptionsMode OFF = new CitationOptionsMode(Value.OFF, "OFF"); - OFF("OFF"); + public static final CitationOptionsMode ACCURATE = new CitationOptionsMode(Value.ACCURATE, "ACCURATE"); - private final String value; + private final Value value; - CitationOptionsMode(String 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 59c2173..fb510c4 100644 --- a/src/main/java/com/cohere/api/types/DatasetType.java +++ b/src/main/java/com/cohere/api/types/DatasetType.java @@ -3,42 +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"); - BATCH_CHAT_INPUT("batch-chat-input"), + public static final DatasetType BATCH_CHAT_V_2_INPUT = + new DatasetType(Value.BATCH_CHAT_V_2_INPUT, "batch-chat-v2-input"); - BATCH_OPENAI_CHAT_INPUT("batch-openai-chat-input"), + public static final DatasetType CLUSTER_RESULT = new DatasetType(Value.CLUSTER_RESULT, "cluster-result"); - BATCH_EMBED_V_2_INPUT("batch-embed-v2-input"), + public static final DatasetType CLUSTER_OUTLIERS = new DatasetType(Value.CLUSTER_OUTLIERS, "cluster-outliers"); - BATCH_CHAT_V_2_INPUT("batch-chat-v2-input"); + public static final DatasetType CHAT_FINETUNE_INPUT = + new DatasetType(Value.CHAT_FINETUNE_INPUT, "chat-finetune-input"); - private final String value; + private final Value value; - DatasetType(String 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 f07a3e4..d46a06b 100644 --- a/src/main/java/com/cohere/api/types/FinishReason.java +++ b/src/main/java/com/cohere/api/types/FinishReason.java @@ -3,34 +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"); - TIMEOUT("TIMEOUT"); + public static final FinishReason ERROR = new FinishReason(Value.ERROR, "ERROR"); - private final String value; + private final Value value; - FinishReason(String 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/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/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/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/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"); }